Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/include -I /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191=. -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 -o /tmp/scan-build-2020-11-21-121427-42170-1 -x c++ /build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/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_via_dependent_bases_lookup) << &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 ||
440 (*Res)->getLocation().getRawEncoding() <
441 IIDecl->getLocation().getRawEncoding())
442 IIDecl = *Res;
443 }
444 }
445
446 if (!IIDecl) {
447 // None of the entities we found is a type, so there is no way
448 // to even assume that the result is a type. In this case, don't
449 // complain about the ambiguity. The parser will either try to
450 // perform this lookup again (e.g., as an object name), which
451 // will produce the ambiguity, or will complain that it expected
452 // a type name.
453 Result.suppressDiagnostics();
454 return nullptr;
455 }
456
457 // We found a type within the ambiguous lookup; diagnose the
458 // ambiguity and then return that type. This might be the right
459 // answer, or it might not be, but it suppresses any attempt to
460 // perform the name lookup again.
461 break;
462
463 case LookupResult::Found:
464 IIDecl = Result.getFoundDecl();
465 break;
466 }
467
468 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 468, __PRETTY_FUNCTION__))
;
469
470 QualType T;
471 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
472 // C++ [class.qual]p2: A lookup that would find the injected-class-name
473 // instead names the constructors of the class, except when naming a class.
474 // This is ill-formed when we're not actually forming a ctor or dtor name.
475 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
476 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
477 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
478 FoundRD->isInjectedClassName() &&
479 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
480 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
481 << &II << /*Type*/1;
482
483 DiagnoseUseOfDecl(IIDecl, NameLoc);
484
485 T = Context.getTypeDeclType(TD);
486 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
487 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
488 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
489 if (!HasTrailingDot)
490 T = Context.getObjCInterfaceType(IDecl);
491 } else if (AllowDeducedTemplate) {
492 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
493 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
494 QualType(), false);
495 }
496
497 if (T.isNull()) {
498 // If it's not plausibly a type, suppress diagnostics.
499 Result.suppressDiagnostics();
500 return nullptr;
501 }
502
503 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
504 // constructor or destructor name (in such a case, the scope specifier
505 // will be attached to the enclosing Expr or Decl node).
506 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
507 !isa<ObjCInterfaceDecl>(IIDecl)) {
508 if (WantNontrivialTypeSourceInfo) {
509 // Construct a type with type-source information.
510 TypeLocBuilder Builder;
511 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
512
513 T = getElaboratedType(ETK_None, *SS, T);
514 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
515 ElabTL.setElaboratedKeywordLoc(SourceLocation());
516 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
517 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
518 } else {
519 T = getElaboratedType(ETK_None, *SS, T);
520 }
521 }
522
523 return ParsedType::make(T);
524}
525
526// Builds a fake NNS for the given decl context.
527static NestedNameSpecifier *
528synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
529 for (;; DC = DC->getLookupParent()) {
530 DC = DC->getPrimaryContext();
531 auto *ND = dyn_cast<NamespaceDecl>(DC);
532 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
533 return NestedNameSpecifier::Create(Context, nullptr, ND);
534 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
535 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
536 RD->getTypeForDecl());
537 else if (isa<TranslationUnitDecl>(DC))
538 return NestedNameSpecifier::GlobalSpecifier(Context);
539 }
540 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 540)
;
541}
542
543/// Find the parent class with dependent bases of the innermost enclosing method
544/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
545/// up allowing unqualified dependent type names at class-level, which MSVC
546/// correctly rejects.
547static const CXXRecordDecl *
548findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
549 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
550 DC = DC->getPrimaryContext();
551 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
552 if (MD->getParent()->hasAnyDependentBases())
553 return MD->getParent();
554 }
555 return nullptr;
556}
557
558ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
559 SourceLocation NameLoc,
560 bool IsTemplateTypeArg) {
561 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 561, __PRETTY_FUNCTION__))
;
562
563 NestedNameSpecifier *NNS = nullptr;
564 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
565 // If we weren't able to parse a default template argument, delay lookup
566 // until instantiation time by making a non-dependent DependentTypeName. We
567 // pretend we saw a NestedNameSpecifier referring to the current scope, and
568 // lookup is retried.
569 // FIXME: This hurts our diagnostic quality, since we get errors like "no
570 // type named 'Foo' in 'current_namespace'" when the user didn't write any
571 // name specifiers.
572 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
573 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
574 } else if (const CXXRecordDecl *RD =
575 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
576 // Build a DependentNameType that will perform lookup into RD at
577 // instantiation time.
578 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
579 RD->getTypeForDecl());
580
581 // Diagnose that this identifier was undeclared, and retry the lookup during
582 // template instantiation.
583 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
584 << RD;
585 } else {
586 // This is not a situation that we should recover from.
587 return ParsedType();
588 }
589
590 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
591
592 // Build type location information. We synthesized the qualifier, so we have
593 // to build a fake NestedNameSpecifierLoc.
594 NestedNameSpecifierLocBuilder NNSLocBuilder;
595 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
596 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
597
598 TypeLocBuilder Builder;
599 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
600 DepTL.setNameLoc(NameLoc);
601 DepTL.setElaboratedKeywordLoc(SourceLocation());
602 DepTL.setQualifierLoc(QualifierLoc);
603 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
604}
605
606/// isTagName() - This method is called *for error recovery purposes only*
607/// to determine if the specified name is a valid tag name ("struct foo"). If
608/// so, this returns the TST for the tag corresponding to it (TST_enum,
609/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
610/// cases in C where the user forgot to specify the tag.
611DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
612 // Do a tag name lookup in this scope.
613 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
614 LookupName(R, S, false);
615 R.suppressDiagnostics();
616 if (R.getResultKind() == LookupResult::Found)
617 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
618 switch (TD->getTagKind()) {
619 case TTK_Struct: return DeclSpec::TST_struct;
620 case TTK_Interface: return DeclSpec::TST_interface;
621 case TTK_Union: return DeclSpec::TST_union;
622 case TTK_Class: return DeclSpec::TST_class;
623 case TTK_Enum: return DeclSpec::TST_enum;
624 }
625 }
626
627 return DeclSpec::TST_unspecified;
628}
629
630/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
631/// if a CXXScopeSpec's type is equal to the type of one of the base classes
632/// then downgrade the missing typename error to a warning.
633/// This is needed for MSVC compatibility; Example:
634/// @code
635/// template<class T> class A {
636/// public:
637/// typedef int TYPE;
638/// };
639/// template<class T> class B : public A<T> {
640/// public:
641/// A<T>::TYPE a; // no typename required because A<T> is a base class.
642/// };
643/// @endcode
644bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
645 if (CurContext->isRecord()) {
646 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
647 return true;
648
649 const Type *Ty = SS->getScopeRep()->getAsType();
650
651 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
652 for (const auto &Base : RD->bases())
653 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
654 return true;
655 return S->isFunctionPrototypeScope();
656 }
657 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
658}
659
660void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
661 SourceLocation IILoc,
662 Scope *S,
663 CXXScopeSpec *SS,
664 ParsedType &SuggestedType,
665 bool IsTemplateName) {
666 // Don't report typename errors for editor placeholders.
667 if (II->isEditorPlaceholder())
668 return;
669 // We don't have anything to suggest (yet).
670 SuggestedType = nullptr;
671
672 // There may have been a typo in the name of the type. Look up typo
673 // results, in case we have something that we can suggest.
674 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
675 /*AllowTemplates=*/IsTemplateName,
676 /*AllowNonTemplates=*/!IsTemplateName);
677 if (TypoCorrection Corrected =
678 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
679 CCC, CTK_ErrorRecovery)) {
680 // FIXME: Support error recovery for the template-name case.
681 bool CanRecover = !IsTemplateName;
682 if (Corrected.isKeyword()) {
683 // We corrected to a keyword.
684 diagnoseTypo(Corrected,
685 PDiag(IsTemplateName ? diag::err_no_template_suggest
686 : diag::err_unknown_typename_suggest)
687 << II);
688 II = Corrected.getCorrectionAsIdentifierInfo();
689 } else {
690 // We found a similarly-named type or interface; suggest that.
691 if (!SS || !SS->isSet()) {
692 diagnoseTypo(Corrected,
693 PDiag(IsTemplateName ? diag::err_no_template_suggest
694 : diag::err_unknown_typename_suggest)
695 << II, CanRecover);
696 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
697 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
698 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
699 II->getName().equals(CorrectedStr);
700 diagnoseTypo(Corrected,
701 PDiag(IsTemplateName
702 ? diag::err_no_member_template_suggest
703 : diag::err_unknown_nested_typename_suggest)
704 << II << DC << DroppedSpecifier << SS->getRange(),
705 CanRecover);
706 } else {
707 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 707)
;
708 }
709
710 if (!CanRecover)
711 return;
712
713 CXXScopeSpec tmpSS;
714 if (Corrected.getCorrectionSpecifier())
715 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
716 SourceRange(IILoc));
717 // FIXME: Support class template argument deduction here.
718 SuggestedType =
719 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
720 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
721 /*IsCtorOrDtorName=*/false,
722 /*WantNontrivialTypeSourceInfo=*/true);
723 }
724 return;
725 }
726
727 if (getLangOpts().CPlusPlus && !IsTemplateName) {
728 // See if II is a class template that the user forgot to pass arguments to.
729 UnqualifiedId Name;
730 Name.setIdentifier(II, IILoc);
731 CXXScopeSpec EmptySS;
732 TemplateTy TemplateResult;
733 bool MemberOfUnknownSpecialization;
734 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
735 Name, nullptr, true, TemplateResult,
736 MemberOfUnknownSpecialization) == TNK_Type_template) {
737 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
738 return;
739 }
740 }
741
742 // FIXME: Should we move the logic that tries to recover from a missing tag
743 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
744
745 if (!SS || (!SS->isSet() && !SS->isInvalid()))
746 Diag(IILoc, IsTemplateName ? diag::err_no_template
747 : diag::err_unknown_typename)
748 << II;
749 else if (DeclContext *DC = computeDeclContext(*SS, false))
750 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
751 : diag::err_typename_nested_not_found)
752 << II << DC << SS->getRange();
753 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
754 SuggestedType =
755 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
756 } else if (isDependentScopeSpecifier(*SS)) {
757 unsigned DiagID = diag::err_typename_missing;
758 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
759 DiagID = diag::ext_typename_missing;
760
761 Diag(SS->getRange().getBegin(), DiagID)
762 << SS->getScopeRep() << II->getName()
763 << SourceRange(SS->getRange().getBegin(), IILoc)
764 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
765 SuggestedType = ActOnTypenameType(S, SourceLocation(),
766 *SS, *II, IILoc).get();
767 } else {
768 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 769, __PRETTY_FUNCTION__))
769 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 769, __PRETTY_FUNCTION__))
;
770 }
771}
772
773/// Determine whether the given result set contains either a type name
774/// or
775static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
776 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
777 NextToken.is(tok::less);
778
779 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
780 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
781 return true;
782
783 if (CheckTemplate && isa<TemplateDecl>(*I))
784 return true;
785 }
786
787 return false;
788}
789
790static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
791 Scope *S, CXXScopeSpec &SS,
792 IdentifierInfo *&Name,
793 SourceLocation NameLoc) {
794 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
795 SemaRef.LookupParsedName(R, S, &SS);
796 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
797 StringRef FixItTagName;
798 switch (Tag->getTagKind()) {
799 case TTK_Class:
800 FixItTagName = "class ";
801 break;
802
803 case TTK_Enum:
804 FixItTagName = "enum ";
805 break;
806
807 case TTK_Struct:
808 FixItTagName = "struct ";
809 break;
810
811 case TTK_Interface:
812 FixItTagName = "__interface ";
813 break;
814
815 case TTK_Union:
816 FixItTagName = "union ";
817 break;
818 }
819
820 StringRef TagName = FixItTagName.drop_back();
821 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
822 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
823 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
824
825 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
826 I != IEnd; ++I)
827 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
828 << Name << TagName;
829
830 // Replace lookup results with just the tag decl.
831 Result.clear(Sema::LookupTagName);
832 SemaRef.LookupParsedName(Result, S, &SS);
833 return true;
834 }
835
836 return false;
837}
838
839/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
840static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
841 QualType T, SourceLocation NameLoc) {
842 ASTContext &Context = S.Context;
843
844 TypeLocBuilder Builder;
845 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
846
847 T = S.getElaboratedType(ETK_None, SS, T);
848 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
849 ElabTL.setElaboratedKeywordLoc(SourceLocation());
850 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
851 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
852}
853
854Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
855 IdentifierInfo *&Name,
856 SourceLocation NameLoc,
857 const Token &NextToken,
858 CorrectionCandidateCallback *CCC) {
859 DeclarationNameInfo NameInfo(Name, NameLoc);
860 ObjCMethodDecl *CurMethod = getCurMethodDecl();
861
862 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 863, __PRETTY_FUNCTION__))
863 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 863, __PRETTY_FUNCTION__))
;
864 if (getLangOpts().CPlusPlus && SS.isSet() &&
865 isCurrentClassName(*Name, S, &SS)) {
866 // Per [class.qual]p2, this names the constructors of SS, not the
867 // injected-class-name. We don't have a classification for that.
868 // There's not much point caching this result, since the parser
869 // will reject it later.
870 return NameClassification::Unknown();
871 }
872
873 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
874 LookupParsedName(Result, S, &SS, !CurMethod);
875
876 if (SS.isInvalid())
877 return NameClassification::Error();
878
879 // For unqualified lookup in a class template in MSVC mode, look into
880 // dependent base classes where the primary class template is known.
881 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
882 if (ParsedType TypeInBase =
883 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
884 return TypeInBase;
885 }
886
887 // Perform lookup for Objective-C instance variables (including automatically
888 // synthesized instance variables), if we're in an Objective-C method.
889 // FIXME: This lookup really, really needs to be folded in to the normal
890 // unqualified lookup mechanism.
891 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
892 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
893 if (Ivar.isInvalid())
894 return NameClassification::Error();
895 if (Ivar.isUsable())
896 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
897
898 // We defer builtin creation until after ivar lookup inside ObjC methods.
899 if (Result.empty())
900 LookupBuiltin(Result);
901 }
902
903 bool SecondTry = false;
904 bool IsFilteredTemplateName = false;
905
906Corrected:
907 switch (Result.getResultKind()) {
908 case LookupResult::NotFound:
909 // If an unqualified-id is followed by a '(', then we have a function
910 // call.
911 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
912 // In C++, this is an ADL-only call.
913 // FIXME: Reference?
914 if (getLangOpts().CPlusPlus)
915 return NameClassification::UndeclaredNonType();
916
917 // C90 6.3.2.2:
918 // If the expression that precedes the parenthesized argument list in a
919 // function call consists solely of an identifier, and if no
920 // declaration is visible for this identifier, the identifier is
921 // implicitly declared exactly as if, in the innermost block containing
922 // the function call, the declaration
923 //
924 // extern int identifier ();
925 //
926 // appeared.
927 //
928 // We also allow this in C99 as an extension.
929 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
930 return NameClassification::NonType(D);
931 }
932
933 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
934 // In C++20 onwards, this could be an ADL-only call to a function
935 // template, and we're required to assume that this is a template name.
936 //
937 // FIXME: Find a way to still do typo correction in this case.
938 TemplateName Template =
939 Context.getAssumedTemplateName(NameInfo.getName());
940 return NameClassification::UndeclaredTemplate(Template);
941 }
942
943 // In C, we first see whether there is a tag type by the same name, in
944 // which case it's likely that the user just forgot to write "enum",
945 // "struct", or "union".
946 if (!getLangOpts().CPlusPlus && !SecondTry &&
947 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
948 break;
949 }
950
951 // Perform typo correction to determine if there is another name that is
952 // close to this name.
953 if (!SecondTry && CCC) {
954 SecondTry = true;
955 if (TypoCorrection Corrected =
956 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
957 &SS, *CCC, CTK_ErrorRecovery)) {
958 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
959 unsigned QualifiedDiag = diag::err_no_member_suggest;
960
961 NamedDecl *FirstDecl = Corrected.getFoundDecl();
962 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
963 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
964 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
965 UnqualifiedDiag = diag::err_no_template_suggest;
966 QualifiedDiag = diag::err_no_member_template_suggest;
967 } else if (UnderlyingFirstDecl &&
968 (isa<TypeDecl>(UnderlyingFirstDecl) ||
969 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
970 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
971 UnqualifiedDiag = diag::err_unknown_typename_suggest;
972 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
973 }
974
975 if (SS.isEmpty()) {
976 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
977 } else {// FIXME: is this even reachable? Test it.
978 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
979 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
980 Name->getName().equals(CorrectedStr);
981 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
982 << Name << computeDeclContext(SS, false)
983 << DroppedSpecifier << SS.getRange());
984 }
985
986 // Update the name, so that the caller has the new name.
987 Name = Corrected.getCorrectionAsIdentifierInfo();
988
989 // Typo correction corrected to a keyword.
990 if (Corrected.isKeyword())
991 return Name;
992
993 // Also update the LookupResult...
994 // FIXME: This should probably go away at some point
995 Result.clear();
996 Result.setLookupName(Corrected.getCorrection());
997 if (FirstDecl)
998 Result.addDecl(FirstDecl);
999
1000 // If we found an Objective-C instance variable, let
1001 // LookupInObjCMethod build the appropriate expression to
1002 // reference the ivar.
1003 // FIXME: This is a gross hack.
1004 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1005 DeclResult R =
1006 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1007 if (R.isInvalid())
1008 return NameClassification::Error();
1009 if (R.isUsable())
1010 return NameClassification::NonType(Ivar);
1011 }
1012
1013 goto Corrected;
1014 }
1015 }
1016
1017 // We failed to correct; just fall through and let the parser deal with it.
1018 Result.suppressDiagnostics();
1019 return NameClassification::Unknown();
1020
1021 case LookupResult::NotFoundInCurrentInstantiation: {
1022 // We performed name lookup into the current instantiation, and there were
1023 // dependent bases, so we treat this result the same way as any other
1024 // dependent nested-name-specifier.
1025
1026 // C++ [temp.res]p2:
1027 // A name used in a template declaration or definition and that is
1028 // dependent on a template-parameter is assumed not to name a type
1029 // unless the applicable name lookup finds a type name or the name is
1030 // qualified by the keyword typename.
1031 //
1032 // FIXME: If the next token is '<', we might want to ask the parser to
1033 // perform some heroics to see if we actually have a
1034 // template-argument-list, which would indicate a missing 'template'
1035 // keyword here.
1036 return NameClassification::DependentNonType();
1037 }
1038
1039 case LookupResult::Found:
1040 case LookupResult::FoundOverloaded:
1041 case LookupResult::FoundUnresolvedValue:
1042 break;
1043
1044 case LookupResult::Ambiguous:
1045 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1046 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1047 /*AllowDependent=*/false)) {
1048 // C++ [temp.local]p3:
1049 // A lookup that finds an injected-class-name (10.2) can result in an
1050 // ambiguity in certain cases (for example, if it is found in more than
1051 // one base class). If all of the injected-class-names that are found
1052 // refer to specializations of the same class template, and if the name
1053 // is followed by a template-argument-list, the reference refers to the
1054 // class template itself and not a specialization thereof, and is not
1055 // ambiguous.
1056 //
1057 // This filtering can make an ambiguous result into an unambiguous one,
1058 // so try again after filtering out template names.
1059 FilterAcceptableTemplateNames(Result);
1060 if (!Result.isAmbiguous()) {
1061 IsFilteredTemplateName = true;
1062 break;
1063 }
1064 }
1065
1066 // Diagnose the ambiguity and return an error.
1067 return NameClassification::Error();
1068 }
1069
1070 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1071 (IsFilteredTemplateName ||
1072 hasAnyAcceptableTemplateNames(
1073 Result, /*AllowFunctionTemplates=*/true,
1074 /*AllowDependent=*/false,
1075 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1076 getLangOpts().CPlusPlus20))) {
1077 // C++ [temp.names]p3:
1078 // After name lookup (3.4) finds that a name is a template-name or that
1079 // an operator-function-id or a literal- operator-id refers to a set of
1080 // overloaded functions any member of which is a function template if
1081 // this is followed by a <, the < is always taken as the delimiter of a
1082 // template-argument-list and never as the less-than operator.
1083 // C++2a [temp.names]p2:
1084 // A name is also considered to refer to a template if it is an
1085 // unqualified-id followed by a < and name lookup finds either one
1086 // or more functions or finds nothing.
1087 if (!IsFilteredTemplateName)
1088 FilterAcceptableTemplateNames(Result);
1089
1090 bool IsFunctionTemplate;
1091 bool IsVarTemplate;
1092 TemplateName Template;
1093 if (Result.end() - Result.begin() > 1) {
1094 IsFunctionTemplate = true;
1095 Template = Context.getOverloadedTemplateName(Result.begin(),
1096 Result.end());
1097 } else if (!Result.empty()) {
1098 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1099 *Result.begin(), /*AllowFunctionTemplates=*/true,
1100 /*AllowDependent=*/false));
1101 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1102 IsVarTemplate = isa<VarTemplateDecl>(TD);
1103
1104 if (SS.isNotEmpty())
1105 Template =
1106 Context.getQualifiedTemplateName(SS.getScopeRep(),
1107 /*TemplateKeyword=*/false, TD);
1108 else
1109 Template = TemplateName(TD);
1110 } else {
1111 // All results were non-template functions. This is a function template
1112 // name.
1113 IsFunctionTemplate = true;
1114 Template = Context.getAssumedTemplateName(NameInfo.getName());
1115 }
1116
1117 if (IsFunctionTemplate) {
1118 // Function templates always go through overload resolution, at which
1119 // point we'll perform the various checks (e.g., accessibility) we need
1120 // to based on which function we selected.
1121 Result.suppressDiagnostics();
1122
1123 return NameClassification::FunctionTemplate(Template);
1124 }
1125
1126 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1127 : NameClassification::TypeTemplate(Template);
1128 }
1129
1130 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1131 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1132 DiagnoseUseOfDecl(Type, NameLoc);
1133 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1134 QualType T = Context.getTypeDeclType(Type);
1135 if (SS.isNotEmpty())
1136 return buildNestedType(*this, SS, T, NameLoc);
1137 return ParsedType::make(T);
1138 }
1139
1140 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1141 if (!Class) {
1142 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1143 if (ObjCCompatibleAliasDecl *Alias =
1144 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1145 Class = Alias->getClassInterface();
1146 }
1147
1148 if (Class) {
1149 DiagnoseUseOfDecl(Class, NameLoc);
1150
1151 if (NextToken.is(tok::period)) {
1152 // Interface. <something> is parsed as a property reference expression.
1153 // Just return "unknown" as a fall-through for now.
1154 Result.suppressDiagnostics();
1155 return NameClassification::Unknown();
1156 }
1157
1158 QualType T = Context.getObjCInterfaceType(Class);
1159 return ParsedType::make(T);
1160 }
1161
1162 if (isa<ConceptDecl>(FirstDecl))
1163 return NameClassification::Concept(
1164 TemplateName(cast<TemplateDecl>(FirstDecl)));
1165
1166 // We can have a type template here if we're classifying a template argument.
1167 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1168 !isa<VarTemplateDecl>(FirstDecl))
1169 return NameClassification::TypeTemplate(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 // Check for a tag type hidden by a non-type decl in a few cases where it
1173 // seems likely a type is wanted instead of the non-type that was found.
1174 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1175 if ((NextToken.is(tok::identifier) ||
1176 (NextIsOp &&
1177 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1178 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1179 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1180 DiagnoseUseOfDecl(Type, NameLoc);
1181 QualType T = Context.getTypeDeclType(Type);
1182 if (SS.isNotEmpty())
1183 return buildNestedType(*this, SS, T, NameLoc);
1184 return ParsedType::make(T);
1185 }
1186
1187 // If we already know which single declaration is referenced, just annotate
1188 // that declaration directly. Defer resolving even non-overloaded class
1189 // member accesses, as we need to defer certain access checks until we know
1190 // the context.
1191 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1192 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1193 return NameClassification::NonType(Result.getRepresentativeDecl());
1194
1195 // Otherwise, this is an overload set that we will need to resolve later.
1196 Result.suppressDiagnostics();
1197 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1198 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1199 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1200 Result.begin(), Result.end()));
1201}
1202
1203ExprResult
1204Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1205 SourceLocation NameLoc) {
1206 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1206, __PRETTY_FUNCTION__))
;
1207 CXXScopeSpec SS;
1208 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1209 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1210}
1211
1212ExprResult
1213Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1214 IdentifierInfo *Name,
1215 SourceLocation NameLoc,
1216 bool IsAddressOfOperand) {
1217 DeclarationNameInfo NameInfo(Name, NameLoc);
1218 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1219 NameInfo, IsAddressOfOperand,
1220 /*TemplateArgs=*/nullptr);
1221}
1222
1223ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1224 NamedDecl *Found,
1225 SourceLocation NameLoc,
1226 const Token &NextToken) {
1227 if (getCurMethodDecl() && SS.isEmpty())
1228 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1229 return BuildIvarRefExpr(S, NameLoc, Ivar);
1230
1231 // Reconstruct the lookup result.
1232 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1233 Result.addDecl(Found);
1234 Result.resolveKind();
1235
1236 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1237 return BuildDeclarationNameExpr(SS, Result, ADL);
1238}
1239
1240ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1241 // For an implicit class member access, transform the result into a member
1242 // access expression if necessary.
1243 auto *ULE = cast<UnresolvedLookupExpr>(E);
1244 if ((*ULE->decls_begin())->isCXXClassMember()) {
1245 CXXScopeSpec SS;
1246 SS.Adopt(ULE->getQualifierLoc());
1247
1248 // Reconstruct the lookup result.
1249 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1250 LookupOrdinaryName);
1251 Result.setNamingClass(ULE->getNamingClass());
1252 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1253 Result.addDecl(*I, I.getAccess());
1254 Result.resolveKind();
1255 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1256 nullptr, S);
1257 }
1258
1259 // Otherwise, this is already in the form we needed, and no further checks
1260 // are necessary.
1261 return ULE;
1262}
1263
1264Sema::TemplateNameKindForDiagnostics
1265Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1266 auto *TD = Name.getAsTemplateDecl();
1267 if (!TD)
1268 return TemplateNameKindForDiagnostics::DependentTemplate;
1269 if (isa<ClassTemplateDecl>(TD))
1270 return TemplateNameKindForDiagnostics::ClassTemplate;
1271 if (isa<FunctionTemplateDecl>(TD))
1272 return TemplateNameKindForDiagnostics::FunctionTemplate;
1273 if (isa<VarTemplateDecl>(TD))
1274 return TemplateNameKindForDiagnostics::VarTemplate;
1275 if (isa<TypeAliasTemplateDecl>(TD))
1276 return TemplateNameKindForDiagnostics::AliasTemplate;
1277 if (isa<TemplateTemplateParmDecl>(TD))
1278 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1279 if (isa<ConceptDecl>(TD))
1280 return TemplateNameKindForDiagnostics::Concept;
1281 return TemplateNameKindForDiagnostics::DependentTemplate;
1282}
1283
1284void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1285 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1286, __PRETTY_FUNCTION__))
1286 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1286, __PRETTY_FUNCTION__))
;
1287 CurContext = DC;
1288 S->setEntity(DC);
1289}
1290
1291void Sema::PopDeclContext() {
1292 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1292, __PRETTY_FUNCTION__))
;
1293
1294 CurContext = CurContext->getLexicalParent();
1295 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1295, __PRETTY_FUNCTION__))
;
1296}
1297
1298Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1299 Decl *D) {
1300 // Unlike PushDeclContext, the context to which we return is not necessarily
1301 // the containing DC of TD, because the new context will be some pre-existing
1302 // TagDecl definition instead of a fresh one.
1303 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1304 CurContext = cast<TagDecl>(D)->getDefinition();
1305 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1305, __PRETTY_FUNCTION__))
;
1306 // Start lookups from the parent of the current context; we don't want to look
1307 // into the pre-existing complete definition.
1308 S->setEntity(CurContext->getLookupParent());
1309 return Result;
1310}
1311
1312void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1313 CurContext = static_cast<decltype(CurContext)>(Context);
1314}
1315
1316/// EnterDeclaratorContext - Used when we must lookup names in the context
1317/// of a declarator's nested name specifier.
1318///
1319void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1320 // C++0x [basic.lookup.unqual]p13:
1321 // A name used in the definition of a static data member of class
1322 // X (after the qualified-id of the static member) is looked up as
1323 // if the name was used in a member function of X.
1324 // C++0x [basic.lookup.unqual]p14:
1325 // If a variable member of a namespace is defined outside of the
1326 // scope of its namespace then any name used in the definition of
1327 // the variable member (after the declarator-id) is looked up as
1328 // if the definition of the variable member occurred in its
1329 // namespace.
1330 // Both of these imply that we should push a scope whose context
1331 // is the semantic context of the declaration. We can't use
1332 // PushDeclContext here because that context is not necessarily
1333 // lexically contained in the current context. Fortunately,
1334 // the containing scope should have the appropriate information.
1335
1336 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1336, __PRETTY_FUNCTION__))
;
1337
1338#ifndef NDEBUG
1339 Scope *Ancestor = S->getParent();
1340 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1341 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1341, __PRETTY_FUNCTION__))
;
1342#endif
1343
1344 CurContext = DC;
1345 S->setEntity(DC);
1346
1347 if (S->getParent()->isTemplateParamScope()) {
1348 // Also set the corresponding entities for all immediately-enclosing
1349 // template parameter scopes.
1350 EnterTemplatedContext(S->getParent(), DC);
1351 }
1352}
1353
1354void Sema::ExitDeclaratorContext(Scope *S) {
1355 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1355, __PRETTY_FUNCTION__))
;
1356
1357 // Switch back to the lexical context. The safety of this is
1358 // enforced by an assert in EnterDeclaratorContext.
1359 Scope *Ancestor = S->getParent();
1360 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1361 CurContext = Ancestor->getEntity();
1362
1363 // We don't need to do anything with the scope, which is going to
1364 // disappear.
1365}
1366
1367void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1368 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1369, __PRETTY_FUNCTION__))
1369 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1369, __PRETTY_FUNCTION__))
;
1370
1371 // C++20 [temp.local]p7:
1372 // In the definition of a member of a class template that appears outside
1373 // of the class template definition, the name of a member of the class
1374 // template hides the name of a template-parameter of any enclosing class
1375 // templates (but not a template-parameter of the member if the member is a
1376 // class or function template).
1377 // C++20 [temp.local]p9:
1378 // In the definition of a class template or in the definition of a member
1379 // of such a template that appears outside of the template definition, for
1380 // each non-dependent base class (13.8.2.1), if the name of the base class
1381 // or the name of a member of the base class is the same as the name of a
1382 // template-parameter, the base class name or member name hides the
1383 // template-parameter name (6.4.10).
1384 //
1385 // This means that a template parameter scope should be searched immediately
1386 // after searching the DeclContext for which it is a template parameter
1387 // scope. For example, for
1388 // template<typename T> template<typename U> template<typename V>
1389 // void N::A<T>::B<U>::f(...)
1390 // we search V then B<U> (and base classes) then U then A<T> (and base
1391 // classes) then T then N then ::.
1392 unsigned ScopeDepth = getTemplateDepth(S);
1393 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1394 DeclContext *SearchDCAfterScope = DC;
1395 for (; DC; DC = DC->getLookupParent()) {
1396 if (const TemplateParameterList *TPL =
1397 cast<Decl>(DC)->getDescribedTemplateParams()) {
1398 unsigned DCDepth = TPL->getDepth() + 1;
1399 if (DCDepth > ScopeDepth)
1400 continue;
1401 if (ScopeDepth == DCDepth)
1402 SearchDCAfterScope = DC = DC->getLookupParent();
1403 break;
1404 }
1405 }
1406 S->setLookupEntity(SearchDCAfterScope);
1407 }
1408}
1409
1410void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1411 // We assume that the caller has already called
1412 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1413 FunctionDecl *FD = D->getAsFunction();
1414 if (!FD)
1415 return;
1416
1417 // Same implementation as PushDeclContext, but enters the context
1418 // from the lexical parent, rather than the top-level class.
1419 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1420, __PRETTY_FUNCTION__))
1420 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1420, __PRETTY_FUNCTION__))
;
1421 CurContext = FD;
1422 S->setEntity(CurContext);
1423
1424 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1425 ParmVarDecl *Param = FD->getParamDecl(P);
1426 // If the parameter has an identifier, then add it to the scope
1427 if (Param->getIdentifier()) {
1428 S->AddDecl(Param);
1429 IdResolver.AddDecl(Param);
1430 }
1431 }
1432}
1433
1434void Sema::ActOnExitFunctionContext() {
1435 // Same implementation as PopDeclContext, but returns to the lexical parent,
1436 // rather than the top-level class.
1437 assert(CurContext && "DeclContext imbalance!")((CurContext && "DeclContext imbalance!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1437, __PRETTY_FUNCTION__))
;
1438 CurContext = CurContext->getLexicalParent();
1439 assert(CurContext && "Popped translation unit!")((CurContext && "Popped translation unit!") ? static_cast
<void> (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1439, __PRETTY_FUNCTION__))
;
1440}
1441
1442/// Determine whether we allow overloading of the function
1443/// PrevDecl with another declaration.
1444///
1445/// This routine determines whether overloading is possible, not
1446/// whether some new function is actually an overload. It will return
1447/// true in C++ (where we can always provide overloads) or, as an
1448/// extension, in C when the previous function is already an
1449/// overloaded function declaration or has the "overloadable"
1450/// attribute.
1451static bool AllowOverloadingOfFunction(LookupResult &Previous,
1452 ASTContext &Context,
1453 const FunctionDecl *New) {
1454 if (Context.getLangOpts().CPlusPlus)
1455 return true;
1456
1457 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1458 return true;
1459
1460 return Previous.getResultKind() == LookupResult::Found &&
1461 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1462 New->hasAttr<OverloadableAttr>());
1463}
1464
1465/// Add this decl to the scope shadowed decl chains.
1466void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1467 // Move up the scope chain until we find the nearest enclosing
1468 // non-transparent context. The declaration will be introduced into this
1469 // scope.
1470 while (S->getEntity() && S->getEntity()->isTransparentContext())
1471 S = S->getParent();
1472
1473 // Add scoped declarations into their context, so that they can be
1474 // found later. Declarations without a context won't be inserted
1475 // into any context.
1476 if (AddToContext)
1477 CurContext->addDecl(D);
1478
1479 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1480 // are function-local declarations.
1481 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1482 return;
1483
1484 // Template instantiations should also not be pushed into scope.
1485 if (isa<FunctionDecl>(D) &&
1486 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1487 return;
1488
1489 // If this replaces anything in the current scope,
1490 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1491 IEnd = IdResolver.end();
1492 for (; I != IEnd; ++I) {
1493 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1494 S->RemoveDecl(*I);
1495 IdResolver.RemoveDecl(*I);
1496
1497 // Should only need to replace one decl.
1498 break;
1499 }
1500 }
1501
1502 S->AddDecl(D);
1503
1504 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1505 // Implicitly-generated labels may end up getting generated in an order that
1506 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1507 // the label at the appropriate place in the identifier chain.
1508 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1509 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1510 if (IDC == CurContext) {
1511 if (!S->isDeclScope(*I))
1512 continue;
1513 } else if (IDC->Encloses(CurContext))
1514 break;
1515 }
1516
1517 IdResolver.InsertDeclAfter(I, D);
1518 } else {
1519 IdResolver.AddDecl(D);
1520 }
1521}
1522
1523bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1524 bool AllowInlineNamespace) {
1525 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1526}
1527
1528Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1529 DeclContext *TargetDC = DC->getPrimaryContext();
1530 do {
1531 if (DeclContext *ScopeDC = S->getEntity())
1532 if (ScopeDC->getPrimaryContext() == TargetDC)
1533 return S;
1534 } while ((S = S->getParent()));
1535
1536 return nullptr;
1537}
1538
1539static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1540 DeclContext*,
1541 ASTContext&);
1542
1543/// Filters out lookup results that don't fall within the given scope
1544/// as determined by isDeclInScope.
1545void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1546 bool ConsiderLinkage,
1547 bool AllowInlineNamespace) {
1548 LookupResult::Filter F = R.makeFilter();
1549 while (F.hasNext()) {
1550 NamedDecl *D = F.next();
1551
1552 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1553 continue;
1554
1555 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1556 continue;
1557
1558 F.erase();
1559 }
1560
1561 F.done();
1562}
1563
1564/// We've determined that \p New is a redeclaration of \p Old. Check that they
1565/// have compatible owning modules.
1566bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1567 // FIXME: The Modules TS is not clear about how friend declarations are
1568 // to be treated. It's not meaningful to have different owning modules for
1569 // linkage in redeclarations of the same entity, so for now allow the
1570 // redeclaration and change the owning modules to match.
1571 if (New->getFriendObjectKind() &&
1572 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1573 New->setLocalOwningModule(Old->getOwningModule());
1574 makeMergedDefinitionVisible(New);
1575 return false;
1576 }
1577
1578 Module *NewM = New->getOwningModule();
1579 Module *OldM = Old->getOwningModule();
1580
1581 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1582 NewM = NewM->Parent;
1583 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1584 OldM = OldM->Parent;
1585
1586 if (NewM == OldM)
1587 return false;
1588
1589 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1590 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1591 if (NewIsModuleInterface || OldIsModuleInterface) {
1592 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1593 // if a declaration of D [...] appears in the purview of a module, all
1594 // other such declarations shall appear in the purview of the same module
1595 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1596 << New
1597 << NewIsModuleInterface
1598 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1599 << OldIsModuleInterface
1600 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1601 Diag(Old->getLocation(), diag::note_previous_declaration);
1602 New->setInvalidDecl();
1603 return true;
1604 }
1605
1606 return false;
1607}
1608
1609static bool isUsingDecl(NamedDecl *D) {
1610 return isa<UsingShadowDecl>(D) ||
1611 isa<UnresolvedUsingTypenameDecl>(D) ||
1612 isa<UnresolvedUsingValueDecl>(D);
1613}
1614
1615/// Removes using shadow declarations from the lookup results.
1616static void RemoveUsingDecls(LookupResult &R) {
1617 LookupResult::Filter F = R.makeFilter();
1618 while (F.hasNext())
1619 if (isUsingDecl(F.next()))
1620 F.erase();
1621
1622 F.done();
1623}
1624
1625/// Check for this common pattern:
1626/// @code
1627/// class S {
1628/// S(const S&); // DO NOT IMPLEMENT
1629/// void operator=(const S&); // DO NOT IMPLEMENT
1630/// };
1631/// @endcode
1632static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1633 // FIXME: Should check for private access too but access is set after we get
1634 // the decl here.
1635 if (D->doesThisDeclarationHaveABody())
1636 return false;
1637
1638 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1639 return CD->isCopyConstructor();
1640 return D->isCopyAssignmentOperator();
1641}
1642
1643// We need this to handle
1644//
1645// typedef struct {
1646// void *foo() { return 0; }
1647// } A;
1648//
1649// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1650// for example. If 'A', foo will have external linkage. If we have '*A',
1651// foo will have no linkage. Since we can't know until we get to the end
1652// of the typedef, this function finds out if D might have non-external linkage.
1653// Callers should verify at the end of the TU if it D has external linkage or
1654// not.
1655bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1656 const DeclContext *DC = D->getDeclContext();
1657 while (!DC->isTranslationUnit()) {
1658 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1659 if (!RD->hasNameForLinkage())
1660 return true;
1661 }
1662 DC = DC->getParent();
1663 }
1664
1665 return !D->isExternallyVisible();
1666}
1667
1668// FIXME: This needs to be refactored; some other isInMainFile users want
1669// these semantics.
1670static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1671 if (S.TUKind != TU_Complete)
1672 return false;
1673 return S.SourceMgr.isInMainFile(Loc);
1674}
1675
1676bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1677 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1677, __PRETTY_FUNCTION__))
;
1678
1679 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1680 return false;
1681
1682 // Ignore all entities declared within templates, and out-of-line definitions
1683 // of members of class templates.
1684 if (D->getDeclContext()->isDependentContext() ||
1685 D->getLexicalDeclContext()->isDependentContext())
1686 return false;
1687
1688 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1689 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1690 return false;
1691 // A non-out-of-line declaration of a member specialization was implicitly
1692 // instantiated; it's the out-of-line declaration that we're interested in.
1693 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1694 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1695 return false;
1696
1697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1698 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1699 return false;
1700 } else {
1701 // 'static inline' functions are defined in headers; don't warn.
1702 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1703 return false;
1704 }
1705
1706 if (FD->doesThisDeclarationHaveABody() &&
1707 Context.DeclMustBeEmitted(FD))
1708 return false;
1709 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1710 // Constants and utility variables are defined in headers with internal
1711 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1712 // like "inline".)
1713 if (!isMainFileLoc(*this, VD->getLocation()))
1714 return false;
1715
1716 if (Context.DeclMustBeEmitted(VD))
1717 return false;
1718
1719 if (VD->isStaticDataMember() &&
1720 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1721 return false;
1722 if (VD->isStaticDataMember() &&
1723 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1724 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1725 return false;
1726
1727 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1728 return false;
1729 } else {
1730 return false;
1731 }
1732
1733 // Only warn for unused decls internal to the translation unit.
1734 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1735 // for inline functions defined in the main source file, for instance.
1736 return mightHaveNonExternalLinkage(D);
1737}
1738
1739void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1740 if (!D)
1741 return;
1742
1743 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1744 const FunctionDecl *First = FD->getFirstDecl();
1745 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1746 return; // First should already be in the vector.
1747 }
1748
1749 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1750 const VarDecl *First = VD->getFirstDecl();
1751 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1752 return; // First should already be in the vector.
1753 }
1754
1755 if (ShouldWarnIfUnusedFileScopedDecl(D))
1756 UnusedFileScopedDecls.push_back(D);
1757}
1758
1759static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1760 if (D->isInvalidDecl())
1761 return false;
1762
1763 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1764 // For a decomposition declaration, warn if none of the bindings are
1765 // referenced, instead of if the variable itself is referenced (which
1766 // it is, by the bindings' expressions).
1767 for (auto *BD : DD->bindings())
1768 if (BD->isReferenced())
1769 return false;
1770 } else if (!D->getDeclName()) {
1771 return false;
1772 } else if (D->isReferenced() || D->isUsed()) {
1773 return false;
1774 }
1775
1776 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1777 return false;
1778
1779 if (isa<LabelDecl>(D))
1780 return true;
1781
1782 // Except for labels, we only care about unused decls that are local to
1783 // functions.
1784 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1785 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1786 // For dependent types, the diagnostic is deferred.
1787 WithinFunction =
1788 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1789 if (!WithinFunction)
1790 return false;
1791
1792 if (isa<TypedefNameDecl>(D))
1793 return true;
1794
1795 // White-list anything that isn't a local variable.
1796 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1797 return false;
1798
1799 // Types of valid local variables should be complete, so this should succeed.
1800 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1801
1802 // White-list anything with an __attribute__((unused)) type.
1803 const auto *Ty = VD->getType().getTypePtr();
1804
1805 // Only look at the outermost level of typedef.
1806 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1807 if (TT->getDecl()->hasAttr<UnusedAttr>())
1808 return false;
1809 }
1810
1811 // If we failed to complete the type for some reason, or if the type is
1812 // dependent, don't diagnose the variable.
1813 if (Ty->isIncompleteType() || Ty->isDependentType())
1814 return false;
1815
1816 // Look at the element type to ensure that the warning behaviour is
1817 // consistent for both scalars and arrays.
1818 Ty = Ty->getBaseElementTypeUnsafe();
1819
1820 if (const TagType *TT = Ty->getAs<TagType>()) {
1821 const TagDecl *Tag = TT->getDecl();
1822 if (Tag->hasAttr<UnusedAttr>())
1823 return false;
1824
1825 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1826 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1827 return false;
1828
1829 if (const Expr *Init = VD->getInit()) {
1830 if (const ExprWithCleanups *Cleanups =
1831 dyn_cast<ExprWithCleanups>(Init))
1832 Init = Cleanups->getSubExpr();
1833 const CXXConstructExpr *Construct =
1834 dyn_cast<CXXConstructExpr>(Init);
1835 if (Construct && !Construct->isElidable()) {
1836 CXXConstructorDecl *CD = Construct->getConstructor();
1837 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1838 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1839 return false;
1840 }
1841
1842 // Suppress the warning if we don't know how this is constructed, and
1843 // it could possibly be non-trivial constructor.
1844 if (Init->isTypeDependent())
1845 for (const CXXConstructorDecl *Ctor : RD->ctors())
1846 if (!Ctor->isTrivial())
1847 return false;
1848 }
1849 }
1850 }
1851
1852 // TODO: __attribute__((unused)) templates?
1853 }
1854
1855 return true;
1856}
1857
1858static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1859 FixItHint &Hint) {
1860 if (isa<LabelDecl>(D)) {
1861 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1862 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1863 true);
1864 if (AfterColon.isInvalid())
1865 return;
1866 Hint = FixItHint::CreateRemoval(
1867 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1868 }
1869}
1870
1871void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1872 if (D->getTypeForDecl()->isDependentType())
1873 return;
1874
1875 for (auto *TmpD : D->decls()) {
1876 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1877 DiagnoseUnusedDecl(T);
1878 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1879 DiagnoseUnusedNestedTypedefs(R);
1880 }
1881}
1882
1883/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1884/// unless they are marked attr(unused).
1885void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1886 if (!ShouldDiagnoseUnusedDecl(D))
1887 return;
1888
1889 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1890 // typedefs can be referenced later on, so the diagnostics are emitted
1891 // at end-of-translation-unit.
1892 UnusedLocalTypedefNameCandidates.insert(TD);
1893 return;
1894 }
1895
1896 FixItHint Hint;
1897 GenerateFixForUnusedDecl(D, Context, Hint);
1898
1899 unsigned DiagID;
1900 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1901 DiagID = diag::warn_unused_exception_param;
1902 else if (isa<LabelDecl>(D))
1903 DiagID = diag::warn_unused_label;
1904 else
1905 DiagID = diag::warn_unused_variable;
1906
1907 Diag(D->getLocation(), DiagID) << D << Hint;
1908}
1909
1910static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1911 // Verify that we have no forward references left. If so, there was a goto
1912 // or address of a label taken, but no definition of it. Label fwd
1913 // definitions are indicated with a null substmt which is also not a resolved
1914 // MS inline assembly label name.
1915 bool Diagnose = false;
1916 if (L->isMSAsmLabel())
1917 Diagnose = !L->isResolvedMSAsmLabel();
1918 else
1919 Diagnose = L->getStmt() == nullptr;
1920 if (Diagnose)
1921 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1922}
1923
1924void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1925 S->mergeNRVOIntoParent();
1926
1927 if (S->decl_empty()) return;
1928 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1929, __PRETTY_FUNCTION__))
1929 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1929, __PRETTY_FUNCTION__))
;
1930
1931 for (auto *TmpD : S->decls()) {
1932 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
;
1933
1934 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 1934, __PRETTY_FUNCTION__))
;
1935 NamedDecl *D = cast<NamedDecl>(TmpD);
1936
1937 // Diagnose unused variables in this scope.
1938 if (!S->hasUnrecoverableErrorOccurred()) {
1939 DiagnoseUnusedDecl(D);
1940 if (const auto *RD = dyn_cast<RecordDecl>(D))
1941 DiagnoseUnusedNestedTypedefs(RD);
1942 }
1943
1944 if (!D->getDeclName()) continue;
1945
1946 // If this was a forward reference to a label, verify it was defined.
1947 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1948 CheckPoppedLabel(LD, *this);
1949
1950 // Remove this name from our lexical scope, and warn on it if we haven't
1951 // already.
1952 IdResolver.RemoveDecl(D);
1953 auto ShadowI = ShadowingDecls.find(D);
1954 if (ShadowI != ShadowingDecls.end()) {
1955 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1956 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1957 << D << FD << FD->getParent();
1958 Diag(FD->getLocation(), diag::note_previous_declaration);
1959 }
1960 ShadowingDecls.erase(ShadowI);
1961 }
1962 }
1963}
1964
1965/// Look for an Objective-C class in the translation unit.
1966///
1967/// \param Id The name of the Objective-C class we're looking for. If
1968/// typo-correction fixes this name, the Id will be updated
1969/// to the fixed name.
1970///
1971/// \param IdLoc The location of the name in the translation unit.
1972///
1973/// \param DoTypoCorrection If true, this routine will attempt typo correction
1974/// if there is no class with the given name.
1975///
1976/// \returns The declaration of the named Objective-C class, or NULL if the
1977/// class could not be found.
1978ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1979 SourceLocation IdLoc,
1980 bool DoTypoCorrection) {
1981 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1982 // creation from this context.
1983 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1984
1985 if (!IDecl && DoTypoCorrection) {
1986 // Perform typo correction at the given location, but only if we
1987 // find an Objective-C class name.
1988 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1989 if (TypoCorrection C =
1990 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1991 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1992 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1993 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1994 Id = IDecl->getIdentifier();
1995 }
1996 }
1997 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1998 // This routine must always return a class definition, if any.
1999 if (Def && Def->getDefinition())
2000 Def = Def->getDefinition();
2001 return Def;
2002}
2003
2004/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2005/// from S, where a non-field would be declared. This routine copes
2006/// with the difference between C and C++ scoping rules in structs and
2007/// unions. For example, the following code is well-formed in C but
2008/// ill-formed in C++:
2009/// @code
2010/// struct S6 {
2011/// enum { BAR } e;
2012/// };
2013///
2014/// void test_S6() {
2015/// struct S6 a;
2016/// a.e = BAR;
2017/// }
2018/// @endcode
2019/// For the declaration of BAR, this routine will return a different
2020/// scope. The scope S will be the scope of the unnamed enumeration
2021/// within S6. In C++, this routine will return the scope associated
2022/// with S6, because the enumeration's scope is a transparent
2023/// context but structures can contain non-field names. In C, this
2024/// routine will return the translation unit scope, since the
2025/// enumeration's scope is a transparent context and structures cannot
2026/// contain non-field names.
2027Scope *Sema::getNonFieldDeclScope(Scope *S) {
2028 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2029 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2030 (S->isClassScope() && !getLangOpts().CPlusPlus))
2031 S = S->getParent();
2032 return S;
2033}
2034
2035static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2036 ASTContext::GetBuiltinTypeError Error) {
2037 switch (Error) {
2038 case ASTContext::GE_None:
2039 return "";
2040 case ASTContext::GE_Missing_type:
2041 return BuiltinInfo.getHeaderName(ID);
2042 case ASTContext::GE_Missing_stdio:
2043 return "stdio.h";
2044 case ASTContext::GE_Missing_setjmp:
2045 return "setjmp.h";
2046 case ASTContext::GE_Missing_ucontext:
2047 return "ucontext.h";
2048 }
2049 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 2049)
;
2050}
2051
2052FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2053 unsigned ID, SourceLocation Loc) {
2054 DeclContext *Parent = Context.getTranslationUnitDecl();
2055
2056 if (getLangOpts().CPlusPlus) {
2057 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2058 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2059 CLinkageDecl->setImplicit();
2060 Parent->addDecl(CLinkageDecl);
2061 Parent = CLinkageDecl;
2062 }
2063
2064 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2065 /*TInfo=*/nullptr, SC_Extern, false,
2066 Type->isFunctionProtoType());
2067 New->setImplicit();
2068 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2069
2070 // Create Decl objects for each parameter, adding them to the
2071 // FunctionDecl.
2072 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2073 SmallVector<ParmVarDecl *, 16> Params;
2074 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2075 ParmVarDecl *parm = ParmVarDecl::Create(
2076 Context, New, SourceLocation(), SourceLocation(), nullptr,
2077 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2078 parm->setScopeInfo(0, i);
2079 Params.push_back(parm);
2080 }
2081 New->setParams(Params);
2082 }
2083
2084 AddKnownFunctionAttributes(New);
2085 return New;
2086}
2087
2088/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2089/// file scope. lazily create a decl for it. ForRedeclaration is true
2090/// if we're creating this built-in in anticipation of redeclaring the
2091/// built-in.
2092NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2093 Scope *S, bool ForRedeclaration,
2094 SourceLocation Loc) {
2095 LookupNecessaryTypesForBuiltin(S, ID);
2096
2097 ASTContext::GetBuiltinTypeError Error;
2098 QualType R = Context.GetBuiltinType(ID, Error);
2099 if (Error) {
2100 if (!ForRedeclaration)
2101 return nullptr;
2102
2103 // If we have a builtin without an associated type we should not emit a
2104 // warning when we were not able to find a type for it.
2105 if (Error == ASTContext::GE_Missing_type ||
2106 Context.BuiltinInfo.allowTypeMismatch(ID))
2107 return nullptr;
2108
2109 // If we could not find a type for setjmp it is because the jmp_buf type was
2110 // not defined prior to the setjmp declaration.
2111 if (Error == ASTContext::GE_Missing_setjmp) {
2112 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2113 << Context.BuiltinInfo.getName(ID);
2114 return nullptr;
2115 }
2116
2117 // Generally, we emit a warning that the declaration requires the
2118 // appropriate header.
2119 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2120 << getHeaderName(Context.BuiltinInfo, ID, Error)
2121 << Context.BuiltinInfo.getName(ID);
2122 return nullptr;
2123 }
2124
2125 if (!ForRedeclaration &&
2126 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2127 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2128 Diag(Loc, diag::ext_implicit_lib_function_decl)
2129 << Context.BuiltinInfo.getName(ID) << R;
2130 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2131 Diag(Loc, diag::note_include_header_or_declare)
2132 << Header << Context.BuiltinInfo.getName(ID);
2133 }
2134
2135 if (R.isNull())
2136 return nullptr;
2137
2138 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2139 RegisterLocallyScopedExternCDecl(New, S);
2140
2141 // TUScope is the translation-unit scope to insert this function into.
2142 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2143 // relate Scopes to DeclContexts, and probably eliminate CurContext
2144 // entirely, but we're not there yet.
2145 DeclContext *SavedContext = CurContext;
2146 CurContext = New->getDeclContext();
2147 PushOnScopeChains(New, TUScope);
2148 CurContext = SavedContext;
2149 return New;
2150}
2151
2152/// Typedef declarations don't have linkage, but they still denote the same
2153/// entity if their types are the same.
2154/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2155/// isSameEntity.
2156static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2157 TypedefNameDecl *Decl,
2158 LookupResult &Previous) {
2159 // This is only interesting when modules are enabled.
2160 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2161 return;
2162
2163 // Empty sets are uninteresting.
2164 if (Previous.empty())
2165 return;
2166
2167 LookupResult::Filter Filter = Previous.makeFilter();
2168 while (Filter.hasNext()) {
2169 NamedDecl *Old = Filter.next();
2170
2171 // Non-hidden declarations are never ignored.
2172 if (S.isVisible(Old))
2173 continue;
2174
2175 // Declarations of the same entity are not ignored, even if they have
2176 // different linkages.
2177 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2178 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2179 Decl->getUnderlyingType()))
2180 continue;
2181
2182 // If both declarations give a tag declaration a typedef name for linkage
2183 // purposes, then they declare the same entity.
2184 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2185 Decl->getAnonDeclWithTypedefName())
2186 continue;
2187 }
2188
2189 Filter.erase();
2190 }
2191
2192 Filter.done();
2193}
2194
2195bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2196 QualType OldType;
2197 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2198 OldType = OldTypedef->getUnderlyingType();
2199 else
2200 OldType = Context.getTypeDeclType(Old);
2201 QualType NewType = New->getUnderlyingType();
2202
2203 if (NewType->isVariablyModifiedType()) {
2204 // Must not redefine a typedef with a variably-modified type.
2205 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2206 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2207 << Kind << NewType;
2208 if (Old->getLocation().isValid())
2209 notePreviousDefinition(Old, New->getLocation());
2210 New->setInvalidDecl();
2211 return true;
2212 }
2213
2214 if (OldType != NewType &&
2215 !OldType->isDependentType() &&
2216 !NewType->isDependentType() &&
2217 !Context.hasSameType(OldType, NewType)) {
2218 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2219 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2220 << Kind << NewType << OldType;
2221 if (Old->getLocation().isValid())
2222 notePreviousDefinition(Old, New->getLocation());
2223 New->setInvalidDecl();
2224 return true;
2225 }
2226 return false;
2227}
2228
2229/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2230/// same name and scope as a previous declaration 'Old'. Figure out
2231/// how to resolve this situation, merging decls or emitting
2232/// diagnostics as appropriate. If there was an error, set New to be invalid.
2233///
2234void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2235 LookupResult &OldDecls) {
2236 // If the new decl is known invalid already, don't bother doing any
2237 // merging checks.
2238 if (New->isInvalidDecl()) return;
2239
2240 // Allow multiple definitions for ObjC built-in typedefs.
2241 // FIXME: Verify the underlying types are equivalent!
2242 if (getLangOpts().ObjC) {
2243 const IdentifierInfo *TypeID = New->getIdentifier();
2244 switch (TypeID->getLength()) {
2245 default: break;
2246 case 2:
2247 {
2248 if (!TypeID->isStr("id"))
2249 break;
2250 QualType T = New->getUnderlyingType();
2251 if (!T->isPointerType())
2252 break;
2253 if (!T->isVoidPointerType()) {
2254 QualType PT = T->castAs<PointerType>()->getPointeeType();
2255 if (!PT->isStructureType())
2256 break;
2257 }
2258 Context.setObjCIdRedefinitionType(T);
2259 // Install the built-in type for 'id', ignoring the current definition.
2260 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2261 return;
2262 }
2263 case 5:
2264 if (!TypeID->isStr("Class"))
2265 break;
2266 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2267 // Install the built-in type for 'Class', ignoring the current definition.
2268 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2269 return;
2270 case 3:
2271 if (!TypeID->isStr("SEL"))
2272 break;
2273 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2274 // Install the built-in type for 'SEL', ignoring the current definition.
2275 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2276 return;
2277 }
2278 // Fall through - the typedef name was not a builtin type.
2279 }
2280
2281 // Verify the old decl was also a type.
2282 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2283 if (!Old) {
2284 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2285 << New->getDeclName();
2286
2287 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2288 if (OldD->getLocation().isValid())
2289 notePreviousDefinition(OldD, New->getLocation());
2290
2291 return New->setInvalidDecl();
2292 }
2293
2294 // If the old declaration is invalid, just give up here.
2295 if (Old->isInvalidDecl())
2296 return New->setInvalidDecl();
2297
2298 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2299 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2300 auto *NewTag = New->getAnonDeclWithTypedefName();
2301 NamedDecl *Hidden = nullptr;
2302 if (OldTag && NewTag &&
2303 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2304 !hasVisibleDefinition(OldTag, &Hidden)) {
2305 // There is a definition of this tag, but it is not visible. Use it
2306 // instead of our tag.
2307 New->setTypeForDecl(OldTD->getTypeForDecl());
2308 if (OldTD->isModed())
2309 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2310 OldTD->getUnderlyingType());
2311 else
2312 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2313
2314 // Make the old tag definition visible.
2315 makeMergedDefinitionVisible(Hidden);
2316
2317 // If this was an unscoped enumeration, yank all of its enumerators
2318 // out of the scope.
2319 if (isa<EnumDecl>(NewTag)) {
2320 Scope *EnumScope = getNonFieldDeclScope(S);
2321 for (auto *D : NewTag->decls()) {
2322 auto *ED = cast<EnumConstantDecl>(D);
2323 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 2323, __PRETTY_FUNCTION__))
;
2324 EnumScope->RemoveDecl(ED);
2325 IdResolver.RemoveDecl(ED);
2326 ED->getLexicalDeclContext()->removeDecl(ED);
2327 }
2328 }
2329 }
2330 }
2331
2332 // If the typedef types are not identical, reject them in all languages and
2333 // with any extensions enabled.
2334 if (isIncompatibleTypedef(Old, New))
2335 return;
2336
2337 // The types match. Link up the redeclaration chain and merge attributes if
2338 // the old declaration was a typedef.
2339 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2340 New->setPreviousDecl(Typedef);
2341 mergeDeclAttributes(New, Old);
2342 }
2343
2344 if (getLangOpts().MicrosoftExt)
2345 return;
2346
2347 if (getLangOpts().CPlusPlus) {
2348 // C++ [dcl.typedef]p2:
2349 // In a given non-class scope, a typedef specifier can be used to
2350 // redefine the name of any type declared in that scope to refer
2351 // to the type to which it already refers.
2352 if (!isa<CXXRecordDecl>(CurContext))
2353 return;
2354
2355 // C++0x [dcl.typedef]p4:
2356 // In a given class scope, a typedef specifier can be used to redefine
2357 // any class-name declared in that scope that is not also a typedef-name
2358 // to refer to the type to which it already refers.
2359 //
2360 // This wording came in via DR424, which was a correction to the
2361 // wording in DR56, which accidentally banned code like:
2362 //
2363 // struct S {
2364 // typedef struct A { } A;
2365 // };
2366 //
2367 // in the C++03 standard. We implement the C++0x semantics, which
2368 // allow the above but disallow
2369 //
2370 // struct S {
2371 // typedef int I;
2372 // typedef int I;
2373 // };
2374 //
2375 // since that was the intent of DR56.
2376 if (!isa<TypedefNameDecl>(Old))
2377 return;
2378
2379 Diag(New->getLocation(), diag::err_redefinition)
2380 << New->getDeclName();
2381 notePreviousDefinition(Old, New->getLocation());
2382 return New->setInvalidDecl();
2383 }
2384
2385 // Modules always permit redefinition of typedefs, as does C11.
2386 if (getLangOpts().Modules || getLangOpts().C11)
2387 return;
2388
2389 // If we have a redefinition of a typedef in C, emit a warning. This warning
2390 // is normally mapped to an error, but can be controlled with
2391 // -Wtypedef-redefinition. If either the original or the redefinition is
2392 // in a system header, don't emit this for compatibility with GCC.
2393 if (getDiagnostics().getSuppressSystemWarnings() &&
2394 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2395 (Old->isImplicit() ||
2396 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2397 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2398 return;
2399
2400 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2401 << New->getDeclName();
2402 notePreviousDefinition(Old, New->getLocation());
2403}
2404
2405/// DeclhasAttr - returns true if decl Declaration already has the target
2406/// attribute.
2407static bool DeclHasAttr(const Decl *D, const Attr *A) {
2408 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2409 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2410 for (const auto *i : D->attrs())
2411 if (i->getKind() == A->getKind()) {
2412 if (Ann) {
2413 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2414 return true;
2415 continue;
2416 }
2417 // FIXME: Don't hardcode this check
2418 if (OA && isa<OwnershipAttr>(i))
2419 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2420 return true;
2421 }
2422
2423 return false;
2424}
2425
2426static bool isAttributeTargetADefinition(Decl *D) {
2427 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2428 return VD->isThisDeclarationADefinition();
2429 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2430 return TD->isCompleteDefinition() || TD->isBeingDefined();
2431 return true;
2432}
2433
2434/// Merge alignment attributes from \p Old to \p New, taking into account the
2435/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2436///
2437/// \return \c true if any attributes were added to \p New.
2438static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2439 // Look for alignas attributes on Old, and pick out whichever attribute
2440 // specifies the strictest alignment requirement.
2441 AlignedAttr *OldAlignasAttr = nullptr;
2442 AlignedAttr *OldStrictestAlignAttr = nullptr;
2443 unsigned OldAlign = 0;
2444 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2445 // FIXME: We have no way of representing inherited dependent alignments
2446 // in a case like:
2447 // template<int A, int B> struct alignas(A) X;
2448 // template<int A, int B> struct alignas(B) X {};
2449 // For now, we just ignore any alignas attributes which are not on the
2450 // definition in such a case.
2451 if (I->isAlignmentDependent())
2452 return false;
2453
2454 if (I->isAlignas())
2455 OldAlignasAttr = I;
2456
2457 unsigned Align = I->getAlignment(S.Context);
2458 if (Align > OldAlign) {
2459 OldAlign = Align;
2460 OldStrictestAlignAttr = I;
2461 }
2462 }
2463
2464 // Look for alignas attributes on New.
2465 AlignedAttr *NewAlignasAttr = nullptr;
2466 unsigned NewAlign = 0;
2467 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2468 if (I->isAlignmentDependent())
2469 return false;
2470
2471 if (I->isAlignas())
2472 NewAlignasAttr = I;
2473
2474 unsigned Align = I->getAlignment(S.Context);
2475 if (Align > NewAlign)
2476 NewAlign = Align;
2477 }
2478
2479 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2480 // Both declarations have 'alignas' attributes. We require them to match.
2481 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2482 // fall short. (If two declarations both have alignas, they must both match
2483 // every definition, and so must match each other if there is a definition.)
2484
2485 // If either declaration only contains 'alignas(0)' specifiers, then it
2486 // specifies the natural alignment for the type.
2487 if (OldAlign == 0 || NewAlign == 0) {
2488 QualType Ty;
2489 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2490 Ty = VD->getType();
2491 else
2492 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2493
2494 if (OldAlign == 0)
2495 OldAlign = S.Context.getTypeAlign(Ty);
2496 if (NewAlign == 0)
2497 NewAlign = S.Context.getTypeAlign(Ty);
2498 }
2499
2500 if (OldAlign != NewAlign) {
2501 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2502 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2503 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2504 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2505 }
2506 }
2507
2508 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2509 // C++11 [dcl.align]p6:
2510 // if any declaration of an entity has an alignment-specifier,
2511 // every defining declaration of that entity shall specify an
2512 // equivalent alignment.
2513 // C11 6.7.5/7:
2514 // If the definition of an object does not have an alignment
2515 // specifier, any other declaration of that object shall also
2516 // have no alignment specifier.
2517 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2518 << OldAlignasAttr;
2519 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2520 << OldAlignasAttr;
2521 }
2522
2523 bool AnyAdded = false;
2524
2525 // Ensure we have an attribute representing the strictest alignment.
2526 if (OldAlign > NewAlign) {
2527 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2528 Clone->setInherited(true);
2529 New->addAttr(Clone);
2530 AnyAdded = true;
2531 }
2532
2533 // Ensure we have an alignas attribute if the old declaration had one.
2534 if (OldAlignasAttr && !NewAlignasAttr &&
2535 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2536 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2537 Clone->setInherited(true);
2538 New->addAttr(Clone);
2539 AnyAdded = true;
2540 }
2541
2542 return AnyAdded;
2543}
2544
2545static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2546 const InheritableAttr *Attr,
2547 Sema::AvailabilityMergeKind AMK) {
2548 // This function copies an attribute Attr from a previous declaration to the
2549 // new declaration D if the new declaration doesn't itself have that attribute
2550 // yet or if that attribute allows duplicates.
2551 // If you're adding a new attribute that requires logic different from
2552 // "use explicit attribute on decl if present, else use attribute from
2553 // previous decl", for example if the attribute needs to be consistent
2554 // between redeclarations, you need to call a custom merge function here.
2555 InheritableAttr *NewAttr = nullptr;
2556 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2557 NewAttr = S.mergeAvailabilityAttr(
2558 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2559 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2560 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2561 AA->getPriority());
2562 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2563 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2564 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2565 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2566 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2567 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2568 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2569 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2570 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2571 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2572 FA->getFirstArg());
2573 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2574 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2575 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2576 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2577 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2578 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2579 IA->getInheritanceModel());
2580 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2581 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2582 &S.Context.Idents.get(AA->getSpelling()));
2583 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2584 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2585 isa<CUDAGlobalAttr>(Attr))) {
2586 // CUDA target attributes are part of function signature for
2587 // overloading purposes and must not be merged.
2588 return false;
2589 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2590 NewAttr = S.mergeMinSizeAttr(D, *MA);
2591 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2592 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2593 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2594 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2595 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2596 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2597 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2598 NewAttr = S.mergeCommonAttr(D, *CommonA);
2599 else if (isa<AlignedAttr>(Attr))
2600 // AlignedAttrs are handled separately, because we need to handle all
2601 // such attributes on a declaration at the same time.
2602 NewAttr = nullptr;
2603 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2604 (AMK == Sema::AMK_Override ||
2605 AMK == Sema::AMK_ProtocolImplementation))
2606 NewAttr = nullptr;
2607 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2608 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2609 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2610 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2611 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2612 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2613 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2614 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2615 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2616 NewAttr = S.mergeImportNameAttr(D, *INA);
2617 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2618 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2619
2620 if (NewAttr) {
2621 NewAttr->setInherited(true);
2622 D->addAttr(NewAttr);
2623 if (isa<MSInheritanceAttr>(NewAttr))
2624 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2625 return true;
2626 }
2627
2628 return false;
2629}
2630
2631static const NamedDecl *getDefinition(const Decl *D) {
2632 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2633 return TD->getDefinition();
2634 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2635 const VarDecl *Def = VD->getDefinition();
2636 if (Def)
2637 return Def;
2638 return VD->getActingDefinition();
2639 }
2640 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2641 const FunctionDecl *Def = nullptr;
2642 if (FD->isDefined(Def, true))
2643 return Def;
2644 }
2645 return nullptr;
2646}
2647
2648static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2649 for (const auto *Attribute : D->attrs())
2650 if (Attribute->getKind() == Kind)
2651 return true;
2652 return false;
2653}
2654
2655/// checkNewAttributesAfterDef - If we already have a definition, check that
2656/// there are no new attributes in this declaration.
2657static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2658 if (!New->hasAttrs())
2659 return;
2660
2661 const NamedDecl *Def = getDefinition(Old);
2662 if (!Def || Def == New)
2663 return;
2664
2665 AttrVec &NewAttributes = New->getAttrs();
2666 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2667 const Attr *NewAttribute = NewAttributes[I];
2668
2669 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2670 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2671 Sema::SkipBodyInfo SkipBody;
2672 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2673
2674 // If we're skipping this definition, drop the "alias" attribute.
2675 if (SkipBody.ShouldSkip) {
2676 NewAttributes.erase(NewAttributes.begin() + I);
2677 --E;
2678 continue;
2679 }
2680 } else {
2681 VarDecl *VD = cast<VarDecl>(New);
2682 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2683 VarDecl::TentativeDefinition
2684 ? diag::err_alias_after_tentative
2685 : diag::err_redefinition;
2686 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2687 if (Diag == diag::err_redefinition)
2688 S.notePreviousDefinition(Def, VD->getLocation());
2689 else
2690 S.Diag(Def->getLocation(), diag::note_previous_definition);
2691 VD->setInvalidDecl();
2692 }
2693 ++I;
2694 continue;
2695 }
2696
2697 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2698 // Tentative definitions are only interesting for the alias check above.
2699 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2700 ++I;
2701 continue;
2702 }
2703 }
2704
2705 if (hasAttribute(Def, NewAttribute->getKind())) {
2706 ++I;
2707 continue; // regular attr merging will take care of validating this.
2708 }
2709
2710 if (isa<C11NoReturnAttr>(NewAttribute)) {
2711 // C's _Noreturn is allowed to be added to a function after it is defined.
2712 ++I;
2713 continue;
2714 } else if (isa<UuidAttr>(NewAttribute)) {
2715 // msvc will allow a subsequent definition to add an uuid to a class
2716 ++I;
2717 continue;
2718 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2719 if (AA->isAlignas()) {
2720 // C++11 [dcl.align]p6:
2721 // if any declaration of an entity has an alignment-specifier,
2722 // every defining declaration of that entity shall specify an
2723 // equivalent alignment.
2724 // C11 6.7.5/7:
2725 // If the definition of an object does not have an alignment
2726 // specifier, any other declaration of that object shall also
2727 // have no alignment specifier.
2728 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2729 << AA;
2730 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2731 << AA;
2732 NewAttributes.erase(NewAttributes.begin() + I);
2733 --E;
2734 continue;
2735 }
2736 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2737 // If there is a C definition followed by a redeclaration with this
2738 // attribute then there are two different definitions. In C++, prefer the
2739 // standard diagnostics.
2740 if (!S.getLangOpts().CPlusPlus) {
2741 S.Diag(NewAttribute->getLocation(),
2742 diag::err_loader_uninitialized_redeclaration);
2743 S.Diag(Def->getLocation(), diag::note_previous_definition);
2744 NewAttributes.erase(NewAttributes.begin() + I);
2745 --E;
2746 continue;
2747 }
2748 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2749 cast<VarDecl>(New)->isInline() &&
2750 !cast<VarDecl>(New)->isInlineSpecified()) {
2751 // Don't warn about applying selectany to implicitly inline variables.
2752 // Older compilers and language modes would require the use of selectany
2753 // to make such variables inline, and it would have no effect if we
2754 // honored it.
2755 ++I;
2756 continue;
2757 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2758 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2759 // declarations after defintions.
2760 ++I;
2761 continue;
2762 }
2763
2764 S.Diag(NewAttribute->getLocation(),
2765 diag::warn_attribute_precede_definition);
2766 S.Diag(Def->getLocation(), diag::note_previous_definition);
2767 NewAttributes.erase(NewAttributes.begin() + I);
2768 --E;
2769 }
2770}
2771
2772static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2773 const ConstInitAttr *CIAttr,
2774 bool AttrBeforeInit) {
2775 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2776
2777 // Figure out a good way to write this specifier on the old declaration.
2778 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2779 // enough of the attribute list spelling information to extract that without
2780 // heroics.
2781 std::string SuitableSpelling;
2782 if (S.getLangOpts().CPlusPlus20)
2783 SuitableSpelling = std::string(
2784 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2785 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2786 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2787 InsertLoc, {tok::l_square, tok::l_square,
2788 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2789 S.PP.getIdentifierInfo("require_constant_initialization"),
2790 tok::r_square, tok::r_square}));
2791 if (SuitableSpelling.empty())
2792 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2793 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2794 S.PP.getIdentifierInfo("require_constant_initialization"),
2795 tok::r_paren, tok::r_paren}));
2796 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2797 SuitableSpelling = "constinit";
2798 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2799 SuitableSpelling = "[[clang::require_constant_initialization]]";
2800 if (SuitableSpelling.empty())
2801 SuitableSpelling = "__attribute__((require_constant_initialization))";
2802 SuitableSpelling += " ";
2803
2804 if (AttrBeforeInit) {
2805 // extern constinit int a;
2806 // int a = 0; // error (missing 'constinit'), accepted as extension
2807 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 2807, __PRETTY_FUNCTION__))
;
2808 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2809 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2810 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2811 } else {
2812 // int a = 0;
2813 // constinit extern int a; // error (missing 'constinit')
2814 S.Diag(CIAttr->getLocation(),
2815 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2816 : diag::warn_require_const_init_added_too_late)
2817 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2818 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2819 << CIAttr->isConstinit()
2820 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2821 }
2822}
2823
2824/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2825void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2826 AvailabilityMergeKind AMK) {
2827 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2828 UsedAttr *NewAttr = OldAttr->clone(Context);
2829 NewAttr->setInherited(true);
2830 New->addAttr(NewAttr);
2831 }
2832
2833 if (!Old->hasAttrs() && !New->hasAttrs())
2834 return;
2835
2836 // [dcl.constinit]p1:
2837 // If the [constinit] specifier is applied to any declaration of a
2838 // variable, it shall be applied to the initializing declaration.
2839 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2840 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2841 if (bool(OldConstInit) != bool(NewConstInit)) {
2842 const auto *OldVD = cast<VarDecl>(Old);
2843 auto *NewVD = cast<VarDecl>(New);
2844
2845 // Find the initializing declaration. Note that we might not have linked
2846 // the new declaration into the redeclaration chain yet.
2847 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2848 if (!InitDecl &&
2849 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2850 InitDecl = NewVD;
2851
2852 if (InitDecl == NewVD) {
2853 // This is the initializing declaration. If it would inherit 'constinit',
2854 // that's ill-formed. (Note that we do not apply this to the attribute
2855 // form).
2856 if (OldConstInit && OldConstInit->isConstinit())
2857 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2858 /*AttrBeforeInit=*/true);
2859 } else if (NewConstInit) {
2860 // This is the first time we've been told that this declaration should
2861 // have a constant initializer. If we already saw the initializing
2862 // declaration, this is too late.
2863 if (InitDecl && InitDecl != NewVD) {
2864 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2865 /*AttrBeforeInit=*/false);
2866 NewVD->dropAttr<ConstInitAttr>();
2867 }
2868 }
2869 }
2870
2871 // Attributes declared post-definition are currently ignored.
2872 checkNewAttributesAfterDef(*this, New, Old);
2873
2874 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2875 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2876 if (!OldA->isEquivalent(NewA)) {
2877 // This redeclaration changes __asm__ label.
2878 Diag(New->getLocation(), diag::err_different_asm_label);
2879 Diag(OldA->getLocation(), diag::note_previous_declaration);
2880 }
2881 } else if (Old->isUsed()) {
2882 // This redeclaration adds an __asm__ label to a declaration that has
2883 // already been ODR-used.
2884 Diag(New->getLocation(), diag::err_late_asm_label_name)
2885 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2886 }
2887 }
2888
2889 // Re-declaration cannot add abi_tag's.
2890 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2891 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2892 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2893 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2894 NewTag) == OldAbiTagAttr->tags_end()) {
2895 Diag(NewAbiTagAttr->getLocation(),
2896 diag::err_new_abi_tag_on_redeclaration)
2897 << NewTag;
2898 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2899 }
2900 }
2901 } else {
2902 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2903 Diag(Old->getLocation(), diag::note_previous_declaration);
2904 }
2905 }
2906
2907 // This redeclaration adds a section attribute.
2908 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2909 if (auto *VD = dyn_cast<VarDecl>(New)) {
2910 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2911 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2912 Diag(Old->getLocation(), diag::note_previous_declaration);
2913 }
2914 }
2915 }
2916
2917 // Redeclaration adds code-seg attribute.
2918 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2919 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2920 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2921 Diag(New->getLocation(), diag::warn_mismatched_section)
2922 << 0 /*codeseg*/;
2923 Diag(Old->getLocation(), diag::note_previous_declaration);
2924 }
2925
2926 if (!Old->hasAttrs())
2927 return;
2928
2929 bool foundAny = New->hasAttrs();
2930
2931 // Ensure that any moving of objects within the allocated map is done before
2932 // we process them.
2933 if (!foundAny) New->setAttrs(AttrVec());
2934
2935 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2936 // Ignore deprecated/unavailable/availability attributes if requested.
2937 AvailabilityMergeKind LocalAMK = AMK_None;
2938 if (isa<DeprecatedAttr>(I) ||
2939 isa<UnavailableAttr>(I) ||
2940 isa<AvailabilityAttr>(I)) {
2941 switch (AMK) {
2942 case AMK_None:
2943 continue;
2944
2945 case AMK_Redeclaration:
2946 case AMK_Override:
2947 case AMK_ProtocolImplementation:
2948 LocalAMK = AMK;
2949 break;
2950 }
2951 }
2952
2953 // Already handled.
2954 if (isa<UsedAttr>(I))
2955 continue;
2956
2957 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2958 foundAny = true;
2959 }
2960
2961 if (mergeAlignedAttrs(*this, New, Old))
2962 foundAny = true;
2963
2964 if (!foundAny) New->dropAttrs();
2965}
2966
2967/// mergeParamDeclAttributes - Copy attributes from the old parameter
2968/// to the new one.
2969static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2970 const ParmVarDecl *oldDecl,
2971 Sema &S) {
2972 // C++11 [dcl.attr.depend]p2:
2973 // The first declaration of a function shall specify the
2974 // carries_dependency attribute for its declarator-id if any declaration
2975 // of the function specifies the carries_dependency attribute.
2976 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2977 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2978 S.Diag(CDA->getLocation(),
2979 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2980 // Find the first declaration of the parameter.
2981 // FIXME: Should we build redeclaration chains for function parameters?
2982 const FunctionDecl *FirstFD =
2983 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2984 const ParmVarDecl *FirstVD =
2985 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2986 S.Diag(FirstVD->getLocation(),
2987 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2988 }
2989
2990 if (!oldDecl->hasAttrs())
2991 return;
2992
2993 bool foundAny = newDecl->hasAttrs();
2994
2995 // Ensure that any moving of objects within the allocated map is
2996 // done before we process them.
2997 if (!foundAny) newDecl->setAttrs(AttrVec());
2998
2999 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3000 if (!DeclHasAttr(newDecl, I)) {
3001 InheritableAttr *newAttr =
3002 cast<InheritableParamAttr>(I->clone(S.Context));
3003 newAttr->setInherited(true);
3004 newDecl->addAttr(newAttr);
3005 foundAny = true;
3006 }
3007 }
3008
3009 if (!foundAny) newDecl->dropAttrs();
3010}
3011
3012static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3013 const ParmVarDecl *OldParam,
3014 Sema &S) {
3015 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3016 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3017 if (*Oldnullability != *Newnullability) {
3018 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3019 << DiagNullabilityKind(
3020 *Newnullability,
3021 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3022 != 0))
3023 << DiagNullabilityKind(
3024 *Oldnullability,
3025 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3026 != 0));
3027 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3028 }
3029 } else {
3030 QualType NewT = NewParam->getType();
3031 NewT = S.Context.getAttributedType(
3032 AttributedType::getNullabilityAttrKind(*Oldnullability),
3033 NewT, NewT);
3034 NewParam->setType(NewT);
3035 }
3036 }
3037}
3038
3039namespace {
3040
3041/// Used in MergeFunctionDecl to keep track of function parameters in
3042/// C.
3043struct GNUCompatibleParamWarning {
3044 ParmVarDecl *OldParm;
3045 ParmVarDecl *NewParm;
3046 QualType PromotedType;
3047};
3048
3049} // end anonymous namespace
3050
3051// Determine whether the previous declaration was a definition, implicit
3052// declaration, or a declaration.
3053template <typename T>
3054static std::pair<diag::kind, SourceLocation>
3055getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3056 diag::kind PrevDiag;
3057 SourceLocation OldLocation = Old->getLocation();
3058 if (Old->isThisDeclarationADefinition())
3059 PrevDiag = diag::note_previous_definition;
3060 else if (Old->isImplicit()) {
3061 PrevDiag = diag::note_previous_implicit_declaration;
3062 if (OldLocation.isInvalid())
3063 OldLocation = New->getLocation();
3064 } else
3065 PrevDiag = diag::note_previous_declaration;
3066 return std::make_pair(PrevDiag, OldLocation);
3067}
3068
3069/// canRedefineFunction - checks if a function can be redefined. Currently,
3070/// only extern inline functions can be redefined, and even then only in
3071/// GNU89 mode.
3072static bool canRedefineFunction(const FunctionDecl *FD,
3073 const LangOptions& LangOpts) {
3074 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3075 !LangOpts.CPlusPlus &&
3076 FD->isInlineSpecified() &&
3077 FD->getStorageClass() == SC_Extern);
3078}
3079
3080const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3081 const AttributedType *AT = T->getAs<AttributedType>();
3082 while (AT && !AT->isCallingConv())
3083 AT = AT->getModifiedType()->getAs<AttributedType>();
3084 return AT;
3085}
3086
3087template <typename T>
3088static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3089 const DeclContext *DC = Old->getDeclContext();
3090 if (DC->isRecord())
3091 return false;
3092
3093 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3094 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3095 return true;
3096 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3097 return true;
3098 return false;
3099}
3100
3101template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3102static bool isExternC(VarTemplateDecl *) { return false; }
3103
3104/// Check whether a redeclaration of an entity introduced by a
3105/// using-declaration is valid, given that we know it's not an overload
3106/// (nor a hidden tag declaration).
3107template<typename ExpectedDecl>
3108static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3109 ExpectedDecl *New) {
3110 // C++11 [basic.scope.declarative]p4:
3111 // Given a set of declarations in a single declarative region, each of
3112 // which specifies the same unqualified name,
3113 // -- they shall all refer to the same entity, or all refer to functions
3114 // and function templates; or
3115 // -- exactly one declaration shall declare a class name or enumeration
3116 // name that is not a typedef name and the other declarations shall all
3117 // refer to the same variable or enumerator, or all refer to functions
3118 // and function templates; in this case the class name or enumeration
3119 // name is hidden (3.3.10).
3120
3121 // C++11 [namespace.udecl]p14:
3122 // If a function declaration in namespace scope or block scope has the
3123 // same name and the same parameter-type-list as a function introduced
3124 // by a using-declaration, and the declarations do not declare the same
3125 // function, the program is ill-formed.
3126
3127 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3128 if (Old &&
3129 !Old->getDeclContext()->getRedeclContext()->Equals(
3130 New->getDeclContext()->getRedeclContext()) &&
3131 !(isExternC(Old) && isExternC(New)))
3132 Old = nullptr;
3133
3134 if (!Old) {
3135 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3136 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3137 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3138 return true;
3139 }
3140 return false;
3141}
3142
3143static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3144 const FunctionDecl *B) {
3145 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3145, __PRETTY_FUNCTION__))
;
3146
3147 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3148 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3149 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3150 if (AttrA == AttrB)
3151 return true;
3152 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3153 AttrA->isDynamic() == AttrB->isDynamic();
3154 };
3155
3156 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3157}
3158
3159/// If necessary, adjust the semantic declaration context for a qualified
3160/// declaration to name the correct inline namespace within the qualifier.
3161static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3162 DeclaratorDecl *OldD) {
3163 // The only case where we need to update the DeclContext is when
3164 // redeclaration lookup for a qualified name finds a declaration
3165 // in an inline namespace within the context named by the qualifier:
3166 //
3167 // inline namespace N { int f(); }
3168 // int ::f(); // Sema DC needs adjusting from :: to N::.
3169 //
3170 // For unqualified declarations, the semantic context *can* change
3171 // along the redeclaration chain (for local extern declarations,
3172 // extern "C" declarations, and friend declarations in particular).
3173 if (!NewD->getQualifier())
3174 return;
3175
3176 // NewD is probably already in the right context.
3177 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3178 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3179 if (NamedDC->Equals(SemaDC))
3180 return;
3181
3182 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3184, __PRETTY_FUNCTION__))
3183 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3184, __PRETTY_FUNCTION__))
3184 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3184, __PRETTY_FUNCTION__))
;
3185
3186 auto *LexDC = NewD->getLexicalDeclContext();
3187 auto FixSemaDC = [=](NamedDecl *D) {
3188 if (!D)
3189 return;
3190 D->setDeclContext(SemaDC);
3191 D->setLexicalDeclContext(LexDC);
3192 };
3193
3194 FixSemaDC(NewD);
3195 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3196 FixSemaDC(FD->getDescribedFunctionTemplate());
3197 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3198 FixSemaDC(VD->getDescribedVarTemplate());
3199}
3200
3201/// MergeFunctionDecl - We just parsed a function 'New' from
3202/// declarator D which has the same name and scope as a previous
3203/// declaration 'Old'. Figure out how to resolve this situation,
3204/// merging decls or emitting diagnostics as appropriate.
3205///
3206/// In C++, New and Old must be declarations that are not
3207/// overloaded. Use IsOverload to determine whether New and Old are
3208/// overloaded, and to select the Old declaration that New should be
3209/// merged with.
3210///
3211/// Returns true if there was an error, false otherwise.
3212bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3213 Scope *S, bool MergeTypeWithOld) {
3214 // Verify the old decl was also a function.
3215 FunctionDecl *Old = OldD->getAsFunction();
3216 if (!Old) {
3217 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3218 if (New->getFriendObjectKind()) {
3219 Diag(New->getLocation(), diag::err_using_decl_friend);
3220 Diag(Shadow->getTargetDecl()->getLocation(),
3221 diag::note_using_decl_target);
3222 Diag(Shadow->getUsingDecl()->getLocation(),
3223 diag::note_using_decl) << 0;
3224 return true;
3225 }
3226
3227 // Check whether the two declarations might declare the same function.
3228 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3229 return true;
3230 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3231 } else {
3232 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3233 << New->getDeclName();
3234 notePreviousDefinition(OldD, New->getLocation());
3235 return true;
3236 }
3237 }
3238
3239 // If the old declaration is invalid, just give up here.
3240 if (Old->isInvalidDecl())
3241 return true;
3242
3243 // Disallow redeclaration of some builtins.
3244 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3245 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3246 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3247 << Old << Old->getType();
3248 return true;
3249 }
3250
3251 diag::kind PrevDiag;
3252 SourceLocation OldLocation;
3253 std::tie(PrevDiag, OldLocation) =
3254 getNoteDiagForInvalidRedeclaration(Old, New);
3255
3256 // Don't complain about this if we're in GNU89 mode and the old function
3257 // is an extern inline function.
3258 // Don't complain about specializations. They are not supposed to have
3259 // storage classes.
3260 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3261 New->getStorageClass() == SC_Static &&
3262 Old->hasExternalFormalLinkage() &&
3263 !New->getTemplateSpecializationInfo() &&
3264 !canRedefineFunction(Old, getLangOpts())) {
3265 if (getLangOpts().MicrosoftExt) {
3266 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3267 Diag(OldLocation, PrevDiag);
3268 } else {
3269 Diag(New->getLocation(), diag::err_static_non_static) << New;
3270 Diag(OldLocation, PrevDiag);
3271 return true;
3272 }
3273 }
3274
3275 if (New->hasAttr<InternalLinkageAttr>() &&
3276 !Old->hasAttr<InternalLinkageAttr>()) {
3277 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3278 << New->getDeclName();
3279 notePreviousDefinition(Old, New->getLocation());
3280 New->dropAttr<InternalLinkageAttr>();
3281 }
3282
3283 if (CheckRedeclarationModuleOwnership(New, Old))
3284 return true;
3285
3286 if (!getLangOpts().CPlusPlus) {
3287 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3288 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3289 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3290 << New << OldOvl;
3291
3292 // Try our best to find a decl that actually has the overloadable
3293 // attribute for the note. In most cases (e.g. programs with only one
3294 // broken declaration/definition), this won't matter.
3295 //
3296 // FIXME: We could do this if we juggled some extra state in
3297 // OverloadableAttr, rather than just removing it.
3298 const Decl *DiagOld = Old;
3299 if (OldOvl) {
3300 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3301 const auto *A = D->getAttr<OverloadableAttr>();
3302 return A && !A->isImplicit();
3303 });
3304 // If we've implicitly added *all* of the overloadable attrs to this
3305 // chain, emitting a "previous redecl" note is pointless.
3306 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3307 }
3308
3309 if (DiagOld)
3310 Diag(DiagOld->getLocation(),
3311 diag::note_attribute_overloadable_prev_overload)
3312 << OldOvl;
3313
3314 if (OldOvl)
3315 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3316 else
3317 New->dropAttr<OverloadableAttr>();
3318 }
3319 }
3320
3321 // If a function is first declared with a calling convention, but is later
3322 // declared or defined without one, all following decls assume the calling
3323 // convention of the first.
3324 //
3325 // It's OK if a function is first declared without a calling convention,
3326 // but is later declared or defined with the default calling convention.
3327 //
3328 // To test if either decl has an explicit calling convention, we look for
3329 // AttributedType sugar nodes on the type as written. If they are missing or
3330 // were canonicalized away, we assume the calling convention was implicit.
3331 //
3332 // Note also that we DO NOT return at this point, because we still have
3333 // other tests to run.
3334 QualType OldQType = Context.getCanonicalType(Old->getType());
3335 QualType NewQType = Context.getCanonicalType(New->getType());
3336 const FunctionType *OldType = cast<FunctionType>(OldQType);
3337 const FunctionType *NewType = cast<FunctionType>(NewQType);
3338 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3339 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3340 bool RequiresAdjustment = false;
3341
3342 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3343 FunctionDecl *First = Old->getFirstDecl();
3344 const FunctionType *FT =
3345 First->getType().getCanonicalType()->castAs<FunctionType>();
3346 FunctionType::ExtInfo FI = FT->getExtInfo();
3347 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3348 if (!NewCCExplicit) {
3349 // Inherit the CC from the previous declaration if it was specified
3350 // there but not here.
3351 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3352 RequiresAdjustment = true;
3353 } else if (Old->getBuiltinID()) {
3354 // Builtin attribute isn't propagated to the new one yet at this point,
3355 // so we check if the old one is a builtin.
3356
3357 // Calling Conventions on a Builtin aren't really useful and setting a
3358 // default calling convention and cdecl'ing some builtin redeclarations is
3359 // common, so warn and ignore the calling convention on the redeclaration.
3360 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3361 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3362 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3363 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3364 RequiresAdjustment = true;
3365 } else {
3366 // Calling conventions aren't compatible, so complain.
3367 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3368 Diag(New->getLocation(), diag::err_cconv_change)
3369 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3370 << !FirstCCExplicit
3371 << (!FirstCCExplicit ? "" :
3372 FunctionType::getNameForCallConv(FI.getCC()));
3373
3374 // Put the note on the first decl, since it is the one that matters.
3375 Diag(First->getLocation(), diag::note_previous_declaration);
3376 return true;
3377 }
3378 }
3379
3380 // FIXME: diagnose the other way around?
3381 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3382 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3383 RequiresAdjustment = true;
3384 }
3385
3386 // Merge regparm attribute.
3387 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3388 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3389 if (NewTypeInfo.getHasRegParm()) {
3390 Diag(New->getLocation(), diag::err_regparm_mismatch)
3391 << NewType->getRegParmType()
3392 << OldType->getRegParmType();
3393 Diag(OldLocation, diag::note_previous_declaration);
3394 return true;
3395 }
3396
3397 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3398 RequiresAdjustment = true;
3399 }
3400
3401 // Merge ns_returns_retained attribute.
3402 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3403 if (NewTypeInfo.getProducesResult()) {
3404 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3405 << "'ns_returns_retained'";
3406 Diag(OldLocation, diag::note_previous_declaration);
3407 return true;
3408 }
3409
3410 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3411 RequiresAdjustment = true;
3412 }
3413
3414 if (OldTypeInfo.getNoCallerSavedRegs() !=
3415 NewTypeInfo.getNoCallerSavedRegs()) {
3416 if (NewTypeInfo.getNoCallerSavedRegs()) {
3417 AnyX86NoCallerSavedRegistersAttr *Attr =
3418 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3419 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3420 Diag(OldLocation, diag::note_previous_declaration);
3421 return true;
3422 }
3423
3424 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3425 RequiresAdjustment = true;
3426 }
3427
3428 if (RequiresAdjustment) {
3429 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3430 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3431 New->setType(QualType(AdjustedType, 0));
3432 NewQType = Context.getCanonicalType(New->getType());
3433 }
3434
3435 // If this redeclaration makes the function inline, we may need to add it to
3436 // UndefinedButUsed.
3437 if (!Old->isInlined() && New->isInlined() &&
3438 !New->hasAttr<GNUInlineAttr>() &&
3439 !getLangOpts().GNUInline &&
3440 Old->isUsed(false) &&
3441 !Old->isDefined() && !New->isThisDeclarationADefinition())
3442 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3443 SourceLocation()));
3444
3445 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3446 // about it.
3447 if (New->hasAttr<GNUInlineAttr>() &&
3448 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3449 UndefinedButUsed.erase(Old->getCanonicalDecl());
3450 }
3451
3452 // If pass_object_size params don't match up perfectly, this isn't a valid
3453 // redeclaration.
3454 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3455 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3456 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3457 << New->getDeclName();
3458 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3459 return true;
3460 }
3461
3462 if (getLangOpts().CPlusPlus) {
3463 // C++1z [over.load]p2
3464 // Certain function declarations cannot be overloaded:
3465 // -- Function declarations that differ only in the return type,
3466 // the exception specification, or both cannot be overloaded.
3467
3468 // Check the exception specifications match. This may recompute the type of
3469 // both Old and New if it resolved exception specifications, so grab the
3470 // types again after this. Because this updates the type, we do this before
3471 // any of the other checks below, which may update the "de facto" NewQType
3472 // but do not necessarily update the type of New.
3473 if (CheckEquivalentExceptionSpec(Old, New))
3474 return true;
3475 OldQType = Context.getCanonicalType(Old->getType());
3476 NewQType = Context.getCanonicalType(New->getType());
3477
3478 // Go back to the type source info to compare the declared return types,
3479 // per C++1y [dcl.type.auto]p13:
3480 // Redeclarations or specializations of a function or function template
3481 // with a declared return type that uses a placeholder type shall also
3482 // use that placeholder, not a deduced type.
3483 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3484 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3485 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3486 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3487 OldDeclaredReturnType)) {
3488 QualType ResQT;
3489 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3490 OldDeclaredReturnType->isObjCObjectPointerType())
3491 // FIXME: This does the wrong thing for a deduced return type.
3492 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3493 if (ResQT.isNull()) {
3494 if (New->isCXXClassMember() && New->isOutOfLine())
3495 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3496 << New << New->getReturnTypeSourceRange();
3497 else
3498 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3499 << New->getReturnTypeSourceRange();
3500 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3501 << Old->getReturnTypeSourceRange();
3502 return true;
3503 }
3504 else
3505 NewQType = ResQT;
3506 }
3507
3508 QualType OldReturnType = OldType->getReturnType();
3509 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3510 if (OldReturnType != NewReturnType) {
3511 // If this function has a deduced return type and has already been
3512 // defined, copy the deduced value from the old declaration.
3513 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3514 if (OldAT && OldAT->isDeduced()) {
3515 New->setType(
3516 SubstAutoType(New->getType(),
3517 OldAT->isDependentType() ? Context.DependentTy
3518 : OldAT->getDeducedType()));
3519 NewQType = Context.getCanonicalType(
3520 SubstAutoType(NewQType,
3521 OldAT->isDependentType() ? Context.DependentTy
3522 : OldAT->getDeducedType()));
3523 }
3524 }
3525
3526 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3527 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3528 if (OldMethod && NewMethod) {
3529 // Preserve triviality.
3530 NewMethod->setTrivial(OldMethod->isTrivial());
3531
3532 // MSVC allows explicit template specialization at class scope:
3533 // 2 CXXMethodDecls referring to the same function will be injected.
3534 // We don't want a redeclaration error.
3535 bool IsClassScopeExplicitSpecialization =
3536 OldMethod->isFunctionTemplateSpecialization() &&
3537 NewMethod->isFunctionTemplateSpecialization();
3538 bool isFriend = NewMethod->getFriendObjectKind();
3539
3540 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3541 !IsClassScopeExplicitSpecialization) {
3542 // -- Member function declarations with the same name and the
3543 // same parameter types cannot be overloaded if any of them
3544 // is a static member function declaration.
3545 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3547 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3548 return true;
3549 }
3550
3551 // C++ [class.mem]p1:
3552 // [...] A member shall not be declared twice in the
3553 // member-specification, except that a nested class or member
3554 // class template can be declared and then later defined.
3555 if (!inTemplateInstantiation()) {
3556 unsigned NewDiag;
3557 if (isa<CXXConstructorDecl>(OldMethod))
3558 NewDiag = diag::err_constructor_redeclared;
3559 else if (isa<CXXDestructorDecl>(NewMethod))
3560 NewDiag = diag::err_destructor_redeclared;
3561 else if (isa<CXXConversionDecl>(NewMethod))
3562 NewDiag = diag::err_conv_function_redeclared;
3563 else
3564 NewDiag = diag::err_member_redeclared;
3565
3566 Diag(New->getLocation(), NewDiag);
3567 } else {
3568 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3569 << New << New->getType();
3570 }
3571 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3572 return true;
3573
3574 // Complain if this is an explicit declaration of a special
3575 // member that was initially declared implicitly.
3576 //
3577 // As an exception, it's okay to befriend such methods in order
3578 // to permit the implicit constructor/destructor/operator calls.
3579 } else if (OldMethod->isImplicit()) {
3580 if (isFriend) {
3581 NewMethod->setImplicit();
3582 } else {
3583 Diag(NewMethod->getLocation(),
3584 diag::err_definition_of_implicitly_declared_member)
3585 << New << getSpecialMember(OldMethod);
3586 return true;
3587 }
3588 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3589 Diag(NewMethod->getLocation(),
3590 diag::err_definition_of_explicitly_defaulted_member)
3591 << getSpecialMember(OldMethod);
3592 return true;
3593 }
3594 }
3595
3596 // C++11 [dcl.attr.noreturn]p1:
3597 // The first declaration of a function shall specify the noreturn
3598 // attribute if any declaration of that function specifies the noreturn
3599 // attribute.
3600 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3601 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3602 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3603 Diag(Old->getFirstDecl()->getLocation(),
3604 diag::note_noreturn_missing_first_decl);
3605 }
3606
3607 // C++11 [dcl.attr.depend]p2:
3608 // The first declaration of a function shall specify the
3609 // carries_dependency attribute for its declarator-id if any declaration
3610 // of the function specifies the carries_dependency attribute.
3611 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3612 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3613 Diag(CDA->getLocation(),
3614 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3615 Diag(Old->getFirstDecl()->getLocation(),
3616 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3617 }
3618
3619 // (C++98 8.3.5p3):
3620 // All declarations for a function shall agree exactly in both the
3621 // return type and the parameter-type-list.
3622 // We also want to respect all the extended bits except noreturn.
3623
3624 // noreturn should now match unless the old type info didn't have it.
3625 QualType OldQTypeForComparison = OldQType;
3626 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3627 auto *OldType = OldQType->castAs<FunctionProtoType>();
3628 const FunctionType *OldTypeForComparison
3629 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3630 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3631 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3631, __PRETTY_FUNCTION__))
;
3632 }
3633
3634 if (haveIncompatibleLanguageLinkages(Old, New)) {
3635 // As a special case, retain the language linkage from previous
3636 // declarations of a friend function as an extension.
3637 //
3638 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3639 // and is useful because there's otherwise no way to specify language
3640 // linkage within class scope.
3641 //
3642 // Check cautiously as the friend object kind isn't yet complete.
3643 if (New->getFriendObjectKind() != Decl::FOK_None) {
3644 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3645 Diag(OldLocation, PrevDiag);
3646 } else {
3647 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3648 Diag(OldLocation, PrevDiag);
3649 return true;
3650 }
3651 }
3652
3653 // If the function types are compatible, merge the declarations. Ignore the
3654 // exception specifier because it was already checked above in
3655 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3656 // about incompatible types under -fms-compatibility.
3657 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3658 NewQType))
3659 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3660
3661 // If the types are imprecise (due to dependent constructs in friends or
3662 // local extern declarations), it's OK if they differ. We'll check again
3663 // during instantiation.
3664 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3665 return false;
3666
3667 // Fall through for conflicting redeclarations and redefinitions.
3668 }
3669
3670 // C: Function types need to be compatible, not identical. This handles
3671 // duplicate function decls like "void f(int); void f(enum X);" properly.
3672 if (!getLangOpts().CPlusPlus &&
3673 Context.typesAreCompatible(OldQType, NewQType)) {
3674 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3675 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3676 const FunctionProtoType *OldProto = nullptr;
3677 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3678 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3679 // The old declaration provided a function prototype, but the
3680 // new declaration does not. Merge in the prototype.
3681 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3681, __PRETTY_FUNCTION__))
;
3682 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3683 NewQType =
3684 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3685 OldProto->getExtProtoInfo());
3686 New->setType(NewQType);
3687 New->setHasInheritedPrototype();
3688
3689 // Synthesize parameters with the same types.
3690 SmallVector<ParmVarDecl*, 16> Params;
3691 for (const auto &ParamType : OldProto->param_types()) {
3692 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3693 SourceLocation(), nullptr,
3694 ParamType, /*TInfo=*/nullptr,
3695 SC_None, nullptr);
3696 Param->setScopeInfo(0, Params.size());
3697 Param->setImplicit();
3698 Params.push_back(Param);
3699 }
3700
3701 New->setParams(Params);
3702 }
3703
3704 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3705 }
3706
3707 // Check if the function types are compatible when pointer size address
3708 // spaces are ignored.
3709 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3710 return false;
3711
3712 // GNU C permits a K&R definition to follow a prototype declaration
3713 // if the declared types of the parameters in the K&R definition
3714 // match the types in the prototype declaration, even when the
3715 // promoted types of the parameters from the K&R definition differ
3716 // from the types in the prototype. GCC then keeps the types from
3717 // the prototype.
3718 //
3719 // If a variadic prototype is followed by a non-variadic K&R definition,
3720 // the K&R definition becomes variadic. This is sort of an edge case, but
3721 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3722 // C99 6.9.1p8.
3723 if (!getLangOpts().CPlusPlus &&
3724 Old->hasPrototype() && !New->hasPrototype() &&
3725 New->getType()->getAs<FunctionProtoType>() &&
3726 Old->getNumParams() == New->getNumParams()) {
3727 SmallVector<QualType, 16> ArgTypes;
3728 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3729 const FunctionProtoType *OldProto
3730 = Old->getType()->getAs<FunctionProtoType>();
3731 const FunctionProtoType *NewProto
3732 = New->getType()->getAs<FunctionProtoType>();
3733
3734 // Determine whether this is the GNU C extension.
3735 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3736 NewProto->getReturnType());
3737 bool LooseCompatible = !MergedReturn.isNull();
3738 for (unsigned Idx = 0, End = Old->getNumParams();
3739 LooseCompatible && Idx != End; ++Idx) {
3740 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3741 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3742 if (Context.typesAreCompatible(OldParm->getType(),
3743 NewProto->getParamType(Idx))) {
3744 ArgTypes.push_back(NewParm->getType());
3745 } else if (Context.typesAreCompatible(OldParm->getType(),
3746 NewParm->getType(),
3747 /*CompareUnqualified=*/true)) {
3748 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3749 NewProto->getParamType(Idx) };
3750 Warnings.push_back(Warn);
3751 ArgTypes.push_back(NewParm->getType());
3752 } else
3753 LooseCompatible = false;
3754 }
3755
3756 if (LooseCompatible) {
3757 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3758 Diag(Warnings[Warn].NewParm->getLocation(),
3759 diag::ext_param_promoted_not_compatible_with_prototype)
3760 << Warnings[Warn].PromotedType
3761 << Warnings[Warn].OldParm->getType();
3762 if (Warnings[Warn].OldParm->getLocation().isValid())
3763 Diag(Warnings[Warn].OldParm->getLocation(),
3764 diag::note_previous_declaration);
3765 }
3766
3767 if (MergeTypeWithOld)
3768 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3769 OldProto->getExtProtoInfo()));
3770 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3771 }
3772
3773 // Fall through to diagnose conflicting types.
3774 }
3775
3776 // A function that has already been declared has been redeclared or
3777 // defined with a different type; show an appropriate diagnostic.
3778
3779 // If the previous declaration was an implicitly-generated builtin
3780 // declaration, then at the very least we should use a specialized note.
3781 unsigned BuiltinID;
3782 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3783 // If it's actually a library-defined builtin function like 'malloc'
3784 // or 'printf', just warn about the incompatible redeclaration.
3785 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3786 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3787 Diag(OldLocation, diag::note_previous_builtin_declaration)
3788 << Old << Old->getType();
3789 return false;
3790 }
3791
3792 PrevDiag = diag::note_previous_builtin_declaration;
3793 }
3794
3795 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3796 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3797 return true;
3798}
3799
3800/// Completes the merge of two function declarations that are
3801/// known to be compatible.
3802///
3803/// This routine handles the merging of attributes and other
3804/// properties of function declarations from the old declaration to
3805/// the new declaration, once we know that New is in fact a
3806/// redeclaration of Old.
3807///
3808/// \returns false
3809bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3810 Scope *S, bool MergeTypeWithOld) {
3811 // Merge the attributes
3812 mergeDeclAttributes(New, Old);
3813
3814 // Merge "pure" flag.
3815 if (Old->isPure())
3816 New->setPure();
3817
3818 // Merge "used" flag.
3819 if (Old->getMostRecentDecl()->isUsed(false))
3820 New->setIsUsed();
3821
3822 // Merge attributes from the parameters. These can mismatch with K&R
3823 // declarations.
3824 if (New->getNumParams() == Old->getNumParams())
3825 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3826 ParmVarDecl *NewParam = New->getParamDecl(i);
3827 ParmVarDecl *OldParam = Old->getParamDecl(i);
3828 mergeParamDeclAttributes(NewParam, OldParam, *this);
3829 mergeParamDeclTypes(NewParam, OldParam, *this);
3830 }
3831
3832 if (getLangOpts().CPlusPlus)
3833 return MergeCXXFunctionDecl(New, Old, S);
3834
3835 // Merge the function types so the we get the composite types for the return
3836 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3837 // was visible.
3838 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3839 if (!Merged.isNull() && MergeTypeWithOld)
3840 New->setType(Merged);
3841
3842 return false;
3843}
3844
3845void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3846 ObjCMethodDecl *oldMethod) {
3847 // Merge the attributes, including deprecated/unavailable
3848 AvailabilityMergeKind MergeKind =
3849 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3850 ? AMK_ProtocolImplementation
3851 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3852 : AMK_Override;
3853
3854 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3855
3856 // Merge attributes from the parameters.
3857 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3858 oe = oldMethod->param_end();
3859 for (ObjCMethodDecl::param_iterator
3860 ni = newMethod->param_begin(), ne = newMethod->param_end();
3861 ni != ne && oi != oe; ++ni, ++oi)
3862 mergeParamDeclAttributes(*ni, *oi, *this);
3863
3864 CheckObjCMethodOverride(newMethod, oldMethod);
3865}
3866
3867static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3868 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 3868, __PRETTY_FUNCTION__))
;
3869
3870 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3871 ? diag::err_redefinition_different_type
3872 : diag::err_redeclaration_different_type)
3873 << New->getDeclName() << New->getType() << Old->getType();
3874
3875 diag::kind PrevDiag;
3876 SourceLocation OldLocation;
3877 std::tie(PrevDiag, OldLocation)
3878 = getNoteDiagForInvalidRedeclaration(Old, New);
3879 S.Diag(OldLocation, PrevDiag);
3880 New->setInvalidDecl();
3881}
3882
3883/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3884/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3885/// emitting diagnostics as appropriate.
3886///
3887/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3888/// to here in AddInitializerToDecl. We can't check them before the initializer
3889/// is attached.
3890void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3891 bool MergeTypeWithOld) {
3892 if (New->isInvalidDecl() || Old->isInvalidDecl())
3893 return;
3894
3895 QualType MergedT;
3896 if (getLangOpts().CPlusPlus) {
3897 if (New->getType()->isUndeducedType()) {
3898 // We don't know what the new type is until the initializer is attached.
3899 return;
3900 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3901 // These could still be something that needs exception specs checked.
3902 return MergeVarDeclExceptionSpecs(New, Old);
3903 }
3904 // C++ [basic.link]p10:
3905 // [...] the types specified by all declarations referring to a given
3906 // object or function shall be identical, except that declarations for an
3907 // array object can specify array types that differ by the presence or
3908 // absence of a major array bound (8.3.4).
3909 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3910 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3911 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3912
3913 // We are merging a variable declaration New into Old. If it has an array
3914 // bound, and that bound differs from Old's bound, we should diagnose the
3915 // mismatch.
3916 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3917 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3918 PrevVD = PrevVD->getPreviousDecl()) {
3919 QualType PrevVDTy = PrevVD->getType();
3920 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3921 continue;
3922
3923 if (!Context.hasSameType(New->getType(), PrevVDTy))
3924 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3925 }
3926 }
3927
3928 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3929 if (Context.hasSameType(OldArray->getElementType(),
3930 NewArray->getElementType()))
3931 MergedT = New->getType();
3932 }
3933 // FIXME: Check visibility. New is hidden but has a complete type. If New
3934 // has no array bound, it should not inherit one from Old, if Old is not
3935 // visible.
3936 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3937 if (Context.hasSameType(OldArray->getElementType(),
3938 NewArray->getElementType()))
3939 MergedT = Old->getType();
3940 }
3941 }
3942 else if (New->getType()->isObjCObjectPointerType() &&
3943 Old->getType()->isObjCObjectPointerType()) {
3944 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3945 Old->getType());
3946 }
3947 } else {
3948 // C 6.2.7p2:
3949 // All declarations that refer to the same object or function shall have
3950 // compatible type.
3951 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3952 }
3953 if (MergedT.isNull()) {
3954 // It's OK if we couldn't merge types if either type is dependent, for a
3955 // block-scope variable. In other cases (static data members of class
3956 // templates, variable templates, ...), we require the types to be
3957 // equivalent.
3958 // FIXME: The C++ standard doesn't say anything about this.
3959 if ((New->getType()->isDependentType() ||
3960 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3961 // If the old type was dependent, we can't merge with it, so the new type
3962 // becomes dependent for now. We'll reproduce the original type when we
3963 // instantiate the TypeSourceInfo for the variable.
3964 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3965 New->setType(Context.DependentTy);
3966 return;
3967 }
3968 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3969 }
3970
3971 // Don't actually update the type on the new declaration if the old
3972 // declaration was an extern declaration in a different scope.
3973 if (MergeTypeWithOld)
3974 New->setType(MergedT);
3975}
3976
3977static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3978 LookupResult &Previous) {
3979 // C11 6.2.7p4:
3980 // For an identifier with internal or external linkage declared
3981 // in a scope in which a prior declaration of that identifier is
3982 // visible, if the prior declaration specifies internal or
3983 // external linkage, the type of the identifier at the later
3984 // declaration becomes the composite type.
3985 //
3986 // If the variable isn't visible, we do not merge with its type.
3987 if (Previous.isShadowed())
3988 return false;
3989
3990 if (S.getLangOpts().CPlusPlus) {
3991 // C++11 [dcl.array]p3:
3992 // If there is a preceding declaration of the entity in the same
3993 // scope in which the bound was specified, an omitted array bound
3994 // is taken to be the same as in that earlier declaration.
3995 return NewVD->isPreviousDeclInSameBlockScope() ||
3996 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3997 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3998 } else {
3999 // If the old declaration was function-local, don't merge with its
4000 // type unless we're in the same function.
4001 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4002 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4003 }
4004}
4005
4006/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4007/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4008/// situation, merging decls or emitting diagnostics as appropriate.
4009///
4010/// Tentative definition rules (C99 6.9.2p2) are checked by
4011/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4012/// definitions here, since the initializer hasn't been attached.
4013///
4014void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4015 // If the new decl is already invalid, don't do any other checking.
4016 if (New->isInvalidDecl())
4017 return;
4018
4019 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4020 return;
4021
4022 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4023
4024 // Verify the old decl was also a variable or variable template.
4025 VarDecl *Old = nullptr;
4026 VarTemplateDecl *OldTemplate = nullptr;
4027 if (Previous.isSingleResult()) {
4028 if (NewTemplate) {
4029 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4030 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4031
4032 if (auto *Shadow =
4033 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4034 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4035 return New->setInvalidDecl();
4036 } else {
4037 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4038
4039 if (auto *Shadow =
4040 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4041 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4042 return New->setInvalidDecl();
4043 }
4044 }
4045 if (!Old) {
4046 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4047 << New->getDeclName();
4048 notePreviousDefinition(Previous.getRepresentativeDecl(),
4049 New->getLocation());
4050 return New->setInvalidDecl();
4051 }
4052
4053 // Ensure the template parameters are compatible.
4054 if (NewTemplate &&
4055 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4056 OldTemplate->getTemplateParameters(),
4057 /*Complain=*/true, TPL_TemplateMatch))
4058 return New->setInvalidDecl();
4059
4060 // C++ [class.mem]p1:
4061 // A member shall not be declared twice in the member-specification [...]
4062 //
4063 // Here, we need only consider static data members.
4064 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4065 Diag(New->getLocation(), diag::err_duplicate_member)
4066 << New->getIdentifier();
4067 Diag(Old->getLocation(), diag::note_previous_declaration);
4068 New->setInvalidDecl();
4069 }
4070
4071 mergeDeclAttributes(New, Old);
4072 // Warn if an already-declared variable is made a weak_import in a subsequent
4073 // declaration
4074 if (New->hasAttr<WeakImportAttr>() &&
4075 Old->getStorageClass() == SC_None &&
4076 !Old->hasAttr<WeakImportAttr>()) {
4077 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4078 notePreviousDefinition(Old, New->getLocation());
4079 // Remove weak_import attribute on new declaration.
4080 New->dropAttr<WeakImportAttr>();
4081 }
4082
4083 if (New->hasAttr<InternalLinkageAttr>() &&
4084 !Old->hasAttr<InternalLinkageAttr>()) {
4085 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4086 << New->getDeclName();
4087 notePreviousDefinition(Old, New->getLocation());
4088 New->dropAttr<InternalLinkageAttr>();
4089 }
4090
4091 // Merge the types.
4092 VarDecl *MostRecent = Old->getMostRecentDecl();
4093 if (MostRecent != Old) {
4094 MergeVarDeclTypes(New, MostRecent,
4095 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4096 if (New->isInvalidDecl())
4097 return;
4098 }
4099
4100 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4101 if (New->isInvalidDecl())
4102 return;
4103
4104 diag::kind PrevDiag;
4105 SourceLocation OldLocation;
4106 std::tie(PrevDiag, OldLocation) =
4107 getNoteDiagForInvalidRedeclaration(Old, New);
4108
4109 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4110 if (New->getStorageClass() == SC_Static &&
4111 !New->isStaticDataMember() &&
4112 Old->hasExternalFormalLinkage()) {
4113 if (getLangOpts().MicrosoftExt) {
4114 Diag(New->getLocation(), diag::ext_static_non_static)
4115 << New->getDeclName();
4116 Diag(OldLocation, PrevDiag);
4117 } else {
4118 Diag(New->getLocation(), diag::err_static_non_static)
4119 << New->getDeclName();
4120 Diag(OldLocation, PrevDiag);
4121 return New->setInvalidDecl();
4122 }
4123 }
4124 // C99 6.2.2p4:
4125 // For an identifier declared with the storage-class specifier
4126 // extern in a scope in which a prior declaration of that
4127 // identifier is visible,23) if the prior declaration specifies
4128 // internal or external linkage, the linkage of the identifier at
4129 // the later declaration is the same as the linkage specified at
4130 // the prior declaration. If no prior declaration is visible, or
4131 // if the prior declaration specifies no linkage, then the
4132 // identifier has external linkage.
4133 if (New->hasExternalStorage() && Old->hasLinkage())
4134 /* Okay */;
4135 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4136 !New->isStaticDataMember() &&
4137 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4138 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4139 Diag(OldLocation, PrevDiag);
4140 return New->setInvalidDecl();
4141 }
4142
4143 // Check if extern is followed by non-extern and vice-versa.
4144 if (New->hasExternalStorage() &&
4145 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4146 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4147 Diag(OldLocation, PrevDiag);
4148 return New->setInvalidDecl();
4149 }
4150 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4151 !New->hasExternalStorage()) {
4152 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4153 Diag(OldLocation, PrevDiag);
4154 return New->setInvalidDecl();
4155 }
4156
4157 if (CheckRedeclarationModuleOwnership(New, Old))
4158 return;
4159
4160 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4161
4162 // FIXME: The test for external storage here seems wrong? We still
4163 // need to check for mismatches.
4164 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4165 // Don't complain about out-of-line definitions of static members.
4166 !(Old->getLexicalDeclContext()->isRecord() &&
4167 !New->getLexicalDeclContext()->isRecord())) {
4168 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4169 Diag(OldLocation, PrevDiag);
4170 return New->setInvalidDecl();
4171 }
4172
4173 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4174 if (VarDecl *Def = Old->getDefinition()) {
4175 // C++1z [dcl.fcn.spec]p4:
4176 // If the definition of a variable appears in a translation unit before
4177 // its first declaration as inline, the program is ill-formed.
4178 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4179 Diag(Def->getLocation(), diag::note_previous_definition);
4180 }
4181 }
4182
4183 // If this redeclaration makes the variable inline, we may need to add it to
4184 // UndefinedButUsed.
4185 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4186 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4187 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4188 SourceLocation()));
4189
4190 if (New->getTLSKind() != Old->getTLSKind()) {
4191 if (!Old->getTLSKind()) {
4192 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4193 Diag(OldLocation, PrevDiag);
4194 } else if (!New->getTLSKind()) {
4195 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4196 Diag(OldLocation, PrevDiag);
4197 } else {
4198 // Do not allow redeclaration to change the variable between requiring
4199 // static and dynamic initialization.
4200 // FIXME: GCC allows this, but uses the TLS keyword on the first
4201 // declaration to determine the kind. Do we need to be compatible here?
4202 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4203 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4204 Diag(OldLocation, PrevDiag);
4205 }
4206 }
4207
4208 // C++ doesn't have tentative definitions, so go right ahead and check here.
4209 if (getLangOpts().CPlusPlus &&
4210 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4211 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4212 Old->getCanonicalDecl()->isConstexpr()) {
4213 // This definition won't be a definition any more once it's been merged.
4214 Diag(New->getLocation(),
4215 diag::warn_deprecated_redundant_constexpr_static_def);
4216 } else if (VarDecl *Def = Old->getDefinition()) {
4217 if (checkVarDeclRedefinition(Def, New))
4218 return;
4219 }
4220 }
4221
4222 if (haveIncompatibleLanguageLinkages(Old, New)) {
4223 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4224 Diag(OldLocation, PrevDiag);
4225 New->setInvalidDecl();
4226 return;
4227 }
4228
4229 // Merge "used" flag.
4230 if (Old->getMostRecentDecl()->isUsed(false))
4231 New->setIsUsed();
4232
4233 // Keep a chain of previous declarations.
4234 New->setPreviousDecl(Old);
4235 if (NewTemplate)
4236 NewTemplate->setPreviousDecl(OldTemplate);
4237 adjustDeclContextForDeclaratorDecl(New, Old);
4238
4239 // Inherit access appropriately.
4240 New->setAccess(Old->getAccess());
4241 if (NewTemplate)
4242 NewTemplate->setAccess(New->getAccess());
4243
4244 if (Old->isInline())
4245 New->setImplicitlyInline();
4246}
4247
4248void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4249 SourceManager &SrcMgr = getSourceManager();
4250 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4251 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4252 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4253 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4254 auto &HSI = PP.getHeaderSearchInfo();
4255 StringRef HdrFilename =
4256 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4257
4258 auto noteFromModuleOrInclude = [&](Module *Mod,
4259 SourceLocation IncLoc) -> bool {
4260 // Redefinition errors with modules are common with non modular mapped
4261 // headers, example: a non-modular header H in module A that also gets
4262 // included directly in a TU. Pointing twice to the same header/definition
4263 // is confusing, try to get better diagnostics when modules is on.
4264 if (IncLoc.isValid()) {
4265 if (Mod) {
4266 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4267 << HdrFilename.str() << Mod->getFullModuleName();
4268 if (!Mod->DefinitionLoc.isInvalid())
4269 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4270 << Mod->getFullModuleName();
4271 } else {
4272 Diag(IncLoc, diag::note_redefinition_include_same_file)
4273 << HdrFilename.str();
4274 }
4275 return true;
4276 }
4277
4278 return false;
4279 };
4280
4281 // Is it the same file and same offset? Provide more information on why
4282 // this leads to a redefinition error.
4283 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4284 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4285 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4286 bool EmittedDiag =
4287 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4288 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4289
4290 // If the header has no guards, emit a note suggesting one.
4291 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4292 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4293
4294 if (EmittedDiag)
4295 return;
4296 }
4297
4298 // Redefinition coming from different files or couldn't do better above.
4299 if (Old->getLocation().isValid())
4300 Diag(Old->getLocation(), diag::note_previous_definition);
4301}
4302
4303/// We've just determined that \p Old and \p New both appear to be definitions
4304/// of the same variable. Either diagnose or fix the problem.
4305bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4306 if (!hasVisibleDefinition(Old) &&
4307 (New->getFormalLinkage() == InternalLinkage ||
4308 New->isInline() ||
4309 New->getDescribedVarTemplate() ||
4310 New->getNumTemplateParameterLists() ||
4311 New->getDeclContext()->isDependentContext())) {
4312 // The previous definition is hidden, and multiple definitions are
4313 // permitted (in separate TUs). Demote this to a declaration.
4314 New->demoteThisDefinitionToDeclaration();
4315
4316 // Make the canonical definition visible.
4317 if (auto *OldTD = Old->getDescribedVarTemplate())
4318 makeMergedDefinitionVisible(OldTD);
4319 makeMergedDefinitionVisible(Old);
4320 return false;
4321 } else {
4322 Diag(New->getLocation(), diag::err_redefinition) << New;
4323 notePreviousDefinition(Old, New->getLocation());
4324 New->setInvalidDecl();
4325 return true;
4326 }
4327}
4328
4329/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4330/// no declarator (e.g. "struct foo;") is parsed.
4331Decl *
4332Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4333 RecordDecl *&AnonRecord) {
4334 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4335 AnonRecord);
4336}
4337
4338// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4339// disambiguate entities defined in different scopes.
4340// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4341// compatibility.
4342// We will pick our mangling number depending on which version of MSVC is being
4343// targeted.
4344static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4345 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4346 ? S->getMSCurManglingNumber()
4347 : S->getMSLastManglingNumber();
4348}
4349
4350void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4351 if (!Context.getLangOpts().CPlusPlus)
4352 return;
4353
4354 if (isa<CXXRecordDecl>(Tag->getParent())) {
4355 // If this tag is the direct child of a class, number it if
4356 // it is anonymous.
4357 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4358 return;
4359 MangleNumberingContext &MCtx =
4360 Context.getManglingNumberContext(Tag->getParent());
4361 Context.setManglingNumber(
4362 Tag, MCtx.getManglingNumber(
4363 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4364 return;
4365 }
4366
4367 // If this tag isn't a direct child of a class, number it if it is local.
4368 MangleNumberingContext *MCtx;
4369 Decl *ManglingContextDecl;
4370 std::tie(MCtx, ManglingContextDecl) =
4371 getCurrentMangleNumberContext(Tag->getDeclContext());
4372 if (MCtx) {
4373 Context.setManglingNumber(
4374 Tag, MCtx->getManglingNumber(
4375 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4376 }
4377}
4378
4379namespace {
4380struct NonCLikeKind {
4381 enum {
4382 None,
4383 BaseClass,
4384 DefaultMemberInit,
4385 Lambda,
4386 Friend,
4387 OtherMember,
4388 Invalid,
4389 } Kind = None;
4390 SourceRange Range;
4391
4392 explicit operator bool() { return Kind != None; }
4393};
4394}
4395
4396/// Determine whether a class is C-like, according to the rules of C++
4397/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4398static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4399 if (RD->isInvalidDecl())
4400 return {NonCLikeKind::Invalid, {}};
4401
4402 // C++ [dcl.typedef]p9: [P1766R1]
4403 // An unnamed class with a typedef name for linkage purposes shall not
4404 //
4405 // -- have any base classes
4406 if (RD->getNumBases())
4407 return {NonCLikeKind::BaseClass,
4408 SourceRange(RD->bases_begin()->getBeginLoc(),
4409 RD->bases_end()[-1].getEndLoc())};
4410 bool Invalid = false;
4411 for (Decl *D : RD->decls()) {
4412 // Don't complain about things we already diagnosed.
4413 if (D->isInvalidDecl()) {
4414 Invalid = true;
4415 continue;
4416 }
4417
4418 // -- have any [...] default member initializers
4419 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4420 if (FD->hasInClassInitializer()) {
4421 auto *Init = FD->getInClassInitializer();
4422 return {NonCLikeKind::DefaultMemberInit,
4423 Init ? Init->getSourceRange() : D->getSourceRange()};
4424 }
4425 continue;
4426 }
4427
4428 // FIXME: We don't allow friend declarations. This violates the wording of
4429 // P1766, but not the intent.
4430 if (isa<FriendDecl>(D))
4431 return {NonCLikeKind::Friend, D->getSourceRange()};
4432
4433 // -- declare any members other than non-static data members, member
4434 // enumerations, or member classes,
4435 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4436 isa<EnumDecl>(D))
4437 continue;
4438 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4439 if (!MemberRD) {
4440 if (D->isImplicit())
4441 continue;
4442 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4443 }
4444
4445 // -- contain a lambda-expression,
4446 if (MemberRD->isLambda())
4447 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4448
4449 // and all member classes shall also satisfy these requirements
4450 // (recursively).
4451 if (MemberRD->isThisDeclarationADefinition()) {
4452 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4453 return Kind;
4454 }
4455 }
4456
4457 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4458}
4459
4460void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4461 TypedefNameDecl *NewTD) {
4462 if (TagFromDeclSpec->isInvalidDecl())
4463 return;
4464
4465 // Do nothing if the tag already has a name for linkage purposes.
4466 if (TagFromDeclSpec->hasNameForLinkage())
4467 return;
4468
4469 // A well-formed anonymous tag must always be a TUK_Definition.
4470 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4470, __PRETTY_FUNCTION__))
;
4471
4472 // The type must match the tag exactly; no qualifiers allowed.
4473 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4474 Context.getTagDeclType(TagFromDeclSpec))) {
4475 if (getLangOpts().CPlusPlus)
4476 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4477 return;
4478 }
4479
4480 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4481 // An unnamed class with a typedef name for linkage purposes shall [be
4482 // C-like].
4483 //
4484 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4485 // shouldn't happen, but there are constructs that the language rule doesn't
4486 // disallow for which we can't reasonably avoid computing linkage early.
4487 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4488 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4489 : NonCLikeKind();
4490 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4491 if (NonCLike || ChangesLinkage) {
4492 if (NonCLike.Kind == NonCLikeKind::Invalid)
4493 return;
4494
4495 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4496 if (ChangesLinkage) {
4497 // If the linkage changes, we can't accept this as an extension.
4498 if (NonCLike.Kind == NonCLikeKind::None)
4499 DiagID = diag::err_typedef_changes_linkage;
4500 else
4501 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4502 }
4503
4504 SourceLocation FixitLoc =
4505 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4506 llvm::SmallString<40> TextToInsert;
4507 TextToInsert += ' ';
4508 TextToInsert += NewTD->getIdentifier()->getName();
4509
4510 Diag(FixitLoc, DiagID)
4511 << isa<TypeAliasDecl>(NewTD)
4512 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4513 if (NonCLike.Kind != NonCLikeKind::None) {
4514 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4515 << NonCLike.Kind - 1 << NonCLike.Range;
4516 }
4517 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4518 << NewTD << isa<TypeAliasDecl>(NewTD);
4519
4520 if (ChangesLinkage)
4521 return;
4522 }
4523
4524 // Otherwise, set this as the anon-decl typedef for the tag.
4525 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4526}
4527
4528static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4529 switch (T) {
4530 case DeclSpec::TST_class:
4531 return 0;
4532 case DeclSpec::TST_struct:
4533 return 1;
4534 case DeclSpec::TST_interface:
4535 return 2;
4536 case DeclSpec::TST_union:
4537 return 3;
4538 case DeclSpec::TST_enum:
4539 return 4;
4540 default:
4541 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4541)
;
4542 }
4543}
4544
4545/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4546/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4547/// parameters to cope with template friend declarations.
4548Decl *
4549Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4550 MultiTemplateParamsArg TemplateParams,
4551 bool IsExplicitInstantiation,
4552 RecordDecl *&AnonRecord) {
4553 Decl *TagD = nullptr;
4554 TagDecl *Tag = nullptr;
4555 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4556 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4557 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4558 DS.getTypeSpecType() == DeclSpec::TST_union ||
4559 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4560 TagD = DS.getRepAsDecl();
4561
4562 if (!TagD) // We probably had an error
4563 return nullptr;
4564
4565 // Note that the above type specs guarantee that the
4566 // type rep is a Decl, whereas in many of the others
4567 // it's a Type.
4568 if (isa<TagDecl>(TagD))
4569 Tag = cast<TagDecl>(TagD);
4570 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4571 Tag = CTD->getTemplatedDecl();
4572 }
4573
4574 if (Tag) {
4575 handleTagNumbering(Tag, S);
4576 Tag->setFreeStanding();
4577 if (Tag->isInvalidDecl())
4578 return Tag;
4579 }
4580
4581 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4582 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4583 // or incomplete types shall not be restrict-qualified."
4584 if (TypeQuals & DeclSpec::TQ_restrict)
4585 Diag(DS.getRestrictSpecLoc(),
4586 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4587 << DS.getSourceRange();
4588 }
4589
4590 if (DS.isInlineSpecified())
4591 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4592 << getLangOpts().CPlusPlus17;
4593
4594 if (DS.hasConstexprSpecifier()) {
4595 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4596 // and definitions of functions and variables.
4597 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4598 // the declaration of a function or function template
4599 if (Tag)
4600 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4601 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4602 << DS.getConstexprSpecifier();
4603 else
4604 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4605 << DS.getConstexprSpecifier();
4606 // Don't emit warnings after this error.
4607 return TagD;
4608 }
4609
4610 DiagnoseFunctionSpecifiers(DS);
4611
4612 if (DS.isFriendSpecified()) {
4613 // If we're dealing with a decl but not a TagDecl, assume that
4614 // whatever routines created it handled the friendship aspect.
4615 if (TagD && !Tag)
4616 return nullptr;
4617 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4618 }
4619
4620 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4621 bool IsExplicitSpecialization =
4622 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4623 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4624 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4625 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4626 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4627 // nested-name-specifier unless it is an explicit instantiation
4628 // or an explicit specialization.
4629 //
4630 // FIXME: We allow class template partial specializations here too, per the
4631 // obvious intent of DR1819.
4632 //
4633 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4634 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4635 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4636 return nullptr;
4637 }
4638
4639 // Track whether this decl-specifier declares anything.
4640 bool DeclaresAnything = true;
4641
4642 // Handle anonymous struct definitions.
4643 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4644 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4645 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4646 if (getLangOpts().CPlusPlus ||
4647 Record->getDeclContext()->isRecord()) {
4648 // If CurContext is a DeclContext that can contain statements,
4649 // RecursiveASTVisitor won't visit the decls that
4650 // BuildAnonymousStructOrUnion() will put into CurContext.
4651 // Also store them here so that they can be part of the
4652 // DeclStmt that gets created in this case.
4653 // FIXME: Also return the IndirectFieldDecls created by
4654 // BuildAnonymousStructOr union, for the same reason?
4655 if (CurContext->isFunctionOrMethod())
4656 AnonRecord = Record;
4657 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4658 Context.getPrintingPolicy());
4659 }
4660
4661 DeclaresAnything = false;
4662 }
4663 }
4664
4665 // C11 6.7.2.1p2:
4666 // A struct-declaration that does not declare an anonymous structure or
4667 // anonymous union shall contain a struct-declarator-list.
4668 //
4669 // This rule also existed in C89 and C99; the grammar for struct-declaration
4670 // did not permit a struct-declaration without a struct-declarator-list.
4671 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4672 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4673 // Check for Microsoft C extension: anonymous struct/union member.
4674 // Handle 2 kinds of anonymous struct/union:
4675 // struct STRUCT;
4676 // union UNION;
4677 // and
4678 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4679 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4680 if ((Tag && Tag->getDeclName()) ||
4681 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4682 RecordDecl *Record = nullptr;
4683 if (Tag)
4684 Record = dyn_cast<RecordDecl>(Tag);
4685 else if (const RecordType *RT =
4686 DS.getRepAsType().get()->getAsStructureType())
4687 Record = RT->getDecl();
4688 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4689 Record = UT->getDecl();
4690
4691 if (Record && getLangOpts().MicrosoftExt) {
4692 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4693 << Record->isUnion() << DS.getSourceRange();
4694 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4695 }
4696
4697 DeclaresAnything = false;
4698 }
4699 }
4700
4701 // Skip all the checks below if we have a type error.
4702 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4703 (TagD && TagD->isInvalidDecl()))
4704 return TagD;
4705
4706 if (getLangOpts().CPlusPlus &&
4707 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4708 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4709 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4710 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4711 DeclaresAnything = false;
4712
4713 if (!DS.isMissingDeclaratorOk()) {
4714 // Customize diagnostic for a typedef missing a name.
4715 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4716 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4717 << DS.getSourceRange();
4718 else
4719 DeclaresAnything = false;
4720 }
4721
4722 if (DS.isModulePrivateSpecified() &&
4723 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4724 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4725 << Tag->getTagKind()
4726 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4727
4728 ActOnDocumentableDecl(TagD);
4729
4730 // C 6.7/2:
4731 // A declaration [...] shall declare at least a declarator [...], a tag,
4732 // or the members of an enumeration.
4733 // C++ [dcl.dcl]p3:
4734 // [If there are no declarators], and except for the declaration of an
4735 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4736 // names into the program, or shall redeclare a name introduced by a
4737 // previous declaration.
4738 if (!DeclaresAnything) {
4739 // In C, we allow this as a (popular) extension / bug. Don't bother
4740 // producing further diagnostics for redundant qualifiers after this.
4741 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4742 ? diag::err_no_declarators
4743 : diag::ext_no_declarators)
4744 << DS.getSourceRange();
4745 return TagD;
4746 }
4747
4748 // C++ [dcl.stc]p1:
4749 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4750 // init-declarator-list of the declaration shall not be empty.
4751 // C++ [dcl.fct.spec]p1:
4752 // If a cv-qualifier appears in a decl-specifier-seq, the
4753 // init-declarator-list of the declaration shall not be empty.
4754 //
4755 // Spurious qualifiers here appear to be valid in C.
4756 unsigned DiagID = diag::warn_standalone_specifier;
4757 if (getLangOpts().CPlusPlus)
4758 DiagID = diag::ext_standalone_specifier;
4759
4760 // Note that a linkage-specification sets a storage class, but
4761 // 'extern "C" struct foo;' is actually valid and not theoretically
4762 // useless.
4763 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4764 if (SCS == DeclSpec::SCS_mutable)
4765 // Since mutable is not a viable storage class specifier in C, there is
4766 // no reason to treat it as an extension. Instead, diagnose as an error.
4767 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4768 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4769 Diag(DS.getStorageClassSpecLoc(), DiagID)
4770 << DeclSpec::getSpecifierName(SCS);
4771 }
4772
4773 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4774 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4775 << DeclSpec::getSpecifierName(TSCS);
4776 if (DS.getTypeQualifiers()) {
4777 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4778 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4779 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4780 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4781 // Restrict is covered above.
4782 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4783 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4784 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4785 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4786 }
4787
4788 // Warn about ignored type attributes, for example:
4789 // __attribute__((aligned)) struct A;
4790 // Attributes should be placed after tag to apply to type declaration.
4791 if (!DS.getAttributes().empty()) {
4792 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4793 if (TypeSpecType == DeclSpec::TST_class ||
4794 TypeSpecType == DeclSpec::TST_struct ||
4795 TypeSpecType == DeclSpec::TST_interface ||
4796 TypeSpecType == DeclSpec::TST_union ||
4797 TypeSpecType == DeclSpec::TST_enum) {
4798 for (const ParsedAttr &AL : DS.getAttributes())
4799 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4800 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4801 }
4802 }
4803
4804 return TagD;
4805}
4806
4807/// We are trying to inject an anonymous member into the given scope;
4808/// check if there's an existing declaration that can't be overloaded.
4809///
4810/// \return true if this is a forbidden redeclaration
4811static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4812 Scope *S,
4813 DeclContext *Owner,
4814 DeclarationName Name,
4815 SourceLocation NameLoc,
4816 bool IsUnion) {
4817 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4818 Sema::ForVisibleRedeclaration);
4819 if (!SemaRef.LookupName(R, S)) return false;
4820
4821 // Pick a representative declaration.
4822 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4823 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4823, __PRETTY_FUNCTION__))
;
4824
4825 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4826 return false;
4827
4828 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4829 << IsUnion << Name;
4830 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4831
4832 return true;
4833}
4834
4835/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4836/// anonymous struct or union AnonRecord into the owning context Owner
4837/// and scope S. This routine will be invoked just after we realize
4838/// that an unnamed union or struct is actually an anonymous union or
4839/// struct, e.g.,
4840///
4841/// @code
4842/// union {
4843/// int i;
4844/// float f;
4845/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4846/// // f into the surrounding scope.x
4847/// @endcode
4848///
4849/// This routine is recursive, injecting the names of nested anonymous
4850/// structs/unions into the owning context and scope as well.
4851static bool
4852InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4853 RecordDecl *AnonRecord, AccessSpecifier AS,
4854 SmallVectorImpl<NamedDecl *> &Chaining) {
4855 bool Invalid = false;
4856
4857 // Look every FieldDecl and IndirectFieldDecl with a name.
4858 for (auto *D : AnonRecord->decls()) {
4859 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4860 cast<NamedDecl>(D)->getDeclName()) {
4861 ValueDecl *VD = cast<ValueDecl>(D);
4862 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4863 VD->getLocation(),
4864 AnonRecord->isUnion())) {
4865 // C++ [class.union]p2:
4866 // The names of the members of an anonymous union shall be
4867 // distinct from the names of any other entity in the
4868 // scope in which the anonymous union is declared.
4869 Invalid = true;
4870 } else {
4871 // C++ [class.union]p2:
4872 // For the purpose of name lookup, after the anonymous union
4873 // definition, the members of the anonymous union are
4874 // considered to have been defined in the scope in which the
4875 // anonymous union is declared.
4876 unsigned OldChainingSize = Chaining.size();
4877 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4878 Chaining.append(IF->chain_begin(), IF->chain_end());
4879 else
4880 Chaining.push_back(VD);
4881
4882 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4882, __PRETTY_FUNCTION__))
;
4883 NamedDecl **NamedChain =
4884 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4885 for (unsigned i = 0; i < Chaining.size(); i++)
4886 NamedChain[i] = Chaining[i];
4887
4888 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4889 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4890 VD->getType(), {NamedChain, Chaining.size()});
4891
4892 for (const auto *Attr : VD->attrs())
4893 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4894
4895 IndirectField->setAccess(AS);
4896 IndirectField->setImplicit();
4897 SemaRef.PushOnScopeChains(IndirectField, S);
4898
4899 // That includes picking up the appropriate access specifier.
4900 if (AS != AS_none) IndirectField->setAccess(AS);
4901
4902 Chaining.resize(OldChainingSize);
4903 }
4904 }
4905 }
4906
4907 return Invalid;
4908}
4909
4910/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4911/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4912/// illegal input values are mapped to SC_None.
4913static StorageClass
4914StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4915 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4916 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4917, __PRETTY_FUNCTION__))
4917 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4917, __PRETTY_FUNCTION__))
;
4918 switch (StorageClassSpec) {
4919 case DeclSpec::SCS_unspecified: return SC_None;
4920 case DeclSpec::SCS_extern:
4921 if (DS.isExternInLinkageSpec())
4922 return SC_None;
4923 return SC_Extern;
4924 case DeclSpec::SCS_static: return SC_Static;
4925 case DeclSpec::SCS_auto: return SC_Auto;
4926 case DeclSpec::SCS_register: return SC_Register;
4927 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4928 // Illegal SCSs map to None: error reporting is up to the caller.
4929 case DeclSpec::SCS_mutable: // Fall through.
4930 case DeclSpec::SCS_typedef: return SC_None;
4931 }
4932 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4932)
;
4933}
4934
4935static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4936 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4936, __PRETTY_FUNCTION__))
;
4937
4938 for (const auto *I : Record->decls()) {
4939 const auto *FD = dyn_cast<FieldDecl>(I);
4940 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4941 FD = IFD->getAnonField();
4942 if (FD && FD->hasInClassInitializer())
4943 return FD->getLocation();
4944 }
4945
4946 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 4946)
;
4947}
4948
4949static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4950 SourceLocation DefaultInitLoc) {
4951 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4952 return;
4953
4954 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4955 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4956}
4957
4958static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4959 CXXRecordDecl *AnonUnion) {
4960 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4961 return;
4962
4963 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4964}
4965
4966/// BuildAnonymousStructOrUnion - Handle the declaration of an
4967/// anonymous structure or union. Anonymous unions are a C++ feature
4968/// (C++ [class.union]) and a C11 feature; anonymous structures
4969/// are a C11 feature and GNU C++ extension.
4970Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4971 AccessSpecifier AS,
4972 RecordDecl *Record,
4973 const PrintingPolicy &Policy) {
4974 DeclContext *Owner = Record->getDeclContext();
4975
4976 // Diagnose whether this anonymous struct/union is an extension.
4977 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4978 Diag(Record->getLocation(), diag::ext_anonymous_union);
4979 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4980 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4981 else if (!Record->isUnion() && !getLangOpts().C11)
4982 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4983
4984 // C and C++ require different kinds of checks for anonymous
4985 // structs/unions.
4986 bool Invalid = false;
4987 if (getLangOpts().CPlusPlus) {
4988 const char *PrevSpec = nullptr;
4989 if (Record->isUnion()) {
4990 // C++ [class.union]p6:
4991 // C++17 [class.union.anon]p2:
4992 // Anonymous unions declared in a named namespace or in the
4993 // global namespace shall be declared static.
4994 unsigned DiagID;
4995 DeclContext *OwnerScope = Owner->getRedeclContext();
4996 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4997 (OwnerScope->isTranslationUnit() ||
4998 (OwnerScope->isNamespace() &&
4999 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5000 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5001 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5002
5003 // Recover by adding 'static'.
5004 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5005 PrevSpec, DiagID, Policy);
5006 }
5007 // C++ [class.union]p6:
5008 // A storage class is not allowed in a declaration of an
5009 // anonymous union in a class scope.
5010 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5011 isa<RecordDecl>(Owner)) {
5012 Diag(DS.getStorageClassSpecLoc(),
5013 diag::err_anonymous_union_with_storage_spec)
5014 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5015
5016 // Recover by removing the storage specifier.
5017 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5018 SourceLocation(),
5019 PrevSpec, DiagID, Context.getPrintingPolicy());
5020 }
5021 }
5022
5023 // Ignore const/volatile/restrict qualifiers.
5024 if (DS.getTypeQualifiers()) {
5025 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5026 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5027 << Record->isUnion() << "const"
5028 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5029 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5030 Diag(DS.getVolatileSpecLoc(),
5031 diag::ext_anonymous_struct_union_qualified)
5032 << Record->isUnion() << "volatile"
5033 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5034 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5035 Diag(DS.getRestrictSpecLoc(),
5036 diag::ext_anonymous_struct_union_qualified)
5037 << Record->isUnion() << "restrict"
5038 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5039 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5040 Diag(DS.getAtomicSpecLoc(),
5041 diag::ext_anonymous_struct_union_qualified)
5042 << Record->isUnion() << "_Atomic"
5043 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5044 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5045 Diag(DS.getUnalignedSpecLoc(),
5046 diag::ext_anonymous_struct_union_qualified)
5047 << Record->isUnion() << "__unaligned"
5048 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5049
5050 DS.ClearTypeQualifiers();
5051 }
5052
5053 // C++ [class.union]p2:
5054 // The member-specification of an anonymous union shall only
5055 // define non-static data members. [Note: nested types and
5056 // functions cannot be declared within an anonymous union. ]
5057 for (auto *Mem : Record->decls()) {
5058 // Ignore invalid declarations; we already diagnosed them.
5059 if (Mem->isInvalidDecl())
5060 continue;
5061
5062 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5063 // C++ [class.union]p3:
5064 // An anonymous union shall not have private or protected
5065 // members (clause 11).
5066 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 5066, __PRETTY_FUNCTION__))
;
5067 if (FD->getAccess() != AS_public) {
5068 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5069 << Record->isUnion() << (FD->getAccess() == AS_protected);
5070 Invalid = true;
5071 }
5072
5073 // C++ [class.union]p1
5074 // An object of a class with a non-trivial constructor, a non-trivial
5075 // copy constructor, a non-trivial destructor, or a non-trivial copy
5076 // assignment operator cannot be a member of a union, nor can an
5077 // array of such objects.
5078 if (CheckNontrivialField(FD))
5079 Invalid = true;
5080 } else if (Mem->isImplicit()) {
5081 // Any implicit members are fine.
5082 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5083 // This is a type that showed up in an
5084 // elaborated-type-specifier inside the anonymous struct or
5085 // union, but which actually declares a type outside of the
5086 // anonymous struct or union. It's okay.
5087 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5088 if (!MemRecord->isAnonymousStructOrUnion() &&
5089 MemRecord->getDeclName()) {
5090 // Visual C++ allows type definition in anonymous struct or union.
5091 if (getLangOpts().MicrosoftExt)
5092 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5093 << Record->isUnion();
5094 else {
5095 // This is a nested type declaration.
5096 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5097 << Record->isUnion();
5098 Invalid = true;
5099 }
5100 } else {
5101 // This is an anonymous type definition within another anonymous type.
5102 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5103 // not part of standard C++.
5104 Diag(MemRecord->getLocation(),
5105 diag::ext_anonymous_record_with_anonymous_type)
5106 << Record->isUnion();
5107 }
5108 } else if (isa<AccessSpecDecl>(Mem)) {
5109 // Any access specifier is fine.
5110 } else if (isa<StaticAssertDecl>(Mem)) {
5111 // In C++1z, static_assert declarations are also fine.
5112 } else {
5113 // We have something that isn't a non-static data
5114 // member. Complain about it.
5115 unsigned DK = diag::err_anonymous_record_bad_member;
5116 if (isa<TypeDecl>(Mem))
5117 DK = diag::err_anonymous_record_with_type;
5118 else if (isa<FunctionDecl>(Mem))
5119 DK = diag::err_anonymous_record_with_function;
5120 else if (isa<VarDecl>(Mem))
5121 DK = diag::err_anonymous_record_with_static;
5122
5123 // Visual C++ allows type definition in anonymous struct or union.
5124 if (getLangOpts().MicrosoftExt &&
5125 DK == diag::err_anonymous_record_with_type)
5126 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5127 << Record->isUnion();
5128 else {
5129 Diag(Mem->getLocation(), DK) << Record->isUnion();
5130 Invalid = true;
5131 }
5132 }
5133 }
5134
5135 // C++11 [class.union]p8 (DR1460):
5136 // At most one variant member of a union may have a
5137 // brace-or-equal-initializer.
5138 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5139 Owner->isRecord())
5140 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5141 cast<CXXRecordDecl>(Record));
5142 }
5143
5144 if (!Record->isUnion() && !Owner->isRecord()) {
5145 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5146 << getLangOpts().CPlusPlus;
5147 Invalid = true;
5148 }
5149
5150 // C++ [dcl.dcl]p3:
5151 // [If there are no declarators], and except for the declaration of an
5152 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5153 // names into the program
5154 // C++ [class.mem]p2:
5155 // each such member-declaration shall either declare at least one member
5156 // name of the class or declare at least one unnamed bit-field
5157 //
5158 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5159 if (getLangOpts().CPlusPlus && Record->field_empty())
5160 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5161
5162 // Mock up a declarator.
5163 Declarator Dc(DS, DeclaratorContext::MemberContext);
5164 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5165 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 5165, __PRETTY_FUNCTION__))
;
5166
5167 // Create a declaration for this anonymous struct/union.
5168 NamedDecl *Anon = nullptr;
5169 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5170 Anon = FieldDecl::Create(
5171 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5172 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5173 /*BitWidth=*/nullptr, /*Mutable=*/false,
5174 /*InitStyle=*/ICIS_NoInit);
5175 Anon->setAccess(AS);
5176 ProcessDeclAttributes(S, Anon, Dc);
5177
5178 if (getLangOpts().CPlusPlus)
5179 FieldCollector->Add(cast<FieldDecl>(Anon));
5180 } else {
5181 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5182 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5183 if (SCSpec == DeclSpec::SCS_mutable) {
5184 // mutable can only appear on non-static class members, so it's always
5185 // an error here
5186 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5187 Invalid = true;
5188 SC = SC_None;
5189 }
5190
5191 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 5191, __PRETTY_FUNCTION__))
;
5192 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5193 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5194 Context.getTypeDeclType(Record), TInfo, SC);
5195
5196 // Default-initialize the implicit variable. This initialization will be
5197 // trivial in almost all cases, except if a union member has an in-class
5198 // initializer:
5199 // union { int n = 0; };
5200 ActOnUninitializedDecl(Anon);
5201 }
5202 Anon->setImplicit();
5203
5204 // Mark this as an anonymous struct/union type.
5205 Record->setAnonymousStructOrUnion(true);
5206
5207 // Add the anonymous struct/union object to the current
5208 // context. We'll be referencing this object when we refer to one of
5209 // its members.
5210 Owner->addDecl(Anon);
5211
5212 // Inject the members of the anonymous struct/union into the owning
5213 // context and into the identifier resolver chain for name lookup
5214 // purposes.
5215 SmallVector<NamedDecl*, 2> Chain;
5216 Chain.push_back(Anon);
5217
5218 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5219 Invalid = true;
5220
5221 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5222 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5223 MangleNumberingContext *MCtx;
5224 Decl *ManglingContextDecl;
5225 std::tie(MCtx, ManglingContextDecl) =
5226 getCurrentMangleNumberContext(NewVD->getDeclContext());
5227 if (MCtx) {
5228 Context.setManglingNumber(
5229 NewVD, MCtx->getManglingNumber(
5230 NewVD, getMSManglingNumber(getLangOpts(), S)));
5231 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5232 }
5233 }
5234 }
5235
5236 if (Invalid)
5237 Anon->setInvalidDecl();
5238
5239 return Anon;
5240}
5241
5242/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5243/// Microsoft C anonymous structure.
5244/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5245/// Example:
5246///
5247/// struct A { int a; };
5248/// struct B { struct A; int b; };
5249///
5250/// void foo() {
5251/// B var;
5252/// var.a = 3;
5253/// }
5254///
5255Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5256 RecordDecl *Record) {
5257 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 5257, __PRETTY_FUNCTION__))
;
5258
5259 // Mock up a declarator.
5260 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5261 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5262 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 5262, __PRETTY_FUNCTION__))
;
5263
5264 auto *ParentDecl = cast<RecordDecl>(CurContext);
5265 QualType RecTy = Context.getTypeDeclType(Record);
5266
5267 // Create a declaration for this anonymous struct.
5268 NamedDecl *Anon =
5269 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5270 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5271 /*BitWidth=*/nullptr, /*Mutable=*/false,
5272 /*InitStyle=*/ICIS_NoInit);
5273 Anon->setImplicit();
5274
5275 // Add the anonymous struct object to the current context.
5276 CurContext->addDecl(Anon);
5277
5278 // Inject the members of the anonymous struct into the current
5279 // context and into the identifier resolver chain for name lookup
5280 // purposes.
5281 SmallVector<NamedDecl*, 2> Chain;
5282 Chain.push_back(Anon);
5283
5284 RecordDecl *RecordDef = Record->getDefinition();
5285 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5286 diag::err_field_incomplete_or_sizeless) ||
5287 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5288 AS_none, Chain)) {
5289 Anon->setInvalidDecl();
5290 ParentDecl->setInvalidDecl();
5291 }
5292
5293 return Anon;
5294}
5295
5296/// GetNameForDeclarator - Determine the full declaration name for the
5297/// given Declarator.
5298DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5299 return GetNameFromUnqualifiedId(D.getName());
5300}
5301
5302/// Retrieves the declaration name from a parsed unqualified-id.
5303DeclarationNameInfo
5304Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5305 DeclarationNameInfo NameInfo;
5306 NameInfo.setLoc(Name.StartLocation);
5307
5308 switch (Name.getKind()) {
5309
5310 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5311 case UnqualifiedIdKind::IK_Identifier:
5312 NameInfo.setName(Name.Identifier);
5313 return NameInfo;
5314
5315 case UnqualifiedIdKind::IK_DeductionGuideName: {
5316 // C++ [temp.deduct.guide]p3:
5317 // The simple-template-id shall name a class template specialization.
5318 // The template-name shall be the same identifier as the template-name
5319 // of the simple-template-id.
5320 // These together intend to imply that the template-name shall name a
5321 // class template.
5322 // FIXME: template<typename T> struct X {};
5323 // template<typename T> using Y = X<T>;
5324 // Y(int) -> Y<int>;
5325 // satisfies these rules but does not name a class template.
5326 TemplateName TN = Name.TemplateName.get().get();
5327 auto *Template = TN.getAsTemplateDecl();
5328 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5329 Diag(Name.StartLocation,
5330 diag::err_deduction_guide_name_not_class_template)
5331 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5332 if (Template)
5333 Diag(Template->getLocation(), diag::note_template_decl_here);
5334 return DeclarationNameInfo();
5335 }
5336
5337 NameInfo.setName(
5338 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5339 return NameInfo;
5340 }
5341
5342 case UnqualifiedIdKind::IK_OperatorFunctionId:
5343 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5344 Name.OperatorFunctionId.Operator));
5345 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5346 = Name.OperatorFunctionId.SymbolLocations[0];
5347 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5348 = Name.EndLocation.getRawEncoding();
5349 return NameInfo;
5350
5351 case UnqualifiedIdKind::IK_LiteralOperatorId:
5352 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5353 Name.Identifier));
5354 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5355 return NameInfo;
5356
5357 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5358 TypeSourceInfo *TInfo;
5359 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5360 if (Ty.isNull())
5361 return DeclarationNameInfo();
5362 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5363 Context.getCanonicalType(Ty)));
5364 NameInfo.setNamedTypeInfo(TInfo);
5365 return NameInfo;
5366 }
5367
5368 case UnqualifiedIdKind::IK_ConstructorName: {
5369 TypeSourceInfo *TInfo;
5370 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5371 if (Ty.isNull())
5372 return DeclarationNameInfo();
5373 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5374 Context.getCanonicalType(Ty)));
5375 NameInfo.setNamedTypeInfo(TInfo);
5376 return NameInfo;
5377 }
5378
5379 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5380 // In well-formed code, we can only have a constructor
5381 // template-id that refers to the current context, so go there
5382 // to find the actual type being constructed.
5383 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5384 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5385 return DeclarationNameInfo();
5386
5387 // Determine the type of the class being constructed.
5388 QualType CurClassType = Context.getTypeDeclType(CurClass);
5389
5390 // FIXME: Check two things: that the template-id names the same type as
5391 // CurClassType, and that the template-id does not occur when the name
5392 // was qualified.
5393
5394 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5395 Context.getCanonicalType(CurClassType)));
5396 // FIXME: should we retrieve TypeSourceInfo?
5397 NameInfo.setNamedTypeInfo(nullptr);
5398 return NameInfo;
5399 }
5400
5401 case UnqualifiedIdKind::IK_DestructorName: {
5402 TypeSourceInfo *TInfo;
5403 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5404 if (Ty.isNull())
5405 return DeclarationNameInfo();
5406 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5407 Context.getCanonicalType(Ty)));
5408 NameInfo.setNamedTypeInfo(TInfo);
5409 return NameInfo;
5410 }
5411
5412 case UnqualifiedIdKind::IK_TemplateId: {
5413 TemplateName TName = Name.TemplateId->Template.get();
5414 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5415 return Context.getNameForTemplate(TName, TNameLoc);
5416 }
5417
5418 } // switch (Name.getKind())
5419
5420 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 5420)
;
5421}
5422
5423static QualType getCoreType(QualType Ty) {
5424 do {
5425 if (Ty->isPointerType() || Ty->isReferenceType())
5426 Ty = Ty->getPointeeType();
5427 else if (Ty->isArrayType())
5428 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5429 else
5430 return Ty.withoutLocalFastQualifiers();
5431 } while (true);
5432}
5433
5434/// hasSimilarParameters - Determine whether the C++ functions Declaration
5435/// and Definition have "nearly" matching parameters. This heuristic is
5436/// used to improve diagnostics in the case where an out-of-line function
5437/// definition doesn't match any declaration within the class or namespace.
5438/// Also sets Params to the list of indices to the parameters that differ
5439/// between the declaration and the definition. If hasSimilarParameters
5440/// returns true and Params is empty, then all of the parameters match.
5441static bool hasSimilarParameters(ASTContext &Context,
5442 FunctionDecl *Declaration,
5443 FunctionDecl *Definition,
5444 SmallVectorImpl<unsigned> &Params) {
5445 Params.clear();
5446 if (Declaration->param_size() != Definition->param_size())
5447 return false;
5448 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5449 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5450 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5451
5452 // The parameter types are identical
5453 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5454 continue;
5455
5456 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5457 QualType DefParamBaseTy = getCoreType(DefParamTy);
5458 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5459 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5460
5461 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5462 (DeclTyName && DeclTyName == DefTyName))
5463 Params.push_back(Idx);
5464 else // The two parameters aren't even close
5465 return false;
5466 }
5467
5468 return true;
5469}
5470
5471/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5472/// declarator needs to be rebuilt in the current instantiation.
5473/// Any bits of declarator which appear before the name are valid for
5474/// consideration here. That's specifically the type in the decl spec
5475/// and the base type in any member-pointer chunks.
5476static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5477 DeclarationName Name) {
5478 // The types we specifically need to rebuild are:
5479 // - typenames, typeofs, and decltypes
5480 // - types which will become injected class names
5481 // Of course, we also need to rebuild any type referencing such a
5482 // type. It's safest to just say "dependent", but we call out a
5483 // few cases here.
5484
5485 DeclSpec &DS = D.getMutableDeclSpec();
5486 switch (DS.getTypeSpecType()) {
5487 case DeclSpec::TST_typename:
5488 case DeclSpec::TST_typeofType:
5489 case DeclSpec::TST_underlyingType:
5490 case DeclSpec::TST_atomic: {
5491 // Grab the type from the parser.
5492 TypeSourceInfo *TSI = nullptr;
5493 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5494 if (T.isNull() || !T->isDependentType()) break;
5495
5496 // Make sure there's a type source info. This isn't really much
5497 // of a waste; most dependent types should have type source info
5498 // attached already.
5499 if (!TSI)
5500 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5501
5502 // Rebuild the type in the current instantiation.
5503 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5504 if (!TSI) return true;
5505
5506 // Store the new type back in the decl spec.
5507 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5508 DS.UpdateTypeRep(LocType);
5509 break;
5510 }
5511
5512 case DeclSpec::TST_decltype:
5513 case DeclSpec::TST_typeofExpr: {
5514 Expr *E = DS.getRepAsExpr();
5515 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5516 if (Result.isInvalid()) return true;
5517 DS.UpdateExprRep(Result.get());
5518 break;
5519 }
5520
5521 default:
5522 // Nothing to do for these decl specs.
5523 break;
5524 }
5525
5526 // It doesn't matter what order we do this in.
5527 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5528 DeclaratorChunk &Chunk = D.getTypeObject(I);
5529
5530 // The only type information in the declarator which can come
5531 // before the declaration name is the base type of a member
5532 // pointer.
5533 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5534 continue;
5535
5536 // Rebuild the scope specifier in-place.
5537 CXXScopeSpec &SS = Chunk.Mem.Scope();
5538 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5539 return true;
5540 }
5541
5542 return false;
5543}
5544
5545Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5546 D.setFunctionDefinitionKind(FDK_Declaration);
5547 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5548
5549 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5550 Dcl && Dcl->getDeclContext()->isFileContext())
5551 Dcl->setTopLevelDeclInObjCContainer();
5552
5553 if (getLangOpts().OpenCL)
5554 setCurrentOpenCLExtensionForDecl(Dcl);
5555
5556 return Dcl;
5557}
5558
5559/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5560/// If T is the name of a class, then each of the following shall have a
5561/// name different from T:
5562/// - every static data member of class T;
5563/// - every member function of class T
5564/// - every member of class T that is itself a type;
5565/// \returns true if the declaration name violates these rules.
5566bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5567 DeclarationNameInfo NameInfo) {
5568 DeclarationName Name = NameInfo.getName();
5569
5570 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5571 while (Record && Record->isAnonymousStructOrUnion())
5572 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5573 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5574 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5575 return true;
5576 }
5577
5578 return false;
5579}
5580
5581/// Diagnose a declaration whose declarator-id has the given
5582/// nested-name-specifier.
5583///
5584/// \param SS The nested-name-specifier of the declarator-id.
5585///
5586/// \param DC The declaration context to which the nested-name-specifier
5587/// resolves.
5588///
5589/// \param Name The name of the entity being declared.
5590///
5591/// \param Loc The location of the name of the entity being declared.
5592///
5593/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5594/// we're declaring an explicit / partial specialization / instantiation.
5595///
5596/// \returns true if we cannot safely recover from this error, false otherwise.
5597bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5598 DeclarationName Name,
5599 SourceLocation Loc, bool IsTemplateId) {
5600 DeclContext *Cur = CurContext;
5601 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5602 Cur = Cur->getParent();
5603
5604 // If the user provided a superfluous scope specifier that refers back to the
5605 // class in which the entity is already declared, diagnose and ignore it.
5606 //
5607 // class X {
5608 // void X::f();
5609 // };
5610 //
5611 // Note, it was once ill-formed to give redundant qualification in all
5612 // contexts, but that rule was removed by DR482.
5613 if (Cur->Equals(DC)) {
5614 if (Cur->isRecord()) {
5615 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5616 : diag::err_member_extra_qualification)
5617 << Name << FixItHint::CreateRemoval(SS.getRange());
5618 SS.clear();
5619 } else {
5620 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5621 }
5622 return false;
5623 }
5624
5625 // Check whether the qualifying scope encloses the scope of the original
5626 // declaration. For a template-id, we perform the checks in
5627 // CheckTemplateSpecializationScope.
5628 if (!Cur->Encloses(DC) && !IsTemplateId) {
5629 if (Cur->isRecord())
5630 Diag(Loc, diag::err_member_qualification)
5631 << Name << SS.getRange();
5632 else if (isa<TranslationUnitDecl>(DC))
5633 Diag(Loc, diag::err_invalid_declarator_global_scope)
5634 << Name << SS.getRange();
5635 else if (isa<FunctionDecl>(Cur))
5636 Diag(Loc, diag::err_invalid_declarator_in_function)
5637 << Name << SS.getRange();
5638 else if (isa<BlockDecl>(Cur))
5639 Diag(Loc, diag::err_invalid_declarator_in_block)
5640 << Name << SS.getRange();
5641 else
5642 Diag(Loc, diag::err_invalid_declarator_scope)
5643 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5644
5645 return true;
5646 }
5647
5648 if (Cur->isRecord()) {
5649 // Cannot qualify members within a class.
5650 Diag(Loc, diag::err_member_qualification)
5651 << Name << SS.getRange();
5652 SS.clear();
5653
5654 // C++ constructors and destructors with incorrect scopes can break
5655 // our AST invariants by having the wrong underlying types. If
5656 // that's the case, then drop this declaration entirely.
5657 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5658 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5659 !Context.hasSameType(Name.getCXXNameType(),
5660 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5661 return true;
5662
5663 return false;
5664 }
5665
5666 // C++11 [dcl.meaning]p1:
5667 // [...] "The nested-name-specifier of the qualified declarator-id shall
5668 // not begin with a decltype-specifer"
5669 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5670 while (SpecLoc.getPrefix())
5671 SpecLoc = SpecLoc.getPrefix();
5672 if (dyn_cast_or_null<DecltypeType>(
5673 SpecLoc.getNestedNameSpecifier()->getAsType()))
5674 Diag(Loc, diag::err_decltype_in_declarator)
5675 << SpecLoc.getTypeLoc().getSourceRange();
5676
5677 return false;
5678}
5679
5680NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5681 MultiTemplateParamsArg TemplateParamLists) {
5682 // TODO: consider using NameInfo for diagnostic.
5683 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5684 DeclarationName Name = NameInfo.getName();
5685
5686 // All of these full declarators require an identifier. If it doesn't have
5687 // one, the ParsedFreeStandingDeclSpec action should be used.
5688 if (D.isDecompositionDeclarator()) {
5689 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5690 } else if (!Name) {
5691 if (!D.isInvalidType()) // Reject this if we think it is valid.
5692 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5693 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5694 return nullptr;
5695 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5696 return nullptr;
5697
5698 // The scope passed in may not be a decl scope. Zip up the scope tree until
5699 // we find one that is.
5700 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5701 (S->getFlags() & Scope::TemplateParamScope) != 0)
5702 S = S->getParent();
5703
5704 DeclContext *DC = CurContext;
5705 if (D.getCXXScopeSpec().isInvalid())
5706 D.setInvalidType();
5707 else if (D.getCXXScopeSpec().isSet()) {
5708 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5709 UPPC_DeclarationQualifier))
5710 return nullptr;
5711
5712 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5713 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5714 if (!DC || isa<EnumDecl>(DC)) {
5715 // If we could not compute the declaration context, it's because the
5716 // declaration context is dependent but does not refer to a class,
5717 // class template, or class template partial specialization. Complain
5718 // and return early, to avoid the coming semantic disaster.
5719 Diag(D.getIdentifierLoc(),
5720 diag::err_template_qualified_declarator_no_match)
5721 << D.getCXXScopeSpec().getScopeRep()
5722 << D.getCXXScopeSpec().getRange();
5723 return nullptr;
5724 }
5725 bool IsDependentContext = DC->isDependentContext();
5726
5727 if (!IsDependentContext &&
5728 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5729 return nullptr;
5730
5731 // If a class is incomplete, do not parse entities inside it.
5732 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5733 Diag(D.getIdentifierLoc(),
5734 diag::err_member_def_undefined_record)
5735 << Name << DC << D.getCXXScopeSpec().getRange();
5736 return nullptr;
5737 }
5738 if (!D.getDeclSpec().isFriendSpecified()) {
5739 if (diagnoseQualifiedDeclaration(
5740 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5741 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5742 if (DC->isRecord())
5743 return nullptr;
5744
5745 D.setInvalidType();
5746 }
5747 }
5748
5749 // Check whether we need to rebuild the type of the given
5750 // declaration in the current instantiation.
5751 if (EnteringContext && IsDependentContext &&
5752 TemplateParamLists.size() != 0) {
5753 ContextRAII SavedContext(*this, DC);
5754 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5755 D.setInvalidType();
5756 }
5757 }
5758
5759 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5760 QualType R = TInfo->getType();
5761
5762 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5763 UPPC_DeclarationType))
5764 D.setInvalidType();
5765
5766 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5767 forRedeclarationInCurContext());
5768
5769 // See if this is a redefinition of a variable in the same scope.
5770 if (!D.getCXXScopeSpec().isSet()) {
5771 bool IsLinkageLookup = false;
5772 bool CreateBuiltins = false;
5773
5774 // If the declaration we're planning to build will be a function
5775 // or object with linkage, then look for another declaration with
5776 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5777 //
5778 // If the declaration we're planning to build will be declared with
5779 // external linkage in the translation unit, create any builtin with
5780 // the same name.
5781 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5782 /* Do nothing*/;
5783 else if (CurContext->isFunctionOrMethod() &&
5784 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5785 R->isFunctionType())) {
5786 IsLinkageLookup = true;
5787 CreateBuiltins =
5788 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5789 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5790 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5791 CreateBuiltins = true;
5792
5793 if (IsLinkageLookup) {
5794 Previous.clear(LookupRedeclarationWithLinkage);
5795 Previous.setRedeclarationKind(ForExternalRedeclaration);
5796 }
5797
5798 LookupName(Previous, S, CreateBuiltins);
5799 } else { // Something like "int foo::x;"
5800 LookupQualifiedName(Previous, DC);
5801
5802 // C++ [dcl.meaning]p1:
5803 // When the declarator-id is qualified, the declaration shall refer to a
5804 // previously declared member of the class or namespace to which the
5805 // qualifier refers (or, in the case of a namespace, of an element of the
5806 // inline namespace set of that namespace (7.3.1)) or to a specialization
5807 // thereof; [...]
5808 //
5809 // Note that we already checked the context above, and that we do not have
5810 // enough information to make sure that Previous contains the declaration
5811 // we want to match. For example, given:
5812 //
5813 // class X {
5814 // void f();
5815 // void f(float);
5816 // };
5817 //
5818 // void X::f(int) { } // ill-formed
5819 //
5820 // In this case, Previous will point to the overload set
5821 // containing the two f's declared in X, but neither of them
5822 // matches.
5823
5824 // C++ [dcl.meaning]p1:
5825 // [...] the member shall not merely have been introduced by a
5826 // using-declaration in the scope of the class or namespace nominated by
5827 // the nested-name-specifier of the declarator-id.
5828 RemoveUsingDecls(Previous);
5829 }
5830
5831 if (Previous.isSingleResult() &&
5832 Previous.getFoundDecl()->isTemplateParameter()) {
5833 // Maybe we will complain about the shadowed template parameter.
5834 if (!D.isInvalidType())
5835 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5836 Previous.getFoundDecl());
5837
5838 // Just pretend that we didn't see the previous declaration.
5839 Previous.clear();
5840 }
5841
5842 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5843 // Forget that the previous declaration is the injected-class-name.
5844 Previous.clear();
5845
5846 // In C++, the previous declaration we find might be a tag type
5847 // (class or enum). In this case, the new declaration will hide the
5848 // tag type. Note that this applies to functions, function templates, and
5849 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5850 if (Previous.isSingleTagDecl() &&
5851 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5852 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5853 Previous.clear();
5854
5855 // Check that there are no default arguments other than in the parameters
5856 // of a function declaration (C++ only).
5857 if (getLangOpts().CPlusPlus)
5858 CheckExtraCXXDefaultArguments(D);
5859
5860 NamedDecl *New;
5861
5862 bool AddToScope = true;
5863 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5864 if (TemplateParamLists.size()) {
5865 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5866 return nullptr;
5867 }
5868
5869 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5870 } else if (R->isFunctionType()) {
5871 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5872 TemplateParamLists,
5873 AddToScope);
5874 } else {
5875 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5876 AddToScope);
5877 }
5878
5879 if (!New)
5880 return nullptr;
5881
5882 // If this has an identifier and is not a function template specialization,
5883 // add it to the scope stack.
5884 if (New->getDeclName() && AddToScope)
5885 PushOnScopeChains(New, S);
5886
5887 if (isInOpenMPDeclareTargetContext())
5888 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5889
5890 return New;
5891}
5892
5893/// Helper method to turn variable array types into constant array
5894/// types in certain situations which would otherwise be errors (for
5895/// GCC compatibility).
5896static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5897 ASTContext &Context,
5898 bool &SizeIsNegative,
5899 llvm::APSInt &Oversized) {
5900 // This method tries to turn a variable array into a constant
5901 // array even when the size isn't an ICE. This is necessary
5902 // for compatibility with code that depends on gcc's buggy
5903 // constant expression folding, like struct {char x[(int)(char*)2];}
5904 SizeIsNegative = false;
5905 Oversized = 0;
5906
5907 if (T->isDependentType())
5908 return QualType();
5909
5910 QualifierCollector Qs;
5911 const Type *Ty = Qs.strip(T);
5912
5913 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5914 QualType Pointee = PTy->getPointeeType();
5915 QualType FixedType =
5916 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5917 Oversized);
5918 if (FixedType.isNull()) return FixedType;
5919 FixedType = Context.getPointerType(FixedType);
5920 return Qs.apply(Context, FixedType);
5921 }
5922 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5923 QualType Inner = PTy->getInnerType();
5924 QualType FixedType =
5925 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5926 Oversized);
5927 if (FixedType.isNull()) return FixedType;
5928 FixedType = Context.getParenType(FixedType);
5929 return Qs.apply(Context, FixedType);
5930 }
5931
5932 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5933 if (!VLATy)
5934 return QualType();
5935
5936 QualType ElemTy = VLATy->getElementType();
5937 if (ElemTy->isVariablyModifiedType()) {
5938 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
5939 SizeIsNegative, Oversized);
5940 if (ElemTy.isNull())
5941 return QualType();
5942 }
5943
5944 Expr::EvalResult Result;
5945 if (!VLATy->getSizeExpr() ||
5946 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5947 return QualType();
5948
5949 llvm::APSInt Res = Result.Val.getInt();
5950
5951 // Check whether the array size is negative.
5952 if (Res.isSigned() && Res.isNegative()) {
5953 SizeIsNegative = true;
5954 return QualType();
5955 }
5956
5957 // Check whether the array is too large to be addressed.
5958 unsigned ActiveSizeBits =
5959 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
5960 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
5961 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
5962 : Res.getActiveBits();
5963 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5964 Oversized = Res;
5965 return QualType();
5966 }
5967
5968 return Context.getConstantArrayType(ElemTy, Res, VLATy->getSizeExpr(),
5969 ArrayType::Normal, 0);
5970}
5971
5972static void
5973FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5974 SrcTL = SrcTL.getUnqualifiedLoc();
5975 DstTL = DstTL.getUnqualifiedLoc();
5976 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5977 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5978 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5979 DstPTL.getPointeeLoc());
5980 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5981 return;
5982 }
5983 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5984 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5985 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5986 DstPTL.getInnerLoc());
5987 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5988 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5989 return;
5990 }
5991 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5992 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5993 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5994 TypeLoc DstElemTL = DstATL.getElementLoc();
5995 if (VariableArrayTypeLoc SrcElemATL =
5996 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
5997 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
5998 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
5999 } else {
6000 DstElemTL.initializeFullCopy(SrcElemTL);
6001 }
6002 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6003 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6004 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6005}
6006
6007/// Helper method to turn variable array types into constant array
6008/// types in certain situations which would otherwise be errors (for
6009/// GCC compatibility).
6010static TypeSourceInfo*
6011TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6012 ASTContext &Context,
6013 bool &SizeIsNegative,
6014 llvm::APSInt &Oversized) {
6015 QualType FixedTy
6016 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6017 SizeIsNegative, Oversized);
6018 if (FixedTy.isNull())
6019 return nullptr;
6020 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6021 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6022 FixedTInfo->getTypeLoc());
6023 return FixedTInfo;
6024}
6025
6026/// Register the given locally-scoped extern "C" declaration so
6027/// that it can be found later for redeclarations. We include any extern "C"
6028/// declaration that is not visible in the translation unit here, not just
6029/// function-scope declarations.
6030void
6031Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6032 if (!getLangOpts().CPlusPlus &&
6033 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6034 // Don't need to track declarations in the TU in C.
6035 return;
6036
6037 // Note that we have a locally-scoped external with this name.
6038 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6039}
6040
6041NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6042 // FIXME: We can have multiple results via __attribute__((overloadable)).
6043 auto Result = Context.getExternCContextDecl()->lookup(Name);
6044 return Result.empty() ? nullptr : *Result.begin();
6045}
6046
6047/// Diagnose function specifiers on a declaration of an identifier that
6048/// does not identify a function.
6049void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6050 // FIXME: We should probably indicate the identifier in question to avoid
6051 // confusion for constructs like "virtual int a(), b;"
6052 if (DS.isVirtualSpecified())
6053 Diag(DS.getVirtualSpecLoc(),
6054 diag::err_virtual_non_function);
6055
6056 if (DS.hasExplicitSpecifier())
6057 Diag(DS.getExplicitSpecLoc(),
6058 diag::err_explicit_non_function);
6059
6060 if (DS.isNoreturnSpecified())
6061 Diag(DS.getNoreturnSpecLoc(),
6062 diag::err_noreturn_non_function);
6063}
6064
6065NamedDecl*
6066Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6067 TypeSourceInfo *TInfo, LookupResult &Previous) {
6068 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6069 if (D.getCXXScopeSpec().isSet()) {
6070 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6071 << D.getCXXScopeSpec().getRange();
6072 D.setInvalidType();
6073 // Pretend we didn't see the scope specifier.
6074 DC = CurContext;
6075 Previous.clear();
6076 }
6077
6078 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6079
6080 if (D.getDeclSpec().isInlineSpecified())
6081 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6082 << getLangOpts().CPlusPlus17;
6083 if (D.getDeclSpec().hasConstexprSpecifier())
6084 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6085 << 1 << D.getDeclSpec().getConstexprSpecifier();
6086
6087 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6088 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6089 Diag(D.getName().StartLocation,
6090 diag::err_deduction_guide_invalid_specifier)
6091 << "typedef";
6092 else
6093 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6094 << D.getName().getSourceRange();
6095 return nullptr;
6096 }
6097
6098 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6099 if (!NewTD) return nullptr;
6100
6101 // Handle attributes prior to checking for duplicates in MergeVarDecl
6102 ProcessDeclAttributes(S, NewTD, D);
6103
6104 CheckTypedefForVariablyModifiedType(S, NewTD);
6105
6106 bool Redeclaration = D.isRedeclaration();
6107 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6108 D.setRedeclaration(Redeclaration);
6109 return ND;
6110}
6111
6112void
6113Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6114 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6115 // then it shall have block scope.
6116 // Note that variably modified types must be fixed before merging the decl so
6117 // that redeclarations will match.
6118 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6119 QualType T = TInfo->getType();
6120 if (T->isVariablyModifiedType()) {
6121 setFunctionHasBranchProtectedScope();
6122
6123 if (S->getFnParent() == nullptr) {
6124 bool SizeIsNegative;
6125 llvm::APSInt Oversized;
6126 TypeSourceInfo *FixedTInfo =
6127 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6128 SizeIsNegative,
6129 Oversized);
6130 if (FixedTInfo) {
6131 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6132 NewTD->setTypeSourceInfo(FixedTInfo);
6133 } else {
6134 if (SizeIsNegative)
6135 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6136 else if (T->isVariableArrayType())
6137 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6138 else if (Oversized.getBoolValue())
6139 Diag(NewTD->getLocation(), diag::err_array_too_large)
6140 << Oversized.toString(10);
6141 else
6142 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6143 NewTD->setInvalidDecl();
6144 }
6145 }
6146 }
6147}
6148
6149/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6150/// declares a typedef-name, either using the 'typedef' type specifier or via
6151/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6152NamedDecl*
6153Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6154 LookupResult &Previous, bool &Redeclaration) {
6155
6156 // Find the shadowed declaration before filtering for scope.
6157 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6158
6159 // Merge the decl with the existing one if appropriate. If the decl is
6160 // in an outer scope, it isn't the same thing.
6161 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6162 /*AllowInlineNamespace*/false);
6163 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6164 if (!Previous.empty()) {
6165 Redeclaration = true;
6166 MergeTypedefNameDecl(S, NewTD, Previous);
6167 } else {
6168 inferGslPointerAttribute(NewTD);
6169 }
6170
6171 if (ShadowedDecl && !Redeclaration)
6172 CheckShadow(NewTD, ShadowedDecl, Previous);
6173
6174 // If this is the C FILE type, notify the AST context.
6175 if (IdentifierInfo *II = NewTD->getIdentifier())
6176 if (!NewTD->isInvalidDecl() &&
6177 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6178 if (II->isStr("FILE"))
6179 Context.setFILEDecl(NewTD);
6180 else if (II->isStr("jmp_buf"))
6181 Context.setjmp_bufDecl(NewTD);
6182 else if (II->isStr("sigjmp_buf"))
6183 Context.setsigjmp_bufDecl(NewTD);
6184 else if (II->isStr("ucontext_t"))
6185 Context.setucontext_tDecl(NewTD);
6186 }
6187
6188 return NewTD;
6189}
6190
6191/// Determines whether the given declaration is an out-of-scope
6192/// previous declaration.
6193///
6194/// This routine should be invoked when name lookup has found a
6195/// previous declaration (PrevDecl) that is not in the scope where a
6196/// new declaration by the same name is being introduced. If the new
6197/// declaration occurs in a local scope, previous declarations with
6198/// linkage may still be considered previous declarations (C99
6199/// 6.2.2p4-5, C++ [basic.link]p6).
6200///
6201/// \param PrevDecl the previous declaration found by name
6202/// lookup
6203///
6204/// \param DC the context in which the new declaration is being
6205/// declared.
6206///
6207/// \returns true if PrevDecl is an out-of-scope previous declaration
6208/// for a new delcaration with the same name.
6209static bool
6210isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6211 ASTContext &Context) {
6212 if (!PrevDecl)
6213 return false;
6214
6215 if (!PrevDecl->hasLinkage())
6216 return false;
6217
6218 if (Context.getLangOpts().CPlusPlus) {
6219 // C++ [basic.link]p6:
6220 // If there is a visible declaration of an entity with linkage
6221 // having the same name and type, ignoring entities declared
6222 // outside the innermost enclosing namespace scope, the block
6223 // scope declaration declares that same entity and receives the
6224 // linkage of the previous declaration.
6225 DeclContext *OuterContext = DC->getRedeclContext();
6226 if (!OuterContext->isFunctionOrMethod())
6227 // This rule only applies to block-scope declarations.
6228 return false;
6229
6230 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6231 if (PrevOuterContext->isRecord())
6232 // We found a member function: ignore it.
6233 return false;
6234
6235 // Find the innermost enclosing namespace for the new and
6236 // previous declarations.
6237 OuterContext = OuterContext->getEnclosingNamespaceContext();
6238 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6239
6240 // The previous declaration is in a different namespace, so it
6241 // isn't the same function.
6242 if (!OuterContext->Equals(PrevOuterContext))
6243 return false;
6244 }
6245
6246 return true;
6247}
6248
6249static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6250 CXXScopeSpec &SS = D.getCXXScopeSpec();
6251 if (!SS.isSet()) return;
6252 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6253}
6254
6255bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6256 QualType type = decl->getType();
6257 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6258 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6259 // Various kinds of declaration aren't allowed to be __autoreleasing.
6260 unsigned kind = -1U;
6261 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6262 if (var->hasAttr<BlocksAttr>())
6263 kind = 0; // __block
6264 else if (!var->hasLocalStorage())
6265 kind = 1; // global
6266 } else if (isa<ObjCIvarDecl>(decl)) {
6267 kind = 3; // ivar
6268 } else if (isa<FieldDecl>(decl)) {
6269 kind = 2; // field
6270 }
6271
6272 if (kind != -1U) {
6273 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6274 << kind;
6275 }
6276 } else if (lifetime == Qualifiers::OCL_None) {
6277 // Try to infer lifetime.
6278 if (!type->isObjCLifetimeType())
6279 return false;
6280
6281 lifetime = type->getObjCARCImplicitLifetime();
6282 type = Context.getLifetimeQualifiedType(type, lifetime);
6283 decl->setType(type);
6284 }
6285
6286 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6287 // Thread-local variables cannot have lifetime.
6288 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6289 var->getTLSKind()) {
6290 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6291 << var->getType();
6292 return true;
6293 }
6294 }
6295
6296 return false;
6297}
6298
6299void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6300 if (Decl->getType().hasAddressSpace())
6301 return;
6302 if (Decl->getType()->isDependentType())
6303 return;
6304 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6305 QualType Type = Var->getType();
6306 if (Type->isSamplerT() || Type->isVoidType())
6307 return;
6308 LangAS ImplAS = LangAS::opencl_private;
6309 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6310 Var->hasGlobalStorage())
6311 ImplAS = LangAS::opencl_global;
6312 // If the original type from a decayed type is an array type and that array
6313 // type has no address space yet, deduce it now.
6314 if (auto DT = dyn_cast<DecayedType>(Type)) {
6315 auto OrigTy = DT->getOriginalType();
6316 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6317 // Add the address space to the original array type and then propagate
6318 // that to the element type through `getAsArrayType`.
6319 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6320 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6321 // Re-generate the decayed type.
6322 Type = Context.getDecayedType(OrigTy);
6323 }
6324 }
6325 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6326 // Apply any qualifiers (including address space) from the array type to
6327 // the element type. This implements C99 6.7.3p8: "If the specification of
6328 // an array type includes any type qualifiers, the element type is so
6329 // qualified, not the array type."
6330 if (Type->isArrayType())
6331 Type = QualType(Context.getAsArrayType(Type), 0);
6332 Decl->setType(Type);
6333 }
6334}
6335
6336static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6337 // Ensure that an auto decl is deduced otherwise the checks below might cache
6338 // the wrong linkage.
6339 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6339, __PRETTY_FUNCTION__))
;
6340
6341 // 'weak' only applies to declarations with external linkage.
6342 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6343 if (!ND.isExternallyVisible()) {
6344 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6345 ND.dropAttr<WeakAttr>();
6346 }
6347 }
6348 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6349 if (ND.isExternallyVisible()) {
6350 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6351 ND.dropAttr<WeakRefAttr>();
6352 ND.dropAttr<AliasAttr>();
6353 }
6354 }
6355
6356 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6357 if (VD->hasInit()) {
6358 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6359 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6360, __PRETTY_FUNCTION__))
6360 !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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6360, __PRETTY_FUNCTION__))
;
6361 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6362 VD->dropAttr<AliasAttr>();
6363 }
6364 }
6365 }
6366
6367 // 'selectany' only applies to externally visible variable declarations.
6368 // It does not apply to functions.
6369 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6370 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6371 S.Diag(Attr->getLocation(),
6372 diag::err_attribute_selectany_non_extern_data);
6373 ND.dropAttr<SelectAnyAttr>();
6374 }
6375 }
6376
6377 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6378 auto *VD = dyn_cast<VarDecl>(&ND);
6379 bool IsAnonymousNS = false;
6380 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6381 if (VD) {
6382 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6383 while (NS && !IsAnonymousNS) {
6384 IsAnonymousNS = NS->isAnonymousNamespace();
6385 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6386 }
6387 }
6388 // dll attributes require external linkage. Static locals may have external
6389 // linkage but still cannot be explicitly imported or exported.
6390 // In Microsoft mode, a variable defined in anonymous namespace must have
6391 // external linkage in order to be exported.
6392 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6393 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6394 (!AnonNSInMicrosoftMode &&
6395 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6396 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6397 << &ND << Attr;
6398 ND.setInvalidDecl();
6399 }
6400 }
6401
6402 // Virtual functions cannot be marked as 'notail'.
6403 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6404 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6405 if (MD->isVirtual()) {
6406 S.Diag(ND.getLocation(),
6407 diag::err_invalid_attribute_on_virtual_function)
6408 << Attr;
6409 ND.dropAttr<NotTailCalledAttr>();
6410 }
6411
6412 // Check the attributes on the function type, if any.
6413 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6414 // Don't declare this variable in the second operand of the for-statement;
6415 // GCC miscompiles that by ending its lifetime before evaluating the
6416 // third operand. See gcc.gnu.org/PR86769.
6417 AttributedTypeLoc ATL;
6418 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6419 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6420 TL = ATL.getModifiedLoc()) {
6421 // The [[lifetimebound]] attribute can be applied to the implicit object
6422 // parameter of a non-static member function (other than a ctor or dtor)
6423 // by applying it to the function type.
6424 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6425 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6426 if (!MD || MD->isStatic()) {
6427 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6428 << !MD << A->getRange();
6429 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6430 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6431 << isa<CXXDestructorDecl>(MD) << A->getRange();
6432 }
6433 }
6434 }
6435 }
6436}
6437
6438static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6439 NamedDecl *NewDecl,
6440 bool IsSpecialization,
6441 bool IsDefinition) {
6442 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6443 return;
6444
6445 bool IsTemplate = false;
6446 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6447 OldDecl = OldTD->getTemplatedDecl();
6448 IsTemplate = true;
6449 if (!IsSpecialization)
6450 IsDefinition = false;
6451 }
6452 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6453 NewDecl = NewTD->getTemplatedDecl();
6454 IsTemplate = true;
6455 }
6456
6457 if (!OldDecl || !NewDecl)
6458 return;
6459
6460 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6461 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6462 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6463 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6464
6465 // dllimport and dllexport are inheritable attributes so we have to exclude
6466 // inherited attribute instances.
6467 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6468 (NewExportAttr && !NewExportAttr->isInherited());
6469
6470 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6471 // the only exception being explicit specializations.
6472 // Implicitly generated declarations are also excluded for now because there
6473 // is no other way to switch these to use dllimport or dllexport.
6474 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6475
6476 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6477 // Allow with a warning for free functions and global variables.
6478 bool JustWarn = false;
6479 if (!OldDecl->isCXXClassMember()) {
6480 auto *VD = dyn_cast<VarDecl>(OldDecl);
6481 if (VD && !VD->getDescribedVarTemplate())
6482 JustWarn = true;
6483 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6484 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6485 JustWarn = true;
6486 }
6487
6488 // We cannot change a declaration that's been used because IR has already
6489 // been emitted. Dllimported functions will still work though (modulo
6490 // address equality) as they can use the thunk.
6491 if (OldDecl->isUsed())
6492 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6493 JustWarn = false;
6494
6495 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6496 : diag::err_attribute_dll_redeclaration;
6497 S.Diag(NewDecl->getLocation(), DiagID)
6498 << NewDecl
6499 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6500 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6501 if (!JustWarn) {
6502 NewDecl->setInvalidDecl();
6503 return;
6504 }
6505 }
6506
6507 // A redeclaration is not allowed to drop a dllimport attribute, the only
6508 // exceptions being inline function definitions (except for function
6509 // templates), local extern declarations, qualified friend declarations or
6510 // special MSVC extension: in the last case, the declaration is treated as if
6511 // it were marked dllexport.
6512 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6513 bool IsMicrosoft =
6514 S.Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6515 S.Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment();
6516 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6517 // Ignore static data because out-of-line definitions are diagnosed
6518 // separately.
6519 IsStaticDataMember = VD->isStaticDataMember();
6520 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6521 VarDecl::DeclarationOnly;
6522 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6523 IsInline = FD->isInlined();
6524 IsQualifiedFriend = FD->getQualifier() &&
6525 FD->getFriendObjectKind() == Decl::FOK_Declared;
6526 }
6527
6528 if (OldImportAttr && !HasNewAttr &&
6529 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6530 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6531 if (IsMicrosoft && IsDefinition) {
6532 S.Diag(NewDecl->getLocation(),
6533 diag::warn_redeclaration_without_import_attribute)
6534 << NewDecl;
6535 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6536 NewDecl->dropAttr<DLLImportAttr>();
6537 NewDecl->addAttr(
6538 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6539 } else {
6540 S.Diag(NewDecl->getLocation(),
6541 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6542 << NewDecl << OldImportAttr;
6543 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6544 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6545 OldDecl->dropAttr<DLLImportAttr>();
6546 NewDecl->dropAttr<DLLImportAttr>();
6547 }
6548 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6549 // In MinGW, seeing a function declared inline drops the dllimport
6550 // attribute.
6551 OldDecl->dropAttr<DLLImportAttr>();
6552 NewDecl->dropAttr<DLLImportAttr>();
6553 S.Diag(NewDecl->getLocation(),
6554 diag::warn_dllimport_dropped_from_inline_function)
6555 << NewDecl << OldImportAttr;
6556 }
6557
6558 // A specialization of a class template member function is processed here
6559 // since it's a redeclaration. If the parent class is dllexport, the
6560 // specialization inherits that attribute. This doesn't happen automatically
6561 // since the parent class isn't instantiated until later.
6562 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6563 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6564 !NewImportAttr && !NewExportAttr) {
6565 if (const DLLExportAttr *ParentExportAttr =
6566 MD->getParent()->getAttr<DLLExportAttr>()) {
6567 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6568 NewAttr->setInherited(true);
6569 NewDecl->addAttr(NewAttr);
6570 }
6571 }
6572 }
6573}
6574
6575/// Given that we are within the definition of the given function,
6576/// will that definition behave like C99's 'inline', where the
6577/// definition is discarded except for optimization purposes?
6578static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6579 // Try to avoid calling GetGVALinkageForFunction.
6580
6581 // All cases of this require the 'inline' keyword.
6582 if (!FD->isInlined()) return false;
6583
6584 // This is only possible in C++ with the gnu_inline attribute.
6585 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6586 return false;
6587
6588 // Okay, go ahead and call the relatively-more-expensive function.
6589 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6590}
6591
6592/// Determine whether a variable is extern "C" prior to attaching
6593/// an initializer. We can't just call isExternC() here, because that
6594/// will also compute and cache whether the declaration is externally
6595/// visible, which might change when we attach the initializer.
6596///
6597/// This can only be used if the declaration is known to not be a
6598/// redeclaration of an internal linkage declaration.
6599///
6600/// For instance:
6601///
6602/// auto x = []{};
6603///
6604/// Attaching the initializer here makes this declaration not externally
6605/// visible, because its type has internal linkage.
6606///
6607/// FIXME: This is a hack.
6608template<typename T>
6609static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6610 if (S.getLangOpts().CPlusPlus) {
6611 // In C++, the overloadable attribute negates the effects of extern "C".
6612 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6613 return false;
6614
6615 // So do CUDA's host/device attributes.
6616 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6617 D->template hasAttr<CUDAHostAttr>()))
6618 return false;
6619 }
6620 return D->isExternC();
6621}
6622
6623static bool shouldConsiderLinkage(const VarDecl *VD) {
6624 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6625 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6626 isa<OMPDeclareMapperDecl>(DC))
6627 return VD->hasExternalStorage();
6628 if (DC->isFileContext())
6629 return true;
6630 if (DC->isRecord())
6631 return false;
6632 if (isa<RequiresExprBodyDecl>(DC))
6633 return false;
6634 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6634)
;
6635}
6636
6637static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6638 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6639 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6640 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6641 return true;
6642 if (DC->isRecord())
6643 return false;
6644 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6644)
;
6645}
6646
6647static bool hasParsedAttr(Scope *S, const Declarator &PD,
6648 ParsedAttr::Kind Kind) {
6649 // Check decl attributes on the DeclSpec.
6650 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6651 return true;
6652
6653 // Walk the declarator structure, checking decl attributes that were in a type
6654 // position to the decl itself.
6655 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6656 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6657 return true;
6658 }
6659
6660 // Finally, check attributes on the decl itself.
6661 return PD.getAttributes().hasAttribute(Kind);
6662}
6663
6664/// Adjust the \c DeclContext for a function or variable that might be a
6665/// function-local external declaration.
6666bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6667 if (!DC->isFunctionOrMethod())
6668 return false;
6669
6670 // If this is a local extern function or variable declared within a function
6671 // template, don't add it into the enclosing namespace scope until it is
6672 // instantiated; it might have a dependent type right now.
6673 if (DC->isDependentContext())
6674 return true;
6675
6676 // C++11 [basic.link]p7:
6677 // When a block scope declaration of an entity with linkage is not found to
6678 // refer to some other declaration, then that entity is a member of the
6679 // innermost enclosing namespace.
6680 //
6681 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6682 // semantically-enclosing namespace, not a lexically-enclosing one.
6683 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6684 DC = DC->getParent();
6685 return true;
6686}
6687
6688/// Returns true if given declaration has external C language linkage.
6689static bool isDeclExternC(const Decl *D) {
6690 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6691 return FD->isExternC();
6692 if (const auto *VD = dyn_cast<VarDecl>(D))
6693 return VD->isExternC();
6694
6695 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6695)
;
6696}
6697/// Returns true if there hasn't been any invalid type diagnosed.
6698static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6699 DeclContext *DC, QualType R) {
6700 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6701 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6702 // argument.
6703 if (R->isImageType() || R->isPipeType()) {
6704 Se.Diag(D.getIdentifierLoc(),
6705 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6706 << R;
6707 D.setInvalidType();
6708 return false;
6709 }
6710
6711 // OpenCL v1.2 s6.9.r:
6712 // The event type cannot be used to declare a program scope variable.
6713 // OpenCL v2.0 s6.9.q:
6714 // The clk_event_t and reserve_id_t types cannot be declared in program
6715 // scope.
6716 if (NULL__null == S->getParent()) {
6717 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6718 Se.Diag(D.getIdentifierLoc(),
6719 diag::err_invalid_type_for_program_scope_var)
6720 << R;
6721 D.setInvalidType();
6722 return false;
6723 }
6724 }
6725
6726 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6727 QualType NR = R;
6728 while (NR->isPointerType()) {
6729 if (NR->isFunctionPointerType()) {
6730 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6731 D.setInvalidType();
6732 return false;
6733 }
6734 NR = NR->getPointeeType();
6735 }
6736
6737 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6738 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6739 // half array type (unless the cl_khr_fp16 extension is enabled).
6740 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6741 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6742 D.setInvalidType();
6743 return false;
6744 }
6745 }
6746
6747 // OpenCL v1.2 s6.9.r:
6748 // The event type cannot be used with the __local, __constant and __global
6749 // address space qualifiers.
6750 if (R->isEventT()) {
6751 if (R.getAddressSpace() != LangAS::opencl_private) {
6752 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6753 D.setInvalidType();
6754 return false;
6755 }
6756 }
6757
6758 // C++ for OpenCL does not allow the thread_local storage qualifier.
6759 // OpenCL C does not support thread_local either, and
6760 // also reject all other thread storage class specifiers.
6761 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6762 if (TSC != TSCS_unspecified) {
6763 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6764 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6765 diag::err_opencl_unknown_type_specifier)
6766 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6767 << DeclSpec::getSpecifierName(TSC) << 1;
6768 D.setInvalidType();
6769 return false;
6770 }
6771
6772 if (R->isSamplerT()) {
6773 // OpenCL v1.2 s6.9.b p4:
6774 // The sampler type cannot be used with the __local and __global address
6775 // space qualifiers.
6776 if (R.getAddressSpace() == LangAS::opencl_local ||
6777 R.getAddressSpace() == LangAS::opencl_global) {
6778 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6779 D.setInvalidType();
6780 }
6781
6782 // OpenCL v1.2 s6.12.14.1:
6783 // A global sampler must be declared with either the constant address
6784 // space qualifier or with the const qualifier.
6785 if (DC->isTranslationUnit() &&
6786 !(R.getAddressSpace() == LangAS::opencl_constant ||
6787 R.isConstQualified())) {
6788 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6789 D.setInvalidType();
6790 }
6791 if (D.isInvalidType())
6792 return false;
6793 }
6794 return true;
6795}
6796
6797NamedDecl *Sema::ActOnVariableDeclarator(
6798 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6799 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6800 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6801 QualType R = TInfo->getType();
6802 DeclarationName Name = GetNameForDeclarator(D).getName();
6803
6804 IdentifierInfo *II = Name.getAsIdentifierInfo();
6805
6806 if (D.isDecompositionDeclarator()) {
6807 // Take the name of the first declarator as our name for diagnostic
6808 // purposes.
6809 auto &Decomp = D.getDecompositionDeclarator();
6810 if (!Decomp.bindings().empty()) {
6811 II = Decomp.bindings()[0].Name;
6812 Name = II;
6813 }
6814 } else if (!II) {
6815 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6816 return nullptr;
6817 }
6818
6819
6820 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6821 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6822
6823 // dllimport globals without explicit storage class are treated as extern. We
6824 // have to change the storage class this early to get the right DeclContext.
6825 if (SC == SC_None && !DC->isRecord() &&
6826 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6827 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6828 SC = SC_Extern;
6829
6830 DeclContext *OriginalDC = DC;
6831 bool IsLocalExternDecl = SC == SC_Extern &&
6832 adjustContextForLocalExternDecl(DC);
6833
6834 if (SCSpec == DeclSpec::SCS_mutable) {
6835 // mutable can only appear on non-static class members, so it's always
6836 // an error here
6837 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6838 D.setInvalidType();
6839 SC = SC_None;
6840 }
6841
6842 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6843 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6844 D.getDeclSpec().getStorageClassSpecLoc())) {
6845 // In C++11, the 'register' storage class specifier is deprecated.
6846 // Suppress the warning in system macros, it's used in macros in some
6847 // popular C system headers, such as in glibc's htonl() macro.
6848 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6849 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6850 : diag::warn_deprecated_register)
6851 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6852 }
6853
6854 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6855
6856 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6857 // C99 6.9p2: The storage-class specifiers auto and register shall not
6858 // appear in the declaration specifiers in an external declaration.
6859 // Global Register+Asm is a GNU extension we support.
6860 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6861 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6862 D.setInvalidType();
6863 }
6864 }
6865
6866 bool IsMemberSpecialization = false;
6867 bool IsVariableTemplateSpecialization = false;
6868 bool IsPartialSpecialization = false;
6869 bool IsVariableTemplate = false;
6870 VarDecl *NewVD = nullptr;
6871 VarTemplateDecl *NewTemplate = nullptr;
6872 TemplateParameterList *TemplateParams = nullptr;
6873 if (!getLangOpts().CPlusPlus) {
6874 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6875 II, R, TInfo, SC);
6876
6877 if (R->getContainedDeducedType())
6878 ParsingInitForAutoVars.insert(NewVD);
6879
6880 if (D.isInvalidType())
6881 NewVD->setInvalidDecl();
6882
6883 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6884 NewVD->hasLocalStorage())
6885 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6886 NTCUC_AutoVar, NTCUK_Destruct);
6887 } else {
6888 bool Invalid = false;
6889
6890 if (DC->isRecord() && !CurContext->isRecord()) {
6891 // This is an out-of-line definition of a static data member.
6892 switch (SC) {
6893 case SC_None:
6894 break;
6895 case SC_Static:
6896 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6897 diag::err_static_out_of_line)
6898 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6899 break;
6900 case SC_Auto:
6901 case SC_Register:
6902 case SC_Extern:
6903 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6904 // to names of variables declared in a block or to function parameters.
6905 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6906 // of class members
6907
6908 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6909 diag::err_storage_class_for_static_member)
6910 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6911 break;
6912 case SC_PrivateExtern:
6913 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 6913)
;
6914 }
6915 }
6916
6917 if (SC == SC_Static && CurContext->isRecord()) {
6918 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6919 // Walk up the enclosing DeclContexts to check for any that are
6920 // incompatible with static data members.
6921 const DeclContext *FunctionOrMethod = nullptr;
6922 const CXXRecordDecl *AnonStruct = nullptr;
6923 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6924 if (Ctxt->isFunctionOrMethod()) {
6925 FunctionOrMethod = Ctxt;
6926 break;
6927 }
6928 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6929 if (ParentDecl && !ParentDecl->getDeclName()) {
6930 AnonStruct = ParentDecl;
6931 break;
6932 }
6933 }
6934 if (FunctionOrMethod) {
6935 // C++ [class.static.data]p5: A local class shall not have static data
6936 // members.
6937 Diag(D.getIdentifierLoc(),
6938 diag::err_static_data_member_not_allowed_in_local_class)
6939 << Name << RD->getDeclName() << RD->getTagKind();
6940 } else if (AnonStruct) {
6941 // C++ [class.static.data]p4: Unnamed classes and classes contained
6942 // directly or indirectly within unnamed classes shall not contain
6943 // static data members.
6944 Diag(D.getIdentifierLoc(),
6945 diag::err_static_data_member_not_allowed_in_anon_struct)
6946 << Name << AnonStruct->getTagKind();
6947 Invalid = true;
6948 } else if (RD->isUnion()) {
6949 // C++98 [class.union]p1: If a union contains a static data member,
6950 // the program is ill-formed. C++11 drops this restriction.
6951 Diag(D.getIdentifierLoc(),
6952 getLangOpts().CPlusPlus11
6953 ? diag::warn_cxx98_compat_static_data_member_in_union
6954 : diag::ext_static_data_member_in_union) << Name;
6955 }
6956 }
6957 }
6958
6959 // Match up the template parameter lists with the scope specifier, then
6960 // determine whether we have a template or a template specialization.
6961 bool InvalidScope = false;
6962 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6963 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6964 D.getCXXScopeSpec(),
6965 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6966 ? D.getName().TemplateId
6967 : nullptr,
6968 TemplateParamLists,
6969 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6970 Invalid |= InvalidScope;
6971
6972 if (TemplateParams) {
6973 if (!TemplateParams->size() &&
6974 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6975 // There is an extraneous 'template<>' for this variable. Complain
6976 // about it, but allow the declaration of the variable.
6977 Diag(TemplateParams->getTemplateLoc(),
6978 diag::err_template_variable_noparams)
6979 << II
6980 << SourceRange(TemplateParams->getTemplateLoc(),
6981 TemplateParams->getRAngleLoc());
6982 TemplateParams = nullptr;
6983 } else {
6984 // Check that we can declare a template here.
6985 if (CheckTemplateDeclScope(S, TemplateParams))
6986 return nullptr;
6987
6988 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6989 // This is an explicit specialization or a partial specialization.
6990 IsVariableTemplateSpecialization = true;
6991 IsPartialSpecialization = TemplateParams->size() > 0;
6992 } else { // if (TemplateParams->size() > 0)
6993 // This is a template declaration.
6994 IsVariableTemplate = true;
6995
6996 // Only C++1y supports variable templates (N3651).
6997 Diag(D.getIdentifierLoc(),
6998 getLangOpts().CPlusPlus14
6999 ? diag::warn_cxx11_compat_variable_template
7000 : diag::ext_variable_template);
7001 }
7002 }
7003 } else {
7004 // Check that we can declare a member specialization here.
7005 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7006 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7007 return nullptr;
7008 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7010, __PRETTY_FUNCTION__))
7009 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7010, __PRETTY_FUNCTION__))
7010 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7010, __PRETTY_FUNCTION__))
;
7011 }
7012
7013 if (IsVariableTemplateSpecialization) {
7014 SourceLocation TemplateKWLoc =
7015 TemplateParamLists.size() > 0
7016 ? TemplateParamLists[0]->getTemplateLoc()
7017 : SourceLocation();
7018 DeclResult Res = ActOnVarTemplateSpecialization(
7019 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7020 IsPartialSpecialization);
7021 if (Res.isInvalid())
7022 return nullptr;
7023 NewVD = cast<VarDecl>(Res.get());
7024 AddToScope = false;
7025 } else if (D.isDecompositionDeclarator()) {
7026 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7027 D.getIdentifierLoc(), R, TInfo, SC,
7028 Bindings);
7029 } else
7030 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7031 D.getIdentifierLoc(), II, R, TInfo, SC);
7032
7033 // If this is supposed to be a variable template, create it as such.
7034 if (IsVariableTemplate) {
7035 NewTemplate =
7036 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7037 TemplateParams, NewVD);
7038 NewVD->setDescribedVarTemplate(NewTemplate);
7039 }
7040
7041 // If this decl has an auto type in need of deduction, make a note of the
7042 // Decl so we can diagnose uses of it in its own initializer.
7043 if (R->getContainedDeducedType())
7044 ParsingInitForAutoVars.insert(NewVD);
7045
7046 if (D.isInvalidType() || Invalid) {
7047 NewVD->setInvalidDecl();
7048 if (NewTemplate)
7049 NewTemplate->setInvalidDecl();
7050 }
7051
7052 SetNestedNameSpecifier(*this, NewVD, D);
7053
7054 // If we have any template parameter lists that don't directly belong to
7055 // the variable (matching the scope specifier), store them.
7056 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7057 if (TemplateParamLists.size() > VDTemplateParamLists)
7058 NewVD->setTemplateParameterListsInfo(
7059 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7060 }
7061
7062 if (D.getDeclSpec().isInlineSpecified()) {
7063 if (!getLangOpts().CPlusPlus) {
7064 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7065 << 0;
7066 } else if (CurContext->isFunctionOrMethod()) {
7067 // 'inline' is not allowed on block scope variable declaration.
7068 Diag(D.getDeclSpec().getInlineSpecLoc(),
7069 diag::err_inline_declaration_block_scope) << Name
7070 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7071 } else {
7072 Diag(D.getDeclSpec().getInlineSpecLoc(),
7073 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7074 : diag::ext_inline_variable);
7075 NewVD->setInlineSpecified();
7076 }
7077 }
7078
7079 // Set the lexical context. If the declarator has a C++ scope specifier, the
7080 // lexical context will be different from the semantic context.
7081 NewVD->setLexicalDeclContext(CurContext);
7082 if (NewTemplate)
7083 NewTemplate->setLexicalDeclContext(CurContext);
7084
7085 if (IsLocalExternDecl) {
7086 if (D.isDecompositionDeclarator())
7087 for (auto *B : Bindings)
7088 B->setLocalExternDecl();
7089 else
7090 NewVD->setLocalExternDecl();
7091 }
7092
7093 bool EmitTLSUnsupportedError = false;
7094 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7095 // C++11 [dcl.stc]p4:
7096 // When thread_local is applied to a variable of block scope the
7097 // storage-class-specifier static is implied if it does not appear
7098 // explicitly.
7099 // Core issue: 'static' is not implied if the variable is declared
7100 // 'extern'.
7101 if (NewVD->hasLocalStorage() &&
7102 (SCSpec != DeclSpec::SCS_unspecified ||
7103 TSCS != DeclSpec::TSCS_thread_local ||
7104 !DC->isFunctionOrMethod()))
7105 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7106 diag::err_thread_non_global)
7107 << DeclSpec::getSpecifierName(TSCS);
7108 else if (!Context.getTargetInfo().isTLSSupported()) {
7109 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7110 getLangOpts().SYCLIsDevice) {
7111 // Postpone error emission until we've collected attributes required to
7112 // figure out whether it's a host or device variable and whether the
7113 // error should be ignored.
7114 EmitTLSUnsupportedError = true;
7115 // We still need to mark the variable as TLS so it shows up in AST with
7116 // proper storage class for other tools to use even if we're not going
7117 // to emit any code for it.
7118 NewVD->setTSCSpec(TSCS);
7119 } else
7120 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7121 diag::err_thread_unsupported);
7122 } else
7123 NewVD->setTSCSpec(TSCS);
7124 }
7125
7126 switch (D.getDeclSpec().getConstexprSpecifier()) {
7127 case CSK_unspecified:
7128 break;
7129
7130 case CSK_consteval:
7131 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7132 diag::err_constexpr_wrong_decl_kind)
7133 << D.getDeclSpec().getConstexprSpecifier();
7134 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7135
7136 case CSK_constexpr:
7137 NewVD->setConstexpr(true);
7138 MaybeAddCUDAConstantAttr(NewVD);
7139 // C++1z [dcl.spec.constexpr]p1:
7140 // A static data member declared with the constexpr specifier is
7141 // implicitly an inline variable.
7142 if (NewVD->isStaticDataMember() &&
7143 (getLangOpts().CPlusPlus17 ||
7144 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7145 NewVD->setImplicitlyInline();
7146 break;
7147
7148 case CSK_constinit:
7149 if (!NewVD->hasGlobalStorage())
7150 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7151 diag::err_constinit_local_variable);
7152 else
7153 NewVD->addAttr(ConstInitAttr::Create(
7154 Context, D.getDeclSpec().getConstexprSpecLoc(),
7155 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7156 break;
7157 }
7158
7159 // C99 6.7.4p3
7160 // An inline definition of a function with external linkage shall
7161 // not contain a definition of a modifiable object with static or
7162 // thread storage duration...
7163 // We only apply this when the function is required to be defined
7164 // elsewhere, i.e. when the function is not 'extern inline'. Note
7165 // that a local variable with thread storage duration still has to
7166 // be marked 'static'. Also note that it's possible to get these
7167 // semantics in C++ using __attribute__((gnu_inline)).
7168 if (SC == SC_Static && S->getFnParent() != nullptr &&
7169 !NewVD->getType().isConstQualified()) {
7170 FunctionDecl *CurFD = getCurFunctionDecl();
7171 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7172 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7173 diag::warn_static_local_in_extern_inline);
7174 MaybeSuggestAddingStaticToDecl(CurFD);
7175 }
7176 }
7177
7178 if (D.getDeclSpec().isModulePrivateSpecified()) {
7179 if (IsVariableTemplateSpecialization)
7180 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7181 << (IsPartialSpecialization ? 1 : 0)
7182 << FixItHint::CreateRemoval(
7183 D.getDeclSpec().getModulePrivateSpecLoc());
7184 else if (IsMemberSpecialization)
7185 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7186 << 2
7187 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7188 else if (NewVD->hasLocalStorage())
7189 Diag(NewVD->getLocation(), diag::err_module_private_local)
7190 << 0 << NewVD
7191 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7192 << FixItHint::CreateRemoval(
7193 D.getDeclSpec().getModulePrivateSpecLoc());
7194 else {
7195 NewVD->setModulePrivate();
7196 if (NewTemplate)
7197 NewTemplate->setModulePrivate();
7198 for (auto *B : Bindings)
7199 B->setModulePrivate();
7200 }
7201 }
7202
7203 if (getLangOpts().OpenCL) {
7204
7205 deduceOpenCLAddressSpace(NewVD);
7206
7207 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7208 }
7209
7210 // Handle attributes prior to checking for duplicates in MergeVarDecl
7211 ProcessDeclAttributes(S, NewVD, D);
7212
7213 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7214 getLangOpts().SYCLIsDevice) {
7215 if (EmitTLSUnsupportedError &&
7216 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7217 (getLangOpts().OpenMPIsDevice &&
7218 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7219 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7220 diag::err_thread_unsupported);
7221
7222 if (EmitTLSUnsupportedError &&
7223 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7224 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7225 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7226 // storage [duration]."
7227 if (SC == SC_None && S->getFnParent() != nullptr &&
7228 (NewVD->hasAttr<CUDASharedAttr>() ||
7229 NewVD->hasAttr<CUDAConstantAttr>())) {
7230 NewVD->setStorageClass(SC_Static);
7231 }
7232 }
7233
7234 // Ensure that dllimport globals without explicit storage class are treated as
7235 // extern. The storage class is set above using parsed attributes. Now we can
7236 // check the VarDecl itself.
7237 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7239, __PRETTY_FUNCTION__))
7238 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7239, __PRETTY_FUNCTION__))
7239 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7239, __PRETTY_FUNCTION__))
;
7240
7241 // In auto-retain/release, infer strong retension for variables of
7242 // retainable type.
7243 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7244 NewVD->setInvalidDecl();
7245
7246 // Handle GNU asm-label extension (encoded as an attribute).
7247 if (Expr *E = (Expr*)D.getAsmLabel()) {
7248 // The parser guarantees this is a string.
7249 StringLiteral *SE = cast<StringLiteral>(E);
7250 StringRef Label = SE->getString();
7251 if (S->getFnParent() != nullptr) {
7252 switch (SC) {
7253 case SC_None:
7254 case SC_Auto:
7255 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7256 break;
7257 case SC_Register:
7258 // Local Named register
7259 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7260 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7261 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7262 break;
7263 case SC_Static:
7264 case SC_Extern:
7265 case SC_PrivateExtern:
7266 break;
7267 }
7268 } else if (SC == SC_Register) {
7269 // Global Named register
7270 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7271 const auto &TI = Context.getTargetInfo();
7272 bool HasSizeMismatch;
7273
7274 if (!TI.isValidGCCRegisterName(Label))
7275 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7276 else if (!TI.validateGlobalRegisterVariable(Label,
7277 Context.getTypeSize(R),
7278 HasSizeMismatch))
7279 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7280 else if (HasSizeMismatch)
7281 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7282 }
7283
7284 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7285 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7286 NewVD->setInvalidDecl(true);
7287 }
7288 }
7289
7290 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7291 /*IsLiteralLabel=*/true,
7292 SE->getStrTokenLoc(0)));
7293 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7294 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7295 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7296 if (I != ExtnameUndeclaredIdentifiers.end()) {
7297 if (isDeclExternC(NewVD)) {
7298 NewVD->addAttr(I->second);
7299 ExtnameUndeclaredIdentifiers.erase(I);
7300 } else
7301 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7302 << /*Variable*/1 << NewVD;
7303 }
7304 }
7305
7306 // Find the shadowed declaration before filtering for scope.
7307 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7308 ? getShadowedDeclaration(NewVD, Previous)
7309 : nullptr;
7310
7311 // Don't consider existing declarations that are in a different
7312 // scope and are out-of-semantic-context declarations (if the new
7313 // declaration has linkage).
7314 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7315 D.getCXXScopeSpec().isNotEmpty() ||
7316 IsMemberSpecialization ||
7317 IsVariableTemplateSpecialization);
7318
7319 // Check whether the previous declaration is in the same block scope. This
7320 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7321 if (getLangOpts().CPlusPlus &&
7322 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7323 NewVD->setPreviousDeclInSameBlockScope(
7324 Previous.isSingleResult() && !Previous.isShadowed() &&
7325 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7326
7327 if (!getLangOpts().CPlusPlus) {
7328 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7329 } else {
7330 // If this is an explicit specialization of a static data member, check it.
7331 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7332 CheckMemberSpecialization(NewVD, Previous))
7333 NewVD->setInvalidDecl();
7334
7335 // Merge the decl with the existing one if appropriate.
7336 if (!Previous.empty()) {
7337 if (Previous.isSingleResult() &&
7338 isa<FieldDecl>(Previous.getFoundDecl()) &&
7339 D.getCXXScopeSpec().isSet()) {
7340 // The user tried to define a non-static data member
7341 // out-of-line (C++ [dcl.meaning]p1).
7342 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7343 << D.getCXXScopeSpec().getRange();
7344 Previous.clear();
7345 NewVD->setInvalidDecl();
7346 }
7347 } else if (D.getCXXScopeSpec().isSet()) {
7348 // No previous declaration in the qualifying scope.
7349 Diag(D.getIdentifierLoc(), diag::err_no_member)
7350 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7351 << D.getCXXScopeSpec().getRange();
7352 NewVD->setInvalidDecl();
7353 }
7354
7355 if (!IsVariableTemplateSpecialization)
7356 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7357
7358 if (NewTemplate) {
7359 VarTemplateDecl *PrevVarTemplate =
7360 NewVD->getPreviousDecl()
7361 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7362 : nullptr;
7363
7364 // Check the template parameter list of this declaration, possibly
7365 // merging in the template parameter list from the previous variable
7366 // template declaration.
7367 if (CheckTemplateParameterList(
7368 TemplateParams,
7369 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7370 : nullptr,
7371 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7372 DC->isDependentContext())
7373 ? TPC_ClassTemplateMember
7374 : TPC_VarTemplate))
7375 NewVD->setInvalidDecl();
7376
7377 // If we are providing an explicit specialization of a static variable
7378 // template, make a note of that.
7379 if (PrevVarTemplate &&
7380 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7381 PrevVarTemplate->setMemberSpecialization();
7382 }
7383 }
7384
7385 // Diagnose shadowed variables iff this isn't a redeclaration.
7386 if (ShadowedDecl && !D.isRedeclaration())
7387 CheckShadow(NewVD, ShadowedDecl, Previous);
7388
7389 ProcessPragmaWeak(S, NewVD);
7390
7391 // If this is the first declaration of an extern C variable, update
7392 // the map of such variables.
7393 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7394 isIncompleteDeclExternC(*this, NewVD))
7395 RegisterLocallyScopedExternCDecl(NewVD, S);
7396
7397 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7398 MangleNumberingContext *MCtx;
7399 Decl *ManglingContextDecl;
7400 std::tie(MCtx, ManglingContextDecl) =
7401 getCurrentMangleNumberContext(NewVD->getDeclContext());
7402 if (MCtx) {
7403 Context.setManglingNumber(
7404 NewVD, MCtx->getManglingNumber(
7405 NewVD, getMSManglingNumber(getLangOpts(), S)));
7406 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7407 }
7408 }
7409
7410 // Special handling of variable named 'main'.
7411 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7412 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7413 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7414
7415 // C++ [basic.start.main]p3
7416 // A program that declares a variable main at global scope is ill-formed.
7417 if (getLangOpts().CPlusPlus)
7418 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7419
7420 // In C, and external-linkage variable named main results in undefined
7421 // behavior.
7422 else if (NewVD->hasExternalFormalLinkage())
7423 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7424 }
7425
7426 if (D.isRedeclaration() && !Previous.empty()) {
7427 NamedDecl *Prev = Previous.getRepresentativeDecl();
7428 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7429 D.isFunctionDefinition());
7430 }
7431
7432 if (NewTemplate) {
7433 if (NewVD->isInvalidDecl())
7434 NewTemplate->setInvalidDecl();
7435 ActOnDocumentableDecl(NewTemplate);
7436 return NewTemplate;
7437 }
7438
7439 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7440 CompleteMemberSpecialization(NewVD, Previous);
7441
7442 return NewVD;
7443}
7444
7445/// Enum describing the %select options in diag::warn_decl_shadow.
7446enum ShadowedDeclKind {
7447 SDK_Local,
7448 SDK_Global,
7449 SDK_StaticMember,
7450 SDK_Field,
7451 SDK_Typedef,
7452 SDK_Using
7453};
7454
7455/// Determine what kind of declaration we're shadowing.
7456static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7457 const DeclContext *OldDC) {
7458 if (isa<TypeAliasDecl>(ShadowedDecl))
7459 return SDK_Using;
7460 else if (isa<TypedefDecl>(ShadowedDecl))
7461 return SDK_Typedef;
7462 else if (isa<RecordDecl>(OldDC))
7463 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7464
7465 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7466}
7467
7468/// Return the location of the capture if the given lambda captures the given
7469/// variable \p VD, or an invalid source location otherwise.
7470static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7471 const VarDecl *VD) {
7472 for (const Capture &Capture : LSI->Captures) {
7473 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7474 return Capture.getLocation();
7475 }
7476 return SourceLocation();
7477}
7478
7479static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7480 const LookupResult &R) {
7481 // Only diagnose if we're shadowing an unambiguous field or variable.
7482 if (R.getResultKind() != LookupResult::Found)
7483 return false;
7484
7485 // Return false if warning is ignored.
7486 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7487}
7488
7489/// Return the declaration shadowed by the given variable \p D, or null
7490/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7491NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7492 const LookupResult &R) {
7493 if (!shouldWarnIfShadowedDecl(Diags, R))
7494 return nullptr;
7495
7496 // Don't diagnose declarations at file scope.
7497 if (D->hasGlobalStorage())
7498 return nullptr;
7499
7500 NamedDecl *ShadowedDecl = R.getFoundDecl();
7501 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7502 ? ShadowedDecl
7503 : nullptr;
7504}
7505
7506/// Return the declaration shadowed by the given typedef \p D, or null
7507/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7508NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7509 const LookupResult &R) {
7510 // Don't warn if typedef declaration is part of a class
7511 if (D->getDeclContext()->isRecord())
7512 return nullptr;
7513
7514 if (!shouldWarnIfShadowedDecl(Diags, R))
7515 return nullptr;
7516
7517 NamedDecl *ShadowedDecl = R.getFoundDecl();
7518 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7519}
7520
7521/// Diagnose variable or built-in function shadowing. Implements
7522/// -Wshadow.
7523///
7524/// This method is called whenever a VarDecl is added to a "useful"
7525/// scope.
7526///
7527/// \param ShadowedDecl the declaration that is shadowed by the given variable
7528/// \param R the lookup of the name
7529///
7530void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7531 const LookupResult &R) {
7532 DeclContext *NewDC = D->getDeclContext();
7533
7534 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7535 // Fields are not shadowed by variables in C++ static methods.
7536 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7537 if (MD->isStatic())
7538 return;
7539
7540 // Fields shadowed by constructor parameters are a special case. Usually
7541 // the constructor initializes the field with the parameter.
7542 if (isa<CXXConstructorDecl>(NewDC))
7543 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7544 // Remember that this was shadowed so we can either warn about its
7545 // modification or its existence depending on warning settings.
7546 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7547 return;
7548 }
7549 }
7550
7551 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7552 if (shadowedVar->isExternC()) {
7553 // For shadowing external vars, make sure that we point to the global
7554 // declaration, not a locally scoped extern declaration.
7555 for (auto I : shadowedVar->redecls())
7556 if (I->isFileVarDecl()) {
7557 ShadowedDecl = I;
7558 break;
7559 }
7560 }
7561
7562 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7563
7564 unsigned WarningDiag = diag::warn_decl_shadow;
7565 SourceLocation CaptureLoc;
7566 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7567 isa<CXXMethodDecl>(NewDC)) {
7568 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7569 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7570 if (RD->getLambdaCaptureDefault() == LCD_None) {
7571 // Try to avoid warnings for lambdas with an explicit capture list.
7572 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7573 // Warn only when the lambda captures the shadowed decl explicitly.
7574 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7575 if (CaptureLoc.isInvalid())
7576 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7577 } else {
7578 // Remember that this was shadowed so we can avoid the warning if the
7579 // shadowed decl isn't captured and the warning settings allow it.
7580 cast<LambdaScopeInfo>(getCurFunction())
7581 ->ShadowingDecls.push_back(
7582 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7583 return;
7584 }
7585 }
7586
7587 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7588 // A variable can't shadow a local variable in an enclosing scope, if
7589 // they are separated by a non-capturing declaration context.
7590 for (DeclContext *ParentDC = NewDC;
7591 ParentDC && !ParentDC->Equals(OldDC);
7592 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7593 // Only block literals, captured statements, and lambda expressions
7594 // can capture; other scopes don't.
7595 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7596 !isLambdaCallOperator(ParentDC)) {
7597 return;
7598 }
7599 }
7600 }
7601 }
7602 }
7603
7604 // Only warn about certain kinds of shadowing for class members.
7605 if (NewDC && NewDC->isRecord()) {
7606 // In particular, don't warn about shadowing non-class members.
7607 if (!OldDC->isRecord())
7608 return;
7609
7610 // TODO: should we warn about static data members shadowing
7611 // static data members from base classes?
7612
7613 // TODO: don't diagnose for inaccessible shadowed members.
7614 // This is hard to do perfectly because we might friend the
7615 // shadowing context, but that's just a false negative.
7616 }
7617
7618
7619 DeclarationName Name = R.getLookupName();
7620
7621 // Emit warning and note.
7622 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7623 return;
7624 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7625 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7626 if (!CaptureLoc.isInvalid())
7627 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7628 << Name << /*explicitly*/ 1;
7629 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7630}
7631
7632/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7633/// when these variables are captured by the lambda.
7634void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7635 for (const auto &Shadow : LSI->ShadowingDecls) {
7636 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7637 // Try to avoid the warning when the shadowed decl isn't captured.
7638 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7639 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7640 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7641 ? diag::warn_decl_shadow_uncaptured_local
7642 : diag::warn_decl_shadow)
7643 << Shadow.VD->getDeclName()
7644 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7645 if (!CaptureLoc.isInvalid())
7646 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7647 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7648 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7649 }
7650}
7651
7652/// Check -Wshadow without the advantage of a previous lookup.
7653void Sema::CheckShadow(Scope *S, VarDecl *D) {
7654 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7655 return;
7656
7657 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7658 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7659 LookupName(R, S);
7660 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7661 CheckShadow(D, ShadowedDecl, R);
7662}
7663
7664/// Check if 'E', which is an expression that is about to be modified, refers
7665/// to a constructor parameter that shadows a field.
7666void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7667 // Quickly ignore expressions that can't be shadowing ctor parameters.
7668 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7669 return;
7670 E = E->IgnoreParenImpCasts();
7671 auto *DRE = dyn_cast<DeclRefExpr>(E);
7672 if (!DRE)
7673 return;
7674 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7675 auto I = ShadowingDecls.find(D);
7676 if (I == ShadowingDecls.end())
7677 return;
7678 const NamedDecl *ShadowedDecl = I->second;
7679 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7680 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7681 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7682 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7683
7684 // Avoid issuing multiple warnings about the same decl.
7685 ShadowingDecls.erase(I);
7686}
7687
7688/// Check for conflict between this global or extern "C" declaration and
7689/// previous global or extern "C" declarations. This is only used in C++.
7690template<typename T>
7691static bool checkGlobalOrExternCConflict(
7692 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7693 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7693, __PRETTY_FUNCTION__))
;
7694 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7695
7696 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7697 // The common case: this global doesn't conflict with any extern "C"
7698 // declaration.
7699 return false;
7700 }
7701
7702 if (Prev) {
7703 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7704 // Both the old and new declarations have C language linkage. This is a
7705 // redeclaration.
7706 Previous.clear();
7707 Previous.addDecl(Prev);
7708 return true;
7709 }
7710
7711 // This is a global, non-extern "C" declaration, and there is a previous
7712 // non-global extern "C" declaration. Diagnose if this is a variable
7713 // declaration.
7714 if (!isa<VarDecl>(ND))
7715 return false;
7716 } else {
7717 // The declaration is extern "C". Check for any declaration in the
7718 // translation unit which might conflict.
7719 if (IsGlobal) {
7720 // We have already performed the lookup into the translation unit.
7721 IsGlobal = false;
7722 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7723 I != E; ++I) {
7724 if (isa<VarDecl>(*I)) {
7725 Prev = *I;
7726 break;
7727 }
7728 }
7729 } else {
7730 DeclContext::lookup_result R =
7731 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7732 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7733 I != E; ++I) {
7734 if (isa<VarDecl>(*I)) {
7735 Prev = *I;
7736 break;
7737 }
7738 // FIXME: If we have any other entity with this name in global scope,
7739 // the declaration is ill-formed, but that is a defect: it breaks the
7740 // 'stat' hack, for instance. Only variables can have mangled name
7741 // clashes with extern "C" declarations, so only they deserve a
7742 // diagnostic.
7743 }
7744 }
7745
7746 if (!Prev)
7747 return false;
7748 }
7749
7750 // Use the first declaration's location to ensure we point at something which
7751 // is lexically inside an extern "C" linkage-spec.
7752 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7752, __PRETTY_FUNCTION__))
;
7753 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7754 Prev = FD->getFirstDecl();
7755 else
7756 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7757
7758 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7759 << IsGlobal << ND;
7760 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7761 << IsGlobal;
7762 return false;
7763}
7764
7765/// Apply special rules for handling extern "C" declarations. Returns \c true
7766/// if we have found that this is a redeclaration of some prior entity.
7767///
7768/// Per C++ [dcl.link]p6:
7769/// Two declarations [for a function or variable] with C language linkage
7770/// with the same name that appear in different scopes refer to the same
7771/// [entity]. An entity with C language linkage shall not be declared with
7772/// the same name as an entity in global scope.
7773template<typename T>
7774static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7775 LookupResult &Previous) {
7776 if (!S.getLangOpts().CPlusPlus) {
7777 // In C, when declaring a global variable, look for a corresponding 'extern'
7778 // variable declared in function scope. We don't need this in C++, because
7779 // we find local extern decls in the surrounding file-scope DeclContext.
7780 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7781 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7782 Previous.clear();
7783 Previous.addDecl(Prev);
7784 return true;
7785 }
7786 }
7787 return false;
7788 }
7789
7790 // A declaration in the translation unit can conflict with an extern "C"
7791 // declaration.
7792 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7793 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7794
7795 // An extern "C" declaration can conflict with a declaration in the
7796 // translation unit or can be a redeclaration of an extern "C" declaration
7797 // in another scope.
7798 if (isIncompleteDeclExternC(S,ND))
7799 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7800
7801 // Neither global nor extern "C": nothing to do.
7802 return false;
7803}
7804
7805void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7806 // If the decl is already known invalid, don't check it.
7807 if (NewVD->isInvalidDecl())
7808 return;
7809
7810 QualType T = NewVD->getType();
7811
7812 // Defer checking an 'auto' type until its initializer is attached.
7813 if (T->isUndeducedType())
7814 return;
7815
7816 if (NewVD->hasAttrs())
7817 CheckAlignasUnderalignment(NewVD);
7818
7819 if (T->isObjCObjectType()) {
7820 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7821 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7822 T = Context.getObjCObjectPointerType(T);
7823 NewVD->setType(T);
7824 }
7825
7826 // Emit an error if an address space was applied to decl with local storage.
7827 // This includes arrays of objects with address space qualifiers, but not
7828 // automatic variables that point to other address spaces.
7829 // ISO/IEC TR 18037 S5.1.2
7830 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7831 T.getAddressSpace() != LangAS::Default) {
7832 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7833 NewVD->setInvalidDecl();
7834 return;
7835 }
7836
7837 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7838 // scope.
7839 if (getLangOpts().OpenCLVersion == 120 &&
7840 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7841 NewVD->isStaticLocal()) {
7842 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7843 NewVD->setInvalidDecl();
7844 return;
7845 }
7846
7847 if (getLangOpts().OpenCL) {
7848 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7849 if (NewVD->hasAttr<BlocksAttr>()) {
7850 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7851 return;
7852 }
7853
7854 if (T->isBlockPointerType()) {
7855 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7856 // can't use 'extern' storage class.
7857 if (!T.isConstQualified()) {
7858 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7859 << 0 /*const*/;
7860 NewVD->setInvalidDecl();
7861 return;
7862 }
7863 if (NewVD->hasExternalStorage()) {
7864 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7865 NewVD->setInvalidDecl();
7866 return;
7867 }
7868 }
7869 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7870 // __constant address space.
7871 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7872 // variables inside a function can also be declared in the global
7873 // address space.
7874 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7875 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7876 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7877 NewVD->hasExternalStorage()) {
7878 if (!T->isSamplerT() &&
7879 !T->isDependentType() &&
7880 !(T.getAddressSpace() == LangAS::opencl_constant ||
7881 (T.getAddressSpace() == LangAS::opencl_global &&
7882 (getLangOpts().OpenCLVersion == 200 ||
7883 getLangOpts().OpenCLCPlusPlus)))) {
7884 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7885 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7886 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7887 << Scope << "global or constant";
7888 else
7889 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7890 << Scope << "constant";
7891 NewVD->setInvalidDecl();
7892 return;
7893 }
7894 } else {
7895 if (T.getAddressSpace() == LangAS::opencl_global) {
7896 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7897 << 1 /*is any function*/ << "global";
7898 NewVD->setInvalidDecl();
7899 return;
7900 }
7901 if (T.getAddressSpace() == LangAS::opencl_constant ||
7902 T.getAddressSpace() == LangAS::opencl_local) {
7903 FunctionDecl *FD = getCurFunctionDecl();
7904 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7905 // in functions.
7906 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7907 if (T.getAddressSpace() == LangAS::opencl_constant)
7908 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7909 << 0 /*non-kernel only*/ << "constant";
7910 else
7911 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7912 << 0 /*non-kernel only*/ << "local";
7913 NewVD->setInvalidDecl();
7914 return;
7915 }
7916 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7917 // in the outermost scope of a kernel function.
7918 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7919 if (!getCurScope()->isFunctionScope()) {
7920 if (T.getAddressSpace() == LangAS::opencl_constant)
7921 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7922 << "constant";
7923 else
7924 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7925 << "local";
7926 NewVD->setInvalidDecl();
7927 return;
7928 }
7929 }
7930 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7931 // If we are parsing a template we didn't deduce an addr
7932 // space yet.
7933 T.getAddressSpace() != LangAS::Default) {
7934 // Do not allow other address spaces on automatic variable.
7935 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7936 NewVD->setInvalidDecl();
7937 return;
7938 }
7939 }
7940 }
7941
7942 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7943 && !NewVD->hasAttr<BlocksAttr>()) {
7944 if (getLangOpts().getGC() != LangOptions::NonGC)
7945 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7946 else {
7947 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 7947, __PRETTY_FUNCTION__))
;
7948 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7949 }
7950 }
7951
7952 bool isVM = T->isVariablyModifiedType();
7953 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7954 NewVD->hasAttr<BlocksAttr>())
7955 setFunctionHasBranchProtectedScope();
7956
7957 if ((isVM && NewVD->hasLinkage()) ||
7958 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7959 bool SizeIsNegative;
7960 llvm::APSInt Oversized;
7961 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7962 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7963 QualType FixedT;
7964 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7965 FixedT = FixedTInfo->getType();
7966 else if (FixedTInfo) {
7967 // Type and type-as-written are canonically different. We need to fix up
7968 // both types separately.
7969 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7970 Oversized);
7971 }
7972 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7973 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7974 // FIXME: This won't give the correct result for
7975 // int a[10][n];
7976 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7977
7978 if (NewVD->isFileVarDecl())
7979 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7980 << SizeRange;
7981 else if (NewVD->isStaticLocal())
7982 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7983 << SizeRange;
7984 else
7985 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7986 << SizeRange;
7987 NewVD->setInvalidDecl();
7988 return;
7989 }
7990
7991 if (!FixedTInfo) {
7992 if (NewVD->isFileVarDecl())
7993 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7994 else
7995 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7996 NewVD->setInvalidDecl();
7997 return;
7998 }
7999
8000 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8001 NewVD->setType(FixedT);
8002 NewVD->setTypeSourceInfo(FixedTInfo);
8003 }
8004
8005 if (T->isVoidType()) {
8006 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8007 // of objects and functions.
8008 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8009 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8010 << T;
8011 NewVD->setInvalidDecl();
8012 return;
8013 }
8014 }
8015
8016 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8017 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8018 NewVD->setInvalidDecl();
8019 return;
8020 }
8021
8022 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8023 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8024 NewVD->setInvalidDecl();
8025 return;
8026 }
8027
8028 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8029 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8030 NewVD->setInvalidDecl();
8031 return;
8032 }
8033
8034 if (NewVD->isConstexpr() && !T->isDependentType() &&
8035 RequireLiteralType(NewVD->getLocation(), T,
8036 diag::err_constexpr_var_non_literal)) {
8037 NewVD->setInvalidDecl();
8038 return;
8039 }
8040}
8041
8042/// Perform semantic checking on a newly-created variable
8043/// declaration.
8044///
8045/// This routine performs all of the type-checking required for a
8046/// variable declaration once it has been built. It is used both to
8047/// check variables after they have been parsed and their declarators
8048/// have been translated into a declaration, and to check variables
8049/// that have been instantiated from a template.
8050///
8051/// Sets NewVD->isInvalidDecl() if an error was encountered.
8052///
8053/// Returns true if the variable declaration is a redeclaration.
8054bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8055 CheckVariableDeclarationType(NewVD);
8056
8057 // If the decl is already known invalid, don't check it.
8058 if (NewVD->isInvalidDecl())
8059 return false;
8060
8061 // If we did not find anything by this name, look for a non-visible
8062 // extern "C" declaration with the same name.
8063 if (Previous.empty() &&
8064 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8065 Previous.setShadowed();
8066
8067 if (!Previous.empty()) {
8068 MergeVarDecl(NewVD, Previous);
8069 return true;
8070 }
8071 return false;
8072}
8073
8074namespace {
8075struct FindOverriddenMethod {
8076 Sema *S;
8077 CXXMethodDecl *Method;
8078
8079 /// Member lookup function that determines whether a given C++
8080 /// method overrides a method in a base class, to be used with
8081 /// CXXRecordDecl::lookupInBases().
8082 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8083 RecordDecl *BaseRecord =
8084 Specifier->getType()->castAs<RecordType>()->getDecl();
8085
8086 DeclarationName Name = Method->getDeclName();
8087
8088 // FIXME: Do we care about other names here too?
8089 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8090 // We really want to find the base class destructor here.
8091 QualType T = S->Context.getTypeDeclType(BaseRecord);
8092 CanQualType CT = S->Context.getCanonicalType(T);
8093
8094 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8095 }
8096
8097 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8098 Path.Decls = Path.Decls.slice(1)) {
8099 NamedDecl *D = Path.Decls.front();
8100 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8101 if (MD->isVirtual() &&
8102 !S->IsOverload(
8103 Method, MD, /*UseMemberUsingDeclRules=*/false,
8104 /*ConsiderCudaAttrs=*/true,
8105 // C++2a [class.virtual]p2 does not consider requires clauses
8106 // when overriding.
8107 /*ConsiderRequiresClauses=*/false))
8108 return true;
8109 }
8110 }
8111
8112 return false;
8113 }
8114};
8115} // end anonymous namespace
8116
8117/// AddOverriddenMethods - See if a method overrides any in the base classes,
8118/// and if so, check that it's a valid override and remember it.
8119bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8120 // Look for methods in base classes that this method might override.
8121 CXXBasePaths Paths;
8122 FindOverriddenMethod FOM;
8123 FOM.Method = MD;
8124 FOM.S = this;
8125 bool AddedAny = false;
8126 if (DC->lookupInBases(FOM, Paths)) {
8127 for (auto *I : Paths.found_decls()) {
8128 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8129 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8130 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8131 !CheckOverridingFunctionAttributes(MD, OldMD) &&
8132 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8133 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8134 AddedAny = true;
8135 }
8136 }
8137 }
8138 }
8139
8140 return AddedAny;
8141}
8142
8143namespace {
8144 // Struct for holding all of the extra arguments needed by
8145 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8146 struct ActOnFDArgs {
8147 Scope *S;
8148 Declarator &D;
8149 MultiTemplateParamsArg TemplateParamLists;
8150 bool AddToScope;
8151 };
8152} // end anonymous namespace
8153
8154namespace {
8155
8156// Callback to only accept typo corrections that have a non-zero edit distance.
8157// Also only accept corrections that have the same parent decl.
8158class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8159 public:
8160 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8161 CXXRecordDecl *Parent)
8162 : Context(Context), OriginalFD(TypoFD),
8163 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8164
8165 bool ValidateCandidate(const TypoCorrection &candidate) override {
8166 if (candidate.getEditDistance() == 0)
8167 return false;
8168
8169 SmallVector<unsigned, 1> MismatchedParams;
8170 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8171 CDeclEnd = candidate.end();
8172 CDecl != CDeclEnd; ++CDecl) {
8173 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8174
8175 if (FD && !FD->hasBody() &&
8176 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8177 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8178 CXXRecordDecl *Parent = MD->getParent();
8179 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8180 return true;
8181 } else if (!ExpectedParent) {
8182 return true;
8183 }
8184 }
8185 }
8186
8187 return false;
8188 }
8189
8190 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8191 return std::make_unique<DifferentNameValidatorCCC>(*this);
8192 }
8193
8194 private:
8195 ASTContext &Context;
8196 FunctionDecl *OriginalFD;
8197 CXXRecordDecl *ExpectedParent;
8198};
8199
8200} // end anonymous namespace
8201
8202void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8203 TypoCorrectedFunctionDefinitions.insert(F);
8204}
8205
8206/// Generate diagnostics for an invalid function redeclaration.
8207///
8208/// This routine handles generating the diagnostic messages for an invalid
8209/// function redeclaration, including finding possible similar declarations
8210/// or performing typo correction if there are no previous declarations with
8211/// the same name.
8212///
8213/// Returns a NamedDecl iff typo correction was performed and substituting in
8214/// the new declaration name does not cause new errors.
8215static NamedDecl *DiagnoseInvalidRedeclaration(
8216 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8217 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8218 DeclarationName Name = NewFD->getDeclName();
8219 DeclContext *NewDC = NewFD->getDeclContext();
8220 SmallVector<unsigned, 1> MismatchedParams;
8221 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8222 TypoCorrection Correction;
8223 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8224 unsigned DiagMsg =
8225 IsLocalFriend ? diag::err_no_matching_local_friend :
8226 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8227 diag::err_member_decl_does_not_match;
8228 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8229 IsLocalFriend ? Sema::LookupLocalFriendName
8230 : Sema::LookupOrdinaryName,
8231 Sema::ForVisibleRedeclaration);
8232
8233 NewFD->setInvalidDecl();
8234 if (IsLocalFriend)
8235 SemaRef.LookupName(Prev, S);
8236 else
8237 SemaRef.LookupQualifiedName(Prev, NewDC);
8238 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8239, __PRETTY_FUNCTION__))
8239 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8239, __PRETTY_FUNCTION__))
;
8240 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8241 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8242 MD ? MD->getParent() : nullptr);
8243 if (!Prev.empty()) {
8244 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8245 Func != FuncEnd; ++Func) {
8246 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8247 if (FD &&
8248 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8249 // Add 1 to the index so that 0 can mean the mismatch didn't
8250 // involve a parameter
8251 unsigned ParamNum =
8252 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8253 NearMatches.push_back(std::make_pair(FD, ParamNum));
8254 }
8255 }
8256 // If the qualified name lookup yielded nothing, try typo correction
8257 } else if ((Correction = SemaRef.CorrectTypo(
8258 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8259 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8260 IsLocalFriend ? nullptr : NewDC))) {
8261 // Set up everything for the call to ActOnFunctionDeclarator
8262 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8263 ExtraArgs.D.getIdentifierLoc());
8264 Previous.clear();
8265 Previous.setLookupName(Correction.getCorrection());
8266 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8267 CDeclEnd = Correction.end();
8268 CDecl != CDeclEnd; ++CDecl) {
8269 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8270 if (FD && !FD->hasBody() &&
8271 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8272 Previous.addDecl(FD);
8273 }
8274 }
8275 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8276
8277 NamedDecl *Result;
8278 // Retry building the function declaration with the new previous
8279 // declarations, and with errors suppressed.
8280 {
8281 // Trap errors.
8282 Sema::SFINAETrap Trap(SemaRef);
8283
8284 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8285 // pieces need to verify the typo-corrected C++ declaration and hopefully
8286 // eliminate the need for the parameter pack ExtraArgs.
8287 Result = SemaRef.ActOnFunctionDeclarator(
8288 ExtraArgs.S, ExtraArgs.D,
8289 Correction.getCorrectionDecl()->getDeclContext(),
8290 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8291 ExtraArgs.AddToScope);
8292
8293 if (Trap.hasErrorOccurred())
8294 Result = nullptr;
8295 }
8296
8297 if (Result) {
8298 // Determine which correction we picked.
8299 Decl *Canonical = Result->getCanonicalDecl();
8300 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8301 I != E; ++I)
8302 if ((*I)->getCanonicalDecl() == Canonical)
8303 Correction.setCorrectionDecl(*I);
8304
8305 // Let Sema know about the correction.
8306 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8307 SemaRef.diagnoseTypo(
8308 Correction,
8309 SemaRef.PDiag(IsLocalFriend
8310 ? diag::err_no_matching_local_friend_suggest
8311 : diag::err_member_decl_does_not_match_suggest)
8312 << Name << NewDC << IsDefinition);
8313 return Result;
8314 }
8315
8316 // Pretend the typo correction never occurred
8317 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8318 ExtraArgs.D.getIdentifierLoc());
8319 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8320 Previous.clear();
8321 Previous.setLookupName(Name);
8322 }
8323
8324 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8325 << Name << NewDC << IsDefinition << NewFD->getLocation();
8326
8327 bool NewFDisConst = false;
8328 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8329 NewFDisConst = NewMD->isConst();
8330
8331 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8332 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8333 NearMatch != NearMatchEnd; ++NearMatch) {
8334 FunctionDecl *FD = NearMatch->first;
8335 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8336 bool FDisConst = MD && MD->isConst();
8337 bool IsMember = MD || !IsLocalFriend;
8338
8339 // FIXME: These notes are poorly worded for the local friend case.
8340 if (unsigned Idx = NearMatch->second) {
8341 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8342 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8343 if (Loc.isInvalid()) Loc = FD->getLocation();
8344 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8345 : diag::note_local_decl_close_param_match)
8346 << Idx << FDParam->getType()
8347 << NewFD->getParamDecl(Idx - 1)->getType();
8348 } else if (FDisConst != NewFDisConst) {
8349 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8350 << NewFDisConst << FD->getSourceRange().getEnd();
8351 } else
8352 SemaRef.Diag(FD->getLocation(),
8353 IsMember ? diag::note_member_def_close_match
8354 : diag::note_local_decl_close_match);
8355 }
8356 return nullptr;
8357}
8358
8359static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8360 switch (D.getDeclSpec().getStorageClassSpec()) {
8361 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8361)
;
8362 case DeclSpec::SCS_auto:
8363 case DeclSpec::SCS_register:
8364 case DeclSpec::SCS_mutable:
8365 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8366 diag::err_typecheck_sclass_func);
8367 D.getMutableDeclSpec().ClearStorageClassSpecs();
8368 D.setInvalidType();
8369 break;
8370 case DeclSpec::SCS_unspecified: break;
8371 case DeclSpec::SCS_extern:
8372 if (D.getDeclSpec().isExternInLinkageSpec())
8373 return SC_None;
8374 return SC_Extern;
8375 case DeclSpec::SCS_static: {
8376 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8377 // C99 6.7.1p5:
8378 // The declaration of an identifier for a function that has
8379 // block scope shall have no explicit storage-class specifier
8380 // other than extern
8381 // See also (C++ [dcl.stc]p4).
8382 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8383 diag::err_static_block_func);
8384 break;
8385 } else
8386 return SC_Static;
8387 }
8388 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8389 }
8390
8391 // No explicit storage class has already been returned
8392 return SC_None;
8393}
8394
8395static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8396 DeclContext *DC, QualType &R,
8397 TypeSourceInfo *TInfo,
8398 StorageClass SC,
8399 bool &IsVirtualOkay) {
8400 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8401 DeclarationName Name = NameInfo.getName();
8402
8403 FunctionDecl *NewFD = nullptr;
8404 bool isInline = D.getDeclSpec().isInlineSpecified();
8405
8406 if (!SemaRef.getLangOpts().CPlusPlus) {
8407 // Determine whether the function was written with a
8408 // prototype. This true when:
8409 // - there is a prototype in the declarator, or
8410 // - the type R of the function is some kind of typedef or other non-
8411 // attributed reference to a type name (which eventually refers to a
8412 // function type).
8413 bool HasPrototype =
8414 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8415 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8416
8417 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8418 R, TInfo, SC, isInline, HasPrototype,
8419 CSK_unspecified,
8420 /*TrailingRequiresClause=*/nullptr);
8421 if (D.isInvalidType())
8422 NewFD->setInvalidDecl();
8423
8424 return NewFD;
8425 }
8426
8427 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8428
8429 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8430 if (ConstexprKind == CSK_constinit) {
8431 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8432 diag::err_constexpr_wrong_decl_kind)
8433 << ConstexprKind;
8434 ConstexprKind = CSK_unspecified;
8435 D.getMutableDeclSpec().ClearConstexprSpec();
8436 }
8437 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8438
8439 // Check that the return type is not an abstract class type.
8440 // For record types, this is done by the AbstractClassUsageDiagnoser once
8441 // the class has been completely parsed.
8442 if (!DC->isRecord() &&
8443 SemaRef.RequireNonAbstractType(
8444 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8445 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8446 D.setInvalidType();
8447
8448 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8449 // This is a C++ constructor declaration.
8450 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8451, __PRETTY_FUNCTION__))
8451 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8451, __PRETTY_FUNCTION__))
;
8452
8453 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8454 return CXXConstructorDecl::Create(
8455 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8456 TInfo, ExplicitSpecifier, isInline,
8457 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8458 TrailingRequiresClause);
8459
8460 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8461 // This is a C++ destructor declaration.
8462 if (DC->isRecord()) {
8463 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8464 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8465 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8466 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8467 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8468 TrailingRequiresClause);
8469
8470 // If the destructor needs an implicit exception specification, set it
8471 // now. FIXME: It'd be nice to be able to create the right type to start
8472 // with, but the type needs to reference the destructor declaration.
8473 if (SemaRef.getLangOpts().CPlusPlus11)
8474 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8475
8476 IsVirtualOkay = true;
8477 return NewDD;
8478
8479 } else {
8480 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8481 D.setInvalidType();
8482
8483 // Create a FunctionDecl to satisfy the function definition parsing
8484 // code path.
8485 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8486 D.getIdentifierLoc(), Name, R, TInfo, SC,
8487 isInline,
8488 /*hasPrototype=*/true, ConstexprKind,
8489 TrailingRequiresClause);
8490 }
8491
8492 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8493 if (!DC->isRecord()) {
8494 SemaRef.Diag(D.getIdentifierLoc(),
8495 diag::err_conv_function_not_member);
8496 return nullptr;
8497 }
8498
8499 SemaRef.CheckConversionDeclarator(D, R, SC);
8500 if (D.isInvalidType())
8501 return nullptr;
8502
8503 IsVirtualOkay = true;
8504 return CXXConversionDecl::Create(
8505 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8506 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8507 TrailingRequiresClause);
8508
8509 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8510 if (TrailingRequiresClause)
8511 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8512 diag::err_trailing_requires_clause_on_deduction_guide)
8513 << TrailingRequiresClause->getSourceRange();
8514 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8515
8516 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8517 ExplicitSpecifier, NameInfo, R, TInfo,
8518 D.getEndLoc());
8519 } else if (DC->isRecord()) {
8520 // If the name of the function is the same as the name of the record,
8521 // then this must be an invalid constructor that has a return type.
8522 // (The parser checks for a return type and makes the declarator a
8523 // constructor if it has no return type).
8524 if (Name.getAsIdentifierInfo() &&
8525 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8526 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8527 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8528 << SourceRange(D.getIdentifierLoc());
8529 return nullptr;
8530 }
8531
8532 // This is a C++ method declaration.
8533 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8534 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8535 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8536 TrailingRequiresClause);
8537 IsVirtualOkay = !Ret->isStatic();
8538 return Ret;
8539 } else {
8540 bool isFriend =
8541 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8542 if (!isFriend && SemaRef.CurContext->isRecord())
8543 return nullptr;
8544
8545 // Determine whether the function was written with a
8546 // prototype. This true when:
8547 // - we're in C++ (where every function has a prototype),
8548 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8549 R, TInfo, SC, isInline, true /*HasPrototype*/,
8550 ConstexprKind, TrailingRequiresClause);
8551 }
8552}
8553
8554enum OpenCLParamType {
8555 ValidKernelParam,
8556 PtrPtrKernelParam,
8557 PtrKernelParam,
8558 InvalidAddrSpacePtrKernelParam,
8559 InvalidKernelParam,
8560 RecordKernelParam
8561};
8562
8563static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8564 // Size dependent types are just typedefs to normal integer types
8565 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8566 // integers other than by their names.
8567 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8568
8569 // Remove typedefs one by one until we reach a typedef
8570 // for a size dependent type.
8571 QualType DesugaredTy = Ty;
8572 do {
8573 ArrayRef<StringRef> Names(SizeTypeNames);
8574 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8575 if (Names.end() != Match)
8576 return true;
8577
8578 Ty = DesugaredTy;
8579 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8580 } while (DesugaredTy != Ty);
8581
8582 return false;
8583}
8584
8585static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8586 if (PT->isPointerType()) {
8587 QualType PointeeType = PT->getPointeeType();
8588 if (PointeeType->isPointerType())
8589 return PtrPtrKernelParam;
8590 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8591 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8592 PointeeType.getAddressSpace() == LangAS::Default)
8593 return InvalidAddrSpacePtrKernelParam;
8594 return PtrKernelParam;
8595 }
8596
8597 // OpenCL v1.2 s6.9.k:
8598 // Arguments to kernel functions in a program cannot be declared with the
8599 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8600 // uintptr_t or a struct and/or union that contain fields declared to be one
8601 // of these built-in scalar types.
8602 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8603 return InvalidKernelParam;
8604
8605 if (PT->isImageType())
8606 return PtrKernelParam;
8607
8608 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8609 return InvalidKernelParam;
8610
8611 // OpenCL extension spec v1.2 s9.5:
8612 // This extension adds support for half scalar and vector types as built-in
8613 // types that can be used for arithmetic operations, conversions etc.
8614 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8615 return InvalidKernelParam;
8616
8617 if (PT->isRecordType())
8618 return RecordKernelParam;
8619
8620 // Look into an array argument to check if it has a forbidden type.
8621 if (PT->isArrayType()) {
8622 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8623 // Call ourself to check an underlying type of an array. Since the
8624 // getPointeeOrArrayElementType returns an innermost type which is not an
8625 // array, this recursive call only happens once.
8626 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8627 }
8628
8629 return ValidKernelParam;
8630}
8631
8632static void checkIsValidOpenCLKernelParameter(
8633 Sema &S,
8634 Declarator &D,
8635 ParmVarDecl *Param,
8636 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8637 QualType PT = Param->getType();
8638
8639 // Cache the valid types we encounter to avoid rechecking structs that are
8640 // used again
8641 if (ValidTypes.count(PT.getTypePtr()))
8642 return;
8643
8644 switch (getOpenCLKernelParameterType(S, PT)) {
8645 case PtrPtrKernelParam:
8646 // OpenCL v1.2 s6.9.a:
8647 // A kernel function argument cannot be declared as a
8648 // pointer to a pointer type.
8649 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8650 D.setInvalidType();
8651 return;
8652
8653 case InvalidAddrSpacePtrKernelParam:
8654 // OpenCL v1.0 s6.5:
8655 // __kernel function arguments declared to be a pointer of a type can point
8656 // to one of the following address spaces only : __global, __local or
8657 // __constant.
8658 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8659 D.setInvalidType();
8660 return;
8661
8662 // OpenCL v1.2 s6.9.k:
8663 // Arguments to kernel functions in a program cannot be declared with the
8664 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8665 // uintptr_t or a struct and/or union that contain fields declared to be
8666 // one of these built-in scalar types.
8667
8668 case InvalidKernelParam:
8669 // OpenCL v1.2 s6.8 n:
8670 // A kernel function argument cannot be declared
8671 // of event_t type.
8672 // Do not diagnose half type since it is diagnosed as invalid argument
8673 // type for any function elsewhere.
8674 if (!PT->isHalfType()) {
8675 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8676
8677 // Explain what typedefs are involved.
8678 const TypedefType *Typedef = nullptr;
8679 while ((Typedef = PT->getAs<TypedefType>())) {
8680 SourceLocation Loc = Typedef->getDecl()->getLocation();
8681 // SourceLocation may be invalid for a built-in type.
8682 if (Loc.isValid())
8683 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8684 PT = Typedef->desugar();
8685 }
8686 }
8687
8688 D.setInvalidType();
8689 return;
8690
8691 case PtrKernelParam:
8692 case ValidKernelParam:
8693 ValidTypes.insert(PT.getTypePtr());
8694 return;
8695
8696 case RecordKernelParam:
8697 break;
8698 }
8699
8700 // Track nested structs we will inspect
8701 SmallVector<const Decl *, 4> VisitStack;
8702
8703 // Track where we are in the nested structs. Items will migrate from
8704 // VisitStack to HistoryStack as we do the DFS for bad field.
8705 SmallVector<const FieldDecl *, 4> HistoryStack;
8706 HistoryStack.push_back(nullptr);
8707
8708 // At this point we already handled everything except of a RecordType or
8709 // an ArrayType of a RecordType.
8710 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8710, __PRETTY_FUNCTION__))
;
8711 const RecordType *RecTy =
8712 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8713 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8714
8715 VisitStack.push_back(RecTy->getDecl());
8716 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8716, __PRETTY_FUNCTION__))
;
8717
8718 do {
8719 const Decl *Next = VisitStack.pop_back_val();
8720 if (!Next) {
8721 assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail
("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8721, __PRETTY_FUNCTION__))
;
8722 // Found a marker, we have gone up a level
8723 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8724 ValidTypes.insert(Hist->getType().getTypePtr());
8725
8726 continue;
8727 }
8728
8729 // Adds everything except the original parameter declaration (which is not a
8730 // field itself) to the history stack.
8731 const RecordDecl *RD;
8732 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8733 HistoryStack.push_back(Field);
8734
8735 QualType FieldTy = Field->getType();
8736 // Other field types (known to be valid or invalid) are handled while we
8737 // walk around RecordDecl::fields().
8738 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8739, __PRETTY_FUNCTION__))
8739 "Unexpected type.")(((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
"Unexpected type.") ? static_cast<void> (0) : __assert_fail
("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8739, __PRETTY_FUNCTION__))
;
8740 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8741
8742 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8743 } else {
8744 RD = cast<RecordDecl>(Next);
8745 }
8746
8747 // Add a null marker so we know when we've gone back up a level
8748 VisitStack.push_back(nullptr);
8749
8750 for (const auto *FD : RD->fields()) {
8751 QualType QT = FD->getType();
8752
8753 if (ValidTypes.count(QT.getTypePtr()))
8754 continue;
8755
8756 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8757 if (ParamType == ValidKernelParam)
8758 continue;
8759
8760 if (ParamType == RecordKernelParam) {
8761 VisitStack.push_back(FD);
8762 continue;
8763 }
8764
8765 // OpenCL v1.2 s6.9.p:
8766 // Arguments to kernel functions that are declared to be a struct or union
8767 // do not allow OpenCL objects to be passed as elements of the struct or
8768 // union.
8769 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8770 ParamType == InvalidAddrSpacePtrKernelParam) {
8771 S.Diag(Param->getLocation(),
8772 diag::err_record_with_pointers_kernel_param)
8773 << PT->isUnionType()
8774 << PT;
8775 } else {
8776 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8777 }
8778
8779 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8780 << OrigRecDecl->getDeclName();
8781
8782 // We have an error, now let's go back up through history and show where
8783 // the offending field came from
8784 for (ArrayRef<const FieldDecl *>::const_iterator
8785 I = HistoryStack.begin() + 1,
8786 E = HistoryStack.end();
8787 I != E; ++I) {
8788 const FieldDecl *OuterField = *I;
8789 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8790 << OuterField->getType();
8791 }
8792
8793 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8794 << QT->isPointerType()
8795 << QT;
8796 D.setInvalidType();
8797 return;
8798 }
8799 } while (!VisitStack.empty());
8800}
8801
8802/// Find the DeclContext in which a tag is implicitly declared if we see an
8803/// elaborated type specifier in the specified context, and lookup finds
8804/// nothing.
8805static DeclContext *getTagInjectionContext(DeclContext *DC) {
8806 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8807 DC = DC->getParent();
8808 return DC;
8809}
8810
8811/// Find the Scope in which a tag is implicitly declared if we see an
8812/// elaborated type specifier in the specified context, and lookup finds
8813/// nothing.
8814static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8815 while (S->isClassScope() ||
8816 (LangOpts.CPlusPlus &&
8817 S->isFunctionPrototypeScope()) ||
8818 ((S->getFlags() & Scope::DeclScope) == 0) ||
8819 (S->getEntity() && S->getEntity()->isTransparentContext()))
8820 S = S->getParent();
8821 return S;
8822}
8823
8824NamedDecl*
8825Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8826 TypeSourceInfo *TInfo, LookupResult &Previous,
8827 MultiTemplateParamsArg TemplateParamListsRef,
8828 bool &AddToScope) {
8829 QualType R = TInfo->getType();
8830
8831 assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("R->isFunctionType()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 8831, __PRETTY_FUNCTION__))
;
8832 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8833 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8834
8835 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8836 for (TemplateParameterList *TPL : TemplateParamListsRef)
8837 TemplateParamLists.push_back(TPL);
8838 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8839 if (!TemplateParamLists.empty() &&
8840 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8841 TemplateParamLists.back() = Invented;
8842 else
8843 TemplateParamLists.push_back(Invented);
8844 }
8845
8846 // TODO: consider using NameInfo for diagnostic.
8847 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8848 DeclarationName Name = NameInfo.getName();
8849 StorageClass SC = getFunctionStorageClass(*this, D);
8850
8851 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8852 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8853 diag::err_invalid_thread)
8854 << DeclSpec::getSpecifierName(TSCS);
8855
8856 if (D.isFirstDeclarationOfMember())
8857 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8858 D.getIdentifierLoc());
8859
8860 bool isFriend = false;
8861 FunctionTemplateDecl *FunctionTemplate = nullptr;
8862 bool isMemberSpecialization = false;
8863 bool isFunctionTemplateSpecialization = false;
8864
8865 bool isDependentClassScopeExplicitSpecialization = false;
8866 bool HasExplicitTemplateArgs = false;
8867 TemplateArgumentListInfo TemplateArgs;
8868
8869 bool isVirtualOkay = false;
8870
8871 DeclContext *OriginalDC = DC;
8872 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8873
8874 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8875 isVirtualOkay);
8876 if (!NewFD) return nullptr;
8877
8878 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8879 NewFD->setTopLevelDeclInObjCContainer();
8880
8881 // Set the lexical context. If this is a function-scope declaration, or has a
8882 // C++ scope specifier, or is the object of a friend declaration, the lexical
8883 // context will be different from the semantic context.
8884 NewFD->setLexicalDeclContext(CurContext);
8885
8886 if (IsLocalExternDecl)
8887 NewFD->setLocalExternDecl();
8888
8889 if (getLangOpts().CPlusPlus) {
8890 bool isInline = D.getDeclSpec().isInlineSpecified();
8891 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8892 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8893 isFriend = D.getDeclSpec().isFriendSpecified();
8894 if (isFriend && !isInline && D.isFunctionDefinition()) {
8895 // C++ [class.friend]p5
8896 // A function can be defined in a friend declaration of a
8897 // class . . . . Such a function is implicitly inline.
8898 NewFD->setImplicitlyInline();
8899 }
8900
8901 // If this is a method defined in an __interface, and is not a constructor
8902 // or an overloaded operator, then set the pure flag (isVirtual will already
8903 // return true).
8904 if (const CXXRecordDecl *Parent =
8905 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8906 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8907 NewFD->setPure(true);
8908
8909 // C++ [class.union]p2
8910 // A union can have member functions, but not virtual functions.
8911 if (isVirtual && Parent->isUnion())
8912 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8913 }
8914
8915 SetNestedNameSpecifier(*this, NewFD, D);
8916 isMemberSpecialization = false;
8917 isFunctionTemplateSpecialization = false;
8918 if (D.isInvalidType())
8919 NewFD->setInvalidDecl();
8920
8921 // Match up the template parameter lists with the scope specifier, then
8922 // determine whether we have a template or a template specialization.
8923 bool Invalid = false;
8924 TemplateParameterList *TemplateParams =
8925 MatchTemplateParametersToScopeSpecifier(
8926 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8927 D.getCXXScopeSpec(),
8928 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8929 ? D.getName().TemplateId
8930 : nullptr,
8931 TemplateParamLists, isFriend, isMemberSpecialization,
8932 Invalid);
8933 if (TemplateParams) {
8934 // Check that we can declare a template here.
8935 if (CheckTemplateDeclScope(S, TemplateParams))
8936 NewFD->setInvalidDecl();
8937
8938 if (TemplateParams->size() > 0) {
8939 // This is a function template
8940
8941 // A destructor cannot be a template.
8942 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8943 Diag(NewFD->getLocation(), diag::err_destructor_template);
8944 NewFD->setInvalidDecl();
8945 }
8946
8947 // If we're adding a template to a dependent context, we may need to
8948 // rebuilding some of the types used within the template parameter list,
8949 // now that we know what the current instantiation is.
8950 if (DC->isDependentContext()) {
8951 ContextRAII SavedContext(*this, DC);
8952 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8953 Invalid = true;
8954 }
8955
8956 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8957 NewFD->getLocation(),
8958 Name, TemplateParams,
8959 NewFD);
8960 FunctionTemplate->setLexicalDeclContext(CurContext);
8961 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8962
8963 // For source fidelity, store the other template param lists.
8964 if (TemplateParamLists.size() > 1) {
8965 NewFD->setTemplateParameterListsInfo(Context,
8966 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8967 .drop_back(1));
8968 }
8969 } else {
8970 // This is a function template specialization.
8971 isFunctionTemplateSpecialization = true;
8972 // For source fidelity, store all the template param lists.
8973 if (TemplateParamLists.size() > 0)
8974 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8975
8976 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8977 if (isFriend) {
8978 // We want to remove the "template<>", found here.
8979 SourceRange RemoveRange = TemplateParams->getSourceRange();
8980
8981 // If we remove the template<> and the name is not a
8982 // template-id, we're actually silently creating a problem:
8983 // the friend declaration will refer to an untemplated decl,
8984 // and clearly the user wants a template specialization. So
8985 // we need to insert '<>' after the name.
8986 SourceLocation InsertLoc;
8987 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8988 InsertLoc = D.getName().getSourceRange().getEnd();
8989 InsertLoc = getLocForEndOfToken(InsertLoc);
8990 }
8991
8992 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8993 << Name << RemoveRange
8994 << FixItHint::CreateRemoval(RemoveRange)
8995 << FixItHint::CreateInsertion(InsertLoc, "<>");
8996 }
8997 }
8998 } else {
8999 // Check that we can declare a template here.
9000 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9001 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9002 NewFD->setInvalidDecl();
9003
9004 // All template param lists were matched against the scope specifier:
9005 // this is NOT (an explicit specialization of) a template.
9006 if (TemplateParamLists.size() > 0)
9007 // For source fidelity, store all the template param lists.
9008 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9009 }
9010
9011 if (Invalid) {
9012 NewFD->setInvalidDecl();
9013 if (FunctionTemplate)
9014 FunctionTemplate->setInvalidDecl();
9015 }
9016
9017 // C++ [dcl.fct.spec]p5:
9018 // The virtual specifier shall only be used in declarations of
9019 // nonstatic class member functions that appear within a
9020 // member-specification of a class declaration; see 10.3.
9021 //
9022 if (isVirtual && !NewFD->isInvalidDecl()) {
9023 if (!isVirtualOkay) {
9024 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9025 diag::err_virtual_non_function);
9026 } else if (!CurContext->isRecord()) {
9027 // 'virtual' was specified outside of the class.
9028 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9029 diag::err_virtual_out_of_class)
9030 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9031 } else if (NewFD->getDescribedFunctionTemplate()) {
9032 // C++ [temp.mem]p3:
9033 // A member function template shall not be virtual.
9034 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9035 diag::err_virtual_member_function_template)
9036 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9037 } else {
9038 // Okay: Add virtual to the method.
9039 NewFD->setVirtualAsWritten(true);
9040 }
9041
9042 if (getLangOpts().CPlusPlus14 &&
9043 NewFD->getReturnType()->isUndeducedType())
9044 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9045 }
9046
9047 if (getLangOpts().CPlusPlus14 &&
9048 (NewFD->isDependentContext() ||
9049 (isFriend && CurContext->isDependentContext())) &&
9050 NewFD->getReturnType()->isUndeducedType()) {
9051 // If the function template is referenced directly (for instance, as a
9052 // member of the current instantiation), pretend it has a dependent type.
9053 // This is not really justified by the standard, but is the only sane
9054 // thing to do.
9055 // FIXME: For a friend function, we have not marked the function as being
9056 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9057 const FunctionProtoType *FPT =
9058 NewFD->getType()->castAs<FunctionProtoType>();
9059 QualType Result =
9060 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9061 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9062 FPT->getExtProtoInfo()));
9063 }
9064
9065 // C++ [dcl.fct.spec]p3:
9066 // The inline specifier shall not appear on a block scope function
9067 // declaration.
9068 if (isInline && !NewFD->isInvalidDecl()) {
9069 if (CurContext->isFunctionOrMethod()) {
9070 // 'inline' is not allowed on block scope function declaration.
9071 Diag(D.getDeclSpec().getInlineSpecLoc(),
9072 diag::err_inline_declaration_block_scope) << Name
9073 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9074 }
9075 }
9076
9077 // C++ [dcl.fct.spec]p6:
9078 // The explicit specifier shall be used only in the declaration of a
9079 // constructor or conversion function within its class definition;
9080 // see 12.3.1 and 12.3.2.
9081 if (hasExplicit && !NewFD->isInvalidDecl() &&
9082 !isa<CXXDeductionGuideDecl>(NewFD)) {
9083 if (!CurContext->isRecord()) {
9084 // 'explicit' was specified outside of the class.
9085 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9086 diag::err_explicit_out_of_class)
9087 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9088 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9089 !isa<CXXConversionDecl>(NewFD)) {
9090 // 'explicit' was specified on a function that wasn't a constructor
9091 // or conversion function.
9092 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9093 diag::err_explicit_non_ctor_or_conv_function)
9094 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9095 }
9096 }
9097
9098 if (ConstexprSpecKind ConstexprKind =
9099 D.getDeclSpec().getConstexprSpecifier()) {
9100 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9101 // are implicitly inline.
9102 NewFD->setImplicitlyInline();
9103
9104 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9105 // be either constructors or to return a literal type. Therefore,
9106 // destructors cannot be declared constexpr.
9107 if (isa<CXXDestructorDecl>(NewFD) &&
9108 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9109 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9110 << ConstexprKind;
9111 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9112 }
9113 // C++20 [dcl.constexpr]p2: An allocation function, or a
9114 // deallocation function shall not be declared with the consteval
9115 // specifier.
9116 if (ConstexprKind == CSK_consteval &&
9117 (NewFD->getOverloadedOperator() == OO_New ||
9118 NewFD->getOverloadedOperator() == OO_Array_New ||
9119 NewFD->getOverloadedOperator() == OO_Delete ||
9120 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9121 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9122 diag::err_invalid_consteval_decl_kind)
9123 << NewFD;
9124 NewFD->setConstexprKind(CSK_constexpr);
9125 }
9126 }
9127
9128 // If __module_private__ was specified, mark the function accordingly.
9129 if (D.getDeclSpec().isModulePrivateSpecified()) {
9130 if (isFunctionTemplateSpecialization) {
9131 SourceLocation ModulePrivateLoc
9132 = D.getDeclSpec().getModulePrivateSpecLoc();
9133 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9134 << 0
9135 << FixItHint::CreateRemoval(ModulePrivateLoc);
9136 } else {
9137 NewFD->setModulePrivate();
9138 if (FunctionTemplate)
9139 FunctionTemplate->setModulePrivate();
9140 }
9141 }
9142
9143 if (isFriend) {
9144 if (FunctionTemplate) {
9145 FunctionTemplate->setObjectOfFriendDecl();
9146 FunctionTemplate->setAccess(AS_public);
9147 }
9148 NewFD->setObjectOfFriendDecl();
9149 NewFD->setAccess(AS_public);
9150 }
9151
9152 // If a function is defined as defaulted or deleted, mark it as such now.
9153 // We'll do the relevant checks on defaulted / deleted functions later.
9154 switch (D.getFunctionDefinitionKind()) {
9155 case FDK_Declaration:
9156 case FDK_Definition:
9157 break;
9158
9159 case FDK_Defaulted:
9160 NewFD->setDefaulted();
9161 break;
9162
9163 case FDK_Deleted:
9164 NewFD->setDeletedAsWritten();
9165 break;
9166 }
9167
9168 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9169 D.isFunctionDefinition()) {
9170 // C++ [class.mfct]p2:
9171 // A member function may be defined (8.4) in its class definition, in
9172 // which case it is an inline member function (7.1.2)
9173 NewFD->setImplicitlyInline();
9174 }
9175
9176 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9177 !CurContext->isRecord()) {
9178 // C++ [class.static]p1:
9179 // A data or function member of a class may be declared static
9180 // in a class definition, in which case it is a static member of
9181 // the class.
9182
9183 // Complain about the 'static' specifier if it's on an out-of-line
9184 // member function definition.
9185
9186 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9187 // member function template declaration and class member template
9188 // declaration (MSVC versions before 2015), warn about this.
9189 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9190 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9191 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9192 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9193 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9194 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9195 }
9196
9197 // C++11 [except.spec]p15:
9198 // A deallocation function with no exception-specification is treated
9199 // as if it were specified with noexcept(true).
9200 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9201 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9202 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9203 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9204 NewFD->setType(Context.getFunctionType(
9205 FPT->getReturnType(), FPT->getParamTypes(),
9206 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9207 }
9208
9209 // Filter out previous declarations that don't match the scope.
9210 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9211 D.getCXXScopeSpec().isNotEmpty() ||
9212 isMemberSpecialization ||
9213 isFunctionTemplateSpecialization);
9214
9215 // Handle GNU asm-label extension (encoded as an attribute).
9216 if (Expr *E = (Expr*) D.getAsmLabel()) {
9217 // The parser guarantees this is a string.
9218 StringLiteral *SE = cast<StringLiteral>(E);
9219 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9220 /*IsLiteralLabel=*/true,
9221 SE->getStrTokenLoc(0)));
9222 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9223 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9224 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9225 if (I != ExtnameUndeclaredIdentifiers.end()) {
9226 if (isDeclExternC(NewFD)) {
9227 NewFD->addAttr(I->second);
9228 ExtnameUndeclaredIdentifiers.erase(I);
9229 } else
9230 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9231 << /*Variable*/0 << NewFD;
9232 }
9233 }
9234
9235 // Copy the parameter declarations from the declarator D to the function
9236 // declaration NewFD, if they are available. First scavenge them into Params.
9237 SmallVector<ParmVarDecl*, 16> Params;
9238 unsigned FTIIdx;
9239 if (D.isFunctionDeclarator(FTIIdx)) {
9240 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9241
9242 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9243 // function that takes no arguments, not a function that takes a
9244 // single void argument.
9245 // We let through "const void" here because Sema::GetTypeForDeclarator
9246 // already checks for that case.
9247 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9248 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9249 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9250 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9250, __PRETTY_FUNCTION__))
;
9251 Param->setDeclContext(NewFD);
9252 Params.push_back(Param);
9253
9254 if (Param->isInvalidDecl())
9255 NewFD->setInvalidDecl();
9256 }
9257 }
9258
9259 if (!getLangOpts().CPlusPlus) {
9260 // In C, find all the tag declarations from the prototype and move them
9261 // into the function DeclContext. Remove them from the surrounding tag
9262 // injection context of the function, which is typically but not always
9263 // the TU.
9264 DeclContext *PrototypeTagContext =
9265 getTagInjectionContext(NewFD->getLexicalDeclContext());
9266 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9267 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9268
9269 // We don't want to reparent enumerators. Look at their parent enum
9270 // instead.
9271 if (!TD) {
9272 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9273 TD = cast<EnumDecl>(ECD->getDeclContext());
9274 }
9275 if (!TD)
9276 continue;
9277 DeclContext *TagDC = TD->getLexicalDeclContext();
9278 if (!TagDC->containsDecl(TD))
9279 continue;
9280 TagDC->removeDecl(TD);
9281 TD->setDeclContext(NewFD);
9282 NewFD->addDecl(TD);
9283
9284 // Preserve the lexical DeclContext if it is not the surrounding tag
9285 // injection context of the FD. In this example, the semantic context of
9286 // E will be f and the lexical context will be S, while both the
9287 // semantic and lexical contexts of S will be f:
9288 // void f(struct S { enum E { a } f; } s);
9289 if (TagDC != PrototypeTagContext)
9290 TD->setLexicalDeclContext(TagDC);
9291 }
9292 }
9293 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9294 // When we're declaring a function with a typedef, typeof, etc as in the
9295 // following example, we'll need to synthesize (unnamed)
9296 // parameters for use in the declaration.
9297 //
9298 // @code
9299 // typedef void fn(int);
9300 // fn f;
9301 // @endcode
9302
9303 // Synthesize a parameter for each argument type.
9304 for (const auto &AI : FT->param_types()) {
9305 ParmVarDecl *Param =
9306 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9307 Param->setScopeInfo(0, Params.size());
9308 Params.push_back(Param);
9309 }
9310 } else {
9311 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9312, __PRETTY_FUNCTION__))
9312 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9312, __PRETTY_FUNCTION__))
;
9313 }
9314
9315 // Finally, we know we have the right number of parameters, install them.
9316 NewFD->setParams(Params);
9317
9318 if (D.getDeclSpec().isNoreturnSpecified())
9319 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9320 D.getDeclSpec().getNoreturnSpecLoc(),
9321 AttributeCommonInfo::AS_Keyword));
9322
9323 // Functions returning a variably modified type violate C99 6.7.5.2p2
9324 // because all functions have linkage.
9325 if (!NewFD->isInvalidDecl() &&
9326 NewFD->getReturnType()->isVariablyModifiedType()) {
9327 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9328 NewFD->setInvalidDecl();
9329 }
9330
9331 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9332 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9333 !NewFD->hasAttr<SectionAttr>())
9334 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9335 Context, PragmaClangTextSection.SectionName,
9336 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9337
9338 // Apply an implicit SectionAttr if #pragma code_seg is active.
9339 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9340 !NewFD->hasAttr<SectionAttr>()) {
9341 NewFD->addAttr(SectionAttr::CreateImplicit(
9342 Context, CodeSegStack.CurrentValue->getString(),
9343 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9344 SectionAttr::Declspec_allocate));
9345 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9346 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9347 ASTContext::PSF_Read,
9348 NewFD))
9349 NewFD->dropAttr<SectionAttr>();
9350 }
9351
9352 // Apply an implicit CodeSegAttr from class declspec or
9353 // apply an implicit SectionAttr from #pragma code_seg if active.
9354 if (!NewFD->hasAttr<CodeSegAttr>()) {
9355 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9356 D.isFunctionDefinition())) {
9357 NewFD->addAttr(SAttr);
9358 }
9359 }
9360
9361 // Handle attributes.
9362 ProcessDeclAttributes(S, NewFD, D);
9363
9364 if (getLangOpts().OpenCL) {
9365 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9366 // type declaration will generate a compilation error.
9367 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9368 if (AddressSpace != LangAS::Default) {
9369 Diag(NewFD->getLocation(),
9370 diag::err_opencl_return_value_with_address_space);
9371 NewFD->setInvalidDecl();
9372 }
9373 }
9374
9375 if (!getLangOpts().CPlusPlus) {
9376 // Perform semantic checking on the function declaration.
9377 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9378 CheckMain(NewFD, D.getDeclSpec());
9379
9380 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9381 CheckMSVCRTEntryPoint(NewFD);
9382
9383 if (!NewFD->isInvalidDecl())
9384 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9385 isMemberSpecialization));
9386 else if (!Previous.empty())
9387 // Recover gracefully from an invalid redeclaration.
9388 D.setRedeclaration(true);
9389 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9391, __PRETTY_FUNCTION__))
9390 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9391, __PRETTY_FUNCTION__))
9391 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9391, __PRETTY_FUNCTION__))
;
9392
9393 // Diagnose no-prototype function declarations with calling conventions that
9394 // don't support variadic calls. Only do this in C and do it after merging
9395 // possibly prototyped redeclarations.
9396 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9397 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9398 CallingConv CC = FT->getExtInfo().getCC();
9399 if (!supportsVariadicCall(CC)) {
9400 // Windows system headers sometimes accidentally use stdcall without
9401 // (void) parameters, so we relax this to a warning.
9402 int DiagID =
9403 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9404 Diag(NewFD->getLocation(), DiagID)
9405 << FunctionType::getNameForCallConv(CC);
9406 }
9407 }
9408
9409 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9410 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9411 checkNonTrivialCUnion(NewFD->getReturnType(),
9412 NewFD->getReturnTypeSourceRange().getBegin(),
9413 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9414 } else {
9415 // C++11 [replacement.functions]p3:
9416 // The program's definitions shall not be specified as inline.
9417 //
9418 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9419 //
9420 // Suppress the diagnostic if the function is __attribute__((used)), since
9421 // that forces an external definition to be emitted.
9422 if (D.getDeclSpec().isInlineSpecified() &&
9423 NewFD->isReplaceableGlobalAllocationFunction() &&
9424 !NewFD->hasAttr<UsedAttr>())
9425 Diag(D.getDeclSpec().getInlineSpecLoc(),
9426 diag::ext_operator_new_delete_declared_inline)
9427 << NewFD->getDeclName();
9428
9429 // If the declarator is a template-id, translate the parser's template
9430 // argument list into our AST format.
9431 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9432 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9433 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9434 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9435 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9436 TemplateId->NumArgs);
9437 translateTemplateArguments(TemplateArgsPtr,
9438 TemplateArgs);
9439
9440 HasExplicitTemplateArgs = true;
9441
9442 if (NewFD->isInvalidDecl()) {
9443 HasExplicitTemplateArgs = false;
9444 } else if (FunctionTemplate) {
9445 // Function template with explicit template arguments.
9446 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9447 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9448
9449 HasExplicitTemplateArgs = false;
9450 } else {
9451 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9453, __PRETTY_FUNCTION__))
9452 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9453, __PRETTY_FUNCTION__))
9453 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9453, __PRETTY_FUNCTION__))
;
9454 // "friend void foo<>(int);" is an implicit specialization decl.
9455 isFunctionTemplateSpecialization = true;
9456 }
9457 } else if (isFriend && isFunctionTemplateSpecialization) {
9458 // This combination is only possible in a recovery case; the user
9459 // wrote something like:
9460 // template <> friend void foo(int);
9461 // which we're recovering from as if the user had written:
9462 // friend void foo<>(int);
9463 // Go ahead and fake up a template id.
9464 HasExplicitTemplateArgs = true;
9465 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9466 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9467 }
9468
9469 // We do not add HD attributes to specializations here because
9470 // they may have different constexpr-ness compared to their
9471 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9472 // may end up with different effective targets. Instead, a
9473 // specialization inherits its target attributes from its template
9474 // in the CheckFunctionTemplateSpecialization() call below.
9475 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9476 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9477
9478 // If it's a friend (and only if it's a friend), it's possible
9479 // that either the specialized function type or the specialized
9480 // template is dependent, and therefore matching will fail. In
9481 // this case, don't check the specialization yet.
9482 bool InstantiationDependent = false;
9483 if (isFunctionTemplateSpecialization && isFriend &&
9484 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9485 TemplateSpecializationType::anyDependentTemplateArguments(
9486 TemplateArgs,
9487 InstantiationDependent))) {
9488 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9489, __PRETTY_FUNCTION__))
9489 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9489, __PRETTY_FUNCTION__))
;
9490 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9491 Previous))
9492 NewFD->setInvalidDecl();
9493 } else if (isFunctionTemplateSpecialization) {
9494 if (CurContext->isDependentContext() && CurContext->isRecord()
9495 && !isFriend) {
9496 isDependentClassScopeExplicitSpecialization = true;
9497 } else if (!NewFD->isInvalidDecl() &&
9498 CheckFunctionTemplateSpecialization(
9499 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9500 Previous))
9501 NewFD->setInvalidDecl();
9502
9503 // C++ [dcl.stc]p1:
9504 // A storage-class-specifier shall not be specified in an explicit
9505 // specialization (14.7.3)
9506 FunctionTemplateSpecializationInfo *Info =
9507 NewFD->getTemplateSpecializationInfo();
9508 if (Info && SC != SC_None) {
9509 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9510 Diag(NewFD->getLocation(),
9511 diag::err_explicit_specialization_inconsistent_storage_class)
9512 << SC
9513 << FixItHint::CreateRemoval(
9514 D.getDeclSpec().getStorageClassSpecLoc());
9515
9516 else
9517 Diag(NewFD->getLocation(),
9518 diag::ext_explicit_specialization_storage_class)
9519 << FixItHint::CreateRemoval(
9520 D.getDeclSpec().getStorageClassSpecLoc());
9521 }
9522 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9523 if (CheckMemberSpecialization(NewFD, Previous))
9524 NewFD->setInvalidDecl();
9525 }
9526
9527 // Perform semantic checking on the function declaration.
9528 if (!isDependentClassScopeExplicitSpecialization) {
9529 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9530 CheckMain(NewFD, D.getDeclSpec());
9531
9532 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9533 CheckMSVCRTEntryPoint(NewFD);
9534
9535 if (!NewFD->isInvalidDecl())
9536 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9537 isMemberSpecialization));
9538 else if (!Previous.empty())
9539 // Recover gracefully from an invalid redeclaration.
9540 D.setRedeclaration(true);
9541 }
9542
9543 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9545, __PRETTY_FUNCTION__))
9544 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9545, __PRETTY_FUNCTION__))
9545 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 9545, __PRETTY_FUNCTION__))
;
9546
9547 NamedDecl *PrincipalDecl = (FunctionTemplate
9548 ? cast<NamedDecl>(FunctionTemplate)
9549 : NewFD);
9550
9551 if (isFriend && NewFD->getPreviousDecl()) {
9552 AccessSpecifier Access = AS_public;
9553 if (!NewFD->isInvalidDecl())
9554 Access = NewFD->getPreviousDecl()->getAccess();
9555
9556 NewFD->setAccess(Access);
9557 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9558 }
9559
9560 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9561 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9562 PrincipalDecl->setNonMemberOperator();
9563
9564 // If we have a function template, check the template parameter
9565 // list. This will check and merge default template arguments.
9566 if (FunctionTemplate) {
9567 FunctionTemplateDecl *PrevTemplate =
9568 FunctionTemplate->getPreviousDecl();
9569 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9570 PrevTemplate ? PrevTemplate->getTemplateParameters()
9571 : nullptr,
9572 D.getDeclSpec().isFriendSpecified()
9573 ? (D.isFunctionDefinition()
9574 ? TPC_FriendFunctionTemplateDefinition
9575 : TPC_FriendFunctionTemplate)
9576 : (D.getCXXScopeSpec().isSet() &&
9577 DC && DC->isRecord() &&
9578 DC->isDependentContext())
9579 ? TPC_ClassTemplateMember
9580 : TPC_FunctionTemplate);
9581 }
9582
9583 if (NewFD->isInvalidDecl()) {
9584 // Ignore all the rest of this.
9585 } else if (!D.isRedeclaration()) {
9586 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9587 AddToScope };
9588 // Fake up an access specifier if it's supposed to be a class member.
9589 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9590 NewFD->setAccess(AS_public);
9591
9592 // Qualified decls generally require a previous declaration.
9593 if (D.getCXXScopeSpec().isSet()) {
9594 // ...with the major exception of templated-scope or
9595 // dependent-scope friend declarations.
9596
9597 // TODO: we currently also suppress this check in dependent
9598 // contexts because (1) the parameter depth will be off when
9599 // matching friend templates and (2) we might actually be
9600 // selecting a friend based on a dependent factor. But there
9601 // are situations where these conditions don't apply and we
9602 // can actually do this check immediately.
9603 //
9604 // Unless the scope is dependent, it's always an error if qualified
9605 // redeclaration lookup found nothing at all. Diagnose that now;
9606 // nothing will diagnose that error later.
9607 if (isFriend &&
9608 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9609 (!Previous.empty() && CurContext->isDependentContext()))) {
9610 // ignore these
9611 } else {
9612 // The user tried to provide an out-of-line definition for a
9613 // function that is a member of a class or namespace, but there
9614 // was no such member function declared (C++ [class.mfct]p2,
9615 // C++ [namespace.memdef]p2). For example:
9616 //
9617 // class X {
9618 // void f() const;
9619 // };
9620 //
9621 // void X::f() { } // ill-formed
9622 //
9623 // Complain about this problem, and attempt to suggest close
9624 // matches (e.g., those that differ only in cv-qualifiers and
9625 // whether the parameter types are references).
9626
9627 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9628 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9629 AddToScope = ExtraArgs.AddToScope;
9630 return Result;
9631 }
9632 }
9633
9634 // Unqualified local friend declarations are required to resolve
9635 // to something.
9636 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9637 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9638 *this, Previous, NewFD, ExtraArgs, true, S)) {
9639 AddToScope = ExtraArgs.AddToScope;
9640 return Result;
9641 }
9642 }
9643 } else if (!D.isFunctionDefinition() &&
9644 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9645 !isFriend && !isFunctionTemplateSpecialization &&
9646 !isMemberSpecialization) {
9647 // An out-of-line member function declaration must also be a
9648 // definition (C++ [class.mfct]p2).
9649 // Note that this is not the case for explicit specializations of
9650 // function templates or member functions of class templates, per
9651 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9652 // extension for compatibility with old SWIG code which likes to
9653 // generate them.
9654 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9655 << D.getCXXScopeSpec().getRange();
9656 }
9657 }
9658
9659 // If this is the first declaration of a library builtin function, add
9660 // attributes as appropriate.
9661 if (!D.isRedeclaration() &&
9662 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9663 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9664 if (unsigned BuiltinID = II->getBuiltinID()) {
9665 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9666 // Validate the type matches unless this builtin is specified as
9667 // matching regardless of its declared type.
9668 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9669 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9670 } else {
9671 ASTContext::GetBuiltinTypeError Error;
9672 LookupNecessaryTypesForBuiltin(S, BuiltinID);
9673 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9674
9675 if (!Error && !BuiltinType.isNull() &&
9676 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9677 NewFD->getType(), BuiltinType))
9678 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9679 }
9680 } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9681 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9682 // FIXME: We should consider this a builtin only in the std namespace.
9683 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9684 }
9685 }
9686 }
9687 }
9688
9689 ProcessPragmaWeak(S, NewFD);
9690 checkAttributesAfterMerging(*this, *NewFD);
9691
9692 AddKnownFunctionAttributes(NewFD);
9693
9694 if (NewFD->hasAttr<OverloadableAttr>() &&
9695 !NewFD->getType()->getAs<FunctionProtoType>()) {
9696 Diag(NewFD->getLocation(),
9697 diag::err_attribute_overloadable_no_prototype)
9698 << NewFD;
9699
9700 // Turn this into a variadic function with no parameters.
9701 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9702 FunctionProtoType::ExtProtoInfo EPI(
9703 Context.getDefaultCallingConvention(true, false));
9704 EPI.Variadic = true;
9705 EPI.ExtInfo = FT->getExtInfo();
9706
9707 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9708 NewFD->setType(R);
9709 }
9710
9711 // If there's a #pragma GCC visibility in scope, and this isn't a class
9712 // member, set the visibility of this function.
9713 if (!DC->isRecord() && NewFD->isExternallyVisible())
9714 AddPushedVisibilityAttribute(NewFD);
9715
9716 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9717 // marking the function.
9718 AddCFAuditedAttribute(NewFD);
9719
9720 // If this is a function definition, check if we have to apply optnone due to
9721 // a pragma.
9722 if(D.isFunctionDefinition())
9723 AddRangeBasedOptnone(NewFD);
9724
9725 // If this is the first declaration of an extern C variable, update
9726 // the map of such variables.
9727 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9728 isIncompleteDeclExternC(*this, NewFD))
9729 RegisterLocallyScopedExternCDecl(NewFD, S);
9730
9731 // Set this FunctionDecl's range up to the right paren.
9732 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9733
9734 if (D.isRedeclaration() && !Previous.empty()) {
9735 NamedDecl *Prev = Previous.getRepresentativeDecl();
9736 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9737 isMemberSpecialization ||
9738 isFunctionTemplateSpecialization,
9739 D.isFunctionDefinition());
9740 }
9741
9742 if (getLangOpts().CUDA) {
9743 IdentifierInfo *II = NewFD->getIdentifier();
9744 if (II && II->isStr(getCudaConfigureFuncName()) &&
9745 !NewFD->isInvalidDecl() &&
9746 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9747 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9748 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9749 << getCudaConfigureFuncName();
9750 Context.setcudaConfigureCallDecl(NewFD);
9751 }
9752
9753 // Variadic functions, other than a *declaration* of printf, are not allowed
9754 // in device-side CUDA code, unless someone passed
9755 // -fcuda-allow-variadic-functions.
9756 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9757 (NewFD->hasAttr<CUDADeviceAttr>() ||
9758 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9759 !(II && II->isStr("printf") && NewFD->isExternC() &&
9760 !D.isFunctionDefinition())) {
9761 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9762 }
9763 }
9764
9765 MarkUnusedFileScopedDecl(NewFD);
9766
9767
9768
9769 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9770 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9771 if ((getLangOpts().OpenCLVersion >= 120)
9772 && (SC == SC_Static)) {
9773 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9774 D.setInvalidType();
9775 }
9776
9777 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9778 if (!NewFD->getReturnType()->isVoidType()) {
9779 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9780 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9781 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9782 : FixItHint());
9783 D.setInvalidType();
9784 }
9785
9786 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9787 for (auto Param : NewFD->parameters())
9788 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9789
9790 if (getLangOpts().OpenCLCPlusPlus) {
9791 if (DC->isRecord()) {
9792 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9793 D.setInvalidType();
9794 }
9795 if (FunctionTemplate) {
9796 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9797 D.setInvalidType();
9798 }
9799 }
9800 }
9801
9802 if (getLangOpts().CPlusPlus) {
9803 if (FunctionTemplate) {
9804 if (NewFD->isInvalidDecl())
9805 FunctionTemplate->setInvalidDecl();
9806 return FunctionTemplate;
9807 }
9808
9809 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9810 CompleteMemberSpecialization(NewFD, Previous);
9811 }
9812
9813 for (const ParmVarDecl *Param : NewFD->parameters()) {
9814 QualType PT = Param->getType();
9815
9816 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9817 // types.
9818 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9819 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9820 QualType ElemTy = PipeTy->getElementType();
9821 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9822 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9823 D.setInvalidType();
9824 }
9825 }
9826 }
9827 }
9828
9829 // Here we have an function template explicit specialization at class scope.
9830 // The actual specialization will be postponed to template instatiation
9831 // time via the ClassScopeFunctionSpecializationDecl node.
9832 if (isDependentClassScopeExplicitSpecialization) {
9833 ClassScopeFunctionSpecializationDecl *NewSpec =
9834 ClassScopeFunctionSpecializationDecl::Create(
9835 Context, CurContext, NewFD->getLocation(),
9836 cast<CXXMethodDecl>(NewFD),
9837 HasExplicitTemplateArgs, TemplateArgs);
9838 CurContext->addDecl(NewSpec);
9839 AddToScope = false;
9840 }
9841
9842 // Diagnose availability attributes. Availability cannot be used on functions
9843 // that are run during load/unload.
9844 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9845 if (NewFD->hasAttr<ConstructorAttr>()) {
9846 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9847 << 1;
9848 NewFD->dropAttr<AvailabilityAttr>();
9849 }
9850 if (NewFD->hasAttr<DestructorAttr>()) {
9851 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9852 << 2;
9853 NewFD->dropAttr<AvailabilityAttr>();
9854 }
9855 }
9856
9857 // Diagnose no_builtin attribute on function declaration that are not a
9858 // definition.
9859 // FIXME: We should really be doing this in
9860 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9861 // the FunctionDecl and at this point of the code
9862 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9863 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9864 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9865 switch (D.getFunctionDefinitionKind()) {
9866 case FDK_Defaulted:
9867 case FDK_Deleted:
9868 Diag(NBA->getLocation(),
9869 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9870 << NBA->getSpelling();
9871 break;
9872 case FDK_Declaration:
9873 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9874 << NBA->getSpelling();
9875 break;
9876 case FDK_Definition:
9877 break;
9878 }
9879
9880 return NewFD;
9881}
9882
9883/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9884/// when __declspec(code_seg) "is applied to a class, all member functions of
9885/// the class and nested classes -- this includes compiler-generated special
9886/// member functions -- are put in the specified segment."
9887/// The actual behavior is a little more complicated. The Microsoft compiler
9888/// won't check outer classes if there is an active value from #pragma code_seg.
9889/// The CodeSeg is always applied from the direct parent but only from outer
9890/// classes when the #pragma code_seg stack is empty. See:
9891/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9892/// available since MS has removed the page.
9893static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9894 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9895 if (!Method)
9896 return nullptr;
9897 const CXXRecordDecl *Parent = Method->getParent();
9898 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9899 Attr *NewAttr = SAttr->clone(S.getASTContext());
9900 NewAttr->setImplicit(true);
9901 return NewAttr;
9902 }
9903
9904 // The Microsoft compiler won't check outer classes for the CodeSeg
9905 // when the #pragma code_seg stack is active.
9906 if (S.CodeSegStack.CurrentValue)
9907 return nullptr;
9908
9909 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9910 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9911 Attr *NewAttr = SAttr->clone(S.getASTContext());
9912 NewAttr->setImplicit(true);
9913 return NewAttr;
9914 }
9915 }
9916 return nullptr;
9917}
9918
9919/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9920/// containing class. Otherwise it will return implicit SectionAttr if the
9921/// function is a definition and there is an active value on CodeSegStack
9922/// (from the current #pragma code-seg value).
9923///
9924/// \param FD Function being declared.
9925/// \param IsDefinition Whether it is a definition or just a declarartion.
9926/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9927/// nullptr if no attribute should be added.
9928Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9929 bool IsDefinition) {
9930 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9931 return A;
9932 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9933 CodeSegStack.CurrentValue)
9934 return SectionAttr::CreateImplicit(
9935 getASTContext(), CodeSegStack.CurrentValue->getString(),
9936 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9937 SectionAttr::Declspec_allocate);
9938 return nullptr;
9939}
9940
9941/// Determines if we can perform a correct type check for \p D as a
9942/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9943/// best-effort check.
9944///
9945/// \param NewD The new declaration.
9946/// \param OldD The old declaration.
9947/// \param NewT The portion of the type of the new declaration to check.
9948/// \param OldT The portion of the type of the old declaration to check.
9949bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9950 QualType NewT, QualType OldT) {
9951 if (!NewD->getLexicalDeclContext()->isDependentContext())
9952 return true;
9953
9954 // For dependently-typed local extern declarations and friends, we can't
9955 // perform a correct type check in general until instantiation:
9956 //
9957 // int f();
9958 // template<typename T> void g() { T f(); }
9959 //
9960 // (valid if g() is only instantiated with T = int).
9961 if (NewT->isDependentType() &&
9962 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9963 return false;
9964
9965 // Similarly, if the previous declaration was a dependent local extern
9966 // declaration, we don't really know its type yet.
9967 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9968 return false;
9969
9970 return true;
9971}
9972
9973/// Checks if the new declaration declared in dependent context must be
9974/// put in the same redeclaration chain as the specified declaration.
9975///
9976/// \param D Declaration that is checked.
9977/// \param PrevDecl Previous declaration found with proper lookup method for the
9978/// same declaration name.
9979/// \returns True if D must be added to the redeclaration chain which PrevDecl
9980/// belongs to.
9981///
9982bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9983 if (!D->getLexicalDeclContext()->isDependentContext())
9984 return true;
9985
9986 // Don't chain dependent friend function definitions until instantiation, to
9987 // permit cases like
9988 //
9989 // void func();
9990 // template<typename T> class C1 { friend void func() {} };
9991 // template<typename T> class C2 { friend void func() {} };
9992 //
9993 // ... which is valid if only one of C1 and C2 is ever instantiated.
9994 //
9995 // FIXME: This need only apply to function definitions. For now, we proxy
9996 // this by checking for a file-scope function. We do not want this to apply
9997 // to friend declarations nominating member functions, because that gets in
9998 // the way of access checks.
9999 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10000 return false;
10001
10002 auto *VD = dyn_cast<ValueDecl>(D);
10003 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10004 return !VD || !PrevVD ||
10005 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10006 PrevVD->getType());
10007}
10008
10009/// Check the target attribute of the function for MultiVersion
10010/// validity.
10011///
10012/// Returns true if there was an error, false otherwise.
10013static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10014 const auto *TA = FD->getAttr<TargetAttr>();
10015 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10015, __PRETTY_FUNCTION__))
;
10016 ParsedTargetAttr ParseInfo = TA->parse();
10017 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10018 enum ErrType { Feature = 0, Architecture = 1 };
10019
10020 if (!ParseInfo.Architecture.empty() &&
10021 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10022 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10023 << Architecture << ParseInfo.Architecture;
10024 return true;
10025 }
10026
10027 for (const auto &Feat : ParseInfo.Features) {
10028 auto BareFeat = StringRef{Feat}.substr(1);
10029 if (Feat[0] == '-') {
10030 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10031 << Feature << ("no-" + BareFeat).str();
10032 return true;
10033 }
10034
10035 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10036 !TargetInfo.isValidFeatureName(BareFeat)) {
10037 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10038 << Feature << BareFeat;
10039 return true;
10040 }
10041 }
10042 return false;
10043}
10044
10045// Provide a white-list of attributes that are allowed to be combined with
10046// multiversion functions.
10047static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10048 MultiVersionKind MVType) {
10049 // Note: this list/diagnosis must match the list in
10050 // checkMultiversionAttributesAllSame.
10051 switch (Kind) {
10052 default:
10053 return false;
10054 case attr::Used:
10055 return MVType == MultiVersionKind::Target;
10056 case attr::NonNull:
10057 case attr::NoThrow:
10058 return true;
10059 }
10060}
10061
10062static bool checkNonMultiVersionCompatAttributes(Sema &S,
10063 const FunctionDecl *FD,
10064 const FunctionDecl *CausedFD,
10065 MultiVersionKind MVType) {
10066 bool IsCPUSpecificCPUDispatchMVType =
10067 MVType == MultiVersionKind::CPUDispatch ||
10068 MVType == MultiVersionKind::CPUSpecific;
10069 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10070 Sema &S, const Attr *A) {
10071 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10072 << IsCPUSpecificCPUDispatchMVType << A;
10073 if (CausedFD)
10074 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10075 return true;
10076 };
10077
10078 for (const Attr *A : FD->attrs()) {
10079 switch (A->getKind()) {
10080 case attr::CPUDispatch:
10081 case attr::CPUSpecific:
10082 if (MVType != MultiVersionKind::CPUDispatch &&
10083 MVType != MultiVersionKind::CPUSpecific)
10084 return Diagnose(S, A);
10085 break;
10086 case attr::Target:
10087 if (MVType != MultiVersionKind::Target)
10088 return Diagnose(S, A);
10089 break;
10090 default:
10091 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10092 return Diagnose(S, A);
10093 break;
10094 }
10095 }
10096 return false;
10097}
10098
10099bool Sema::areMultiversionVariantFunctionsCompatible(
10100 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10101 const PartialDiagnostic &NoProtoDiagID,
10102 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10103 const PartialDiagnosticAt &NoSupportDiagIDAt,
10104 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10105 bool ConstexprSupported, bool CLinkageMayDiffer) {
10106 enum DoesntSupport {
10107 FuncTemplates = 0,
10108 VirtFuncs = 1,
10109 DeducedReturn = 2,
10110 Constructors = 3,
10111 Destructors = 4,
10112 DeletedFuncs = 5,
10113 DefaultedFuncs = 6,
10114 ConstexprFuncs = 7,
10115 ConstevalFuncs = 8,
10116 };
10117 enum Different {
10118 CallingConv = 0,
10119 ReturnType = 1,
10120 ConstexprSpec = 2,
10121 InlineSpec = 3,
10122 StorageClass = 4,
10123 Linkage = 5,
10124 };
10125
10126 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10127 !OldFD->getType()->getAs<FunctionProtoType>()) {
10128 Diag(OldFD->getLocation(), NoProtoDiagID);
10129 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10130 return true;
10131 }
10132
10133 if (NoProtoDiagID.getDiagID() != 0 &&
10134 !NewFD->getType()->getAs<FunctionProtoType>())
10135 return Diag(NewFD->getLocation(), NoProtoDiagID);
10136
10137 if (!TemplatesSupported &&
10138 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10139 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10140 << FuncTemplates;
10141
10142 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10143 if (NewCXXFD->isVirtual())
10144 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10145 << VirtFuncs;
10146
10147 if (isa<CXXConstructorDecl>(NewCXXFD))
10148 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10149 << Constructors;
10150
10151 if (isa<CXXDestructorDecl>(NewCXXFD))
10152 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10153 << Destructors;
10154 }
10155
10156 if (NewFD->isDeleted())
10157 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10158 << DeletedFuncs;
10159
10160 if (NewFD->isDefaulted())
10161 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10162 << DefaultedFuncs;
10163
10164 if (!ConstexprSupported && NewFD->isConstexpr())
10165 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10166 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10167
10168 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10169 const auto *NewType = cast<FunctionType>(NewQType);
10170 QualType NewReturnType = NewType->getReturnType();
10171
10172 if (NewReturnType->isUndeducedType())
10173 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10174 << DeducedReturn;
10175
10176 // Ensure the return type is identical.
10177 if (OldFD) {
10178 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10179 const auto *OldType = cast<FunctionType>(OldQType);
10180 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10181 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10182
10183 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10184 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10185
10186 QualType OldReturnType = OldType->getReturnType();
10187
10188 if (OldReturnType != NewReturnType)
10189 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10190
10191 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10192 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10193
10194 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10195 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10196
10197 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10198 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10199
10200 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10201 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10202
10203 if (CheckEquivalentExceptionSpec(
10204 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10205 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10206 return true;
10207 }
10208 return false;
10209}
10210
10211static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10212 const FunctionDecl *NewFD,
10213 bool CausesMV,
10214 MultiVersionKind MVType) {
10215 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10216 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10217 if (OldFD)
10218 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10219 return true;
10220 }
10221
10222 bool IsCPUSpecificCPUDispatchMVType =
10223 MVType == MultiVersionKind::CPUDispatch ||
10224 MVType == MultiVersionKind::CPUSpecific;
10225
10226 if (CausesMV && OldFD &&
10227 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10228 return true;
10229
10230 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10231 return true;
10232
10233 // Only allow transition to MultiVersion if it hasn't been used.
10234 if (OldFD && CausesMV && OldFD->isUsed(false))
10235 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10236
10237 return S.areMultiversionVariantFunctionsCompatible(
10238 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10239 PartialDiagnosticAt(NewFD->getLocation(),
10240 S.PDiag(diag::note_multiversioning_caused_here)),
10241 PartialDiagnosticAt(NewFD->getLocation(),
10242 S.PDiag(diag::err_multiversion_doesnt_support)
10243 << IsCPUSpecificCPUDispatchMVType),
10244 PartialDiagnosticAt(NewFD->getLocation(),
10245 S.PDiag(diag::err_multiversion_diff)),
10246 /*TemplatesSupported=*/false,
10247 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10248 /*CLinkageMayDiffer=*/false);
10249}
10250
10251/// Check the validity of a multiversion function declaration that is the
10252/// first of its kind. Also sets the multiversion'ness' of the function itself.
10253///
10254/// This sets NewFD->isInvalidDecl() to true if there was an error.
10255///
10256/// Returns true if there was an error, false otherwise.
10257static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10258 MultiVersionKind MVType,
10259 const TargetAttr *TA) {
10260 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10261, __PRETTY_FUNCTION__))
10261 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10261, __PRETTY_FUNCTION__))
;
10262
10263 // Target only causes MV if it is default, otherwise this is a normal
10264 // function.
10265 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10266 return false;
10267
10268 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10269 FD->setInvalidDecl();
10270 return true;
10271 }
10272
10273 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10274 FD->setInvalidDecl();
10275 return true;
10276 }
10277
10278 FD->setIsMultiVersion();
10279 return false;
10280}
10281
10282static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10283 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10284 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10285 return true;
10286 }
10287
10288 return false;
10289}
10290
10291static bool CheckTargetCausesMultiVersioning(
10292 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10293 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10294 LookupResult &Previous) {
10295 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10296 ParsedTargetAttr NewParsed = NewTA->parse();
10297 // Sort order doesn't matter, it just needs to be consistent.
10298 llvm::sort(NewParsed.Features);
10299
10300 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10301 // to change, this is a simple redeclaration.
10302 if (!NewTA->isDefaultVersion() &&
10303 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10304 return false;
10305
10306 // Otherwise, this decl causes MultiVersioning.
10307 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10308 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10309 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10310 NewFD->setInvalidDecl();
10311 return true;
10312 }
10313
10314 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10315 MultiVersionKind::Target)) {
10316 NewFD->setInvalidDecl();
10317 return true;
10318 }
10319
10320 if (CheckMultiVersionValue(S, NewFD)) {
10321 NewFD->setInvalidDecl();
10322 return true;
10323 }
10324
10325 // If this is 'default', permit the forward declaration.
10326 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10327 Redeclaration = true;
10328 OldDecl = OldFD;
10329 OldFD->setIsMultiVersion();
10330 NewFD->setIsMultiVersion();
10331 return false;
10332 }
10333
10334 if (CheckMultiVersionValue(S, OldFD)) {
10335 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10336 NewFD->setInvalidDecl();
10337 return true;
10338 }
10339
10340 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10341
10342 if (OldParsed == NewParsed) {
10343 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10344 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10345 NewFD->setInvalidDecl();
10346 return true;
10347 }
10348
10349 for (const auto *FD : OldFD->redecls()) {
10350 const auto *CurTA = FD->getAttr<TargetAttr>();
10351 // We allow forward declarations before ANY multiversioning attributes, but
10352 // nothing after the fact.
10353 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10354 (!CurTA || CurTA->isInherited())) {
10355 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10356 << 0;
10357 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10358 NewFD->setInvalidDecl();
10359 return true;
10360 }
10361 }
10362
10363 OldFD->setIsMultiVersion();
10364 NewFD->setIsMultiVersion();
10365 Redeclaration = false;
10366 MergeTypeWithPrevious = false;
10367 OldDecl = nullptr;
10368 Previous.clear();
10369 return false;
10370}
10371
10372/// Check the validity of a new function declaration being added to an existing
10373/// multiversioned declaration collection.
10374static bool CheckMultiVersionAdditionalDecl(
10375 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10376 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10377 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10378 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10379 LookupResult &Previous) {
10380
10381 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10382 // Disallow mixing of multiversioning types.
10383 if ((OldMVType == MultiVersionKind::Target &&
10384 NewMVType != MultiVersionKind::Target) ||
10385 (NewMVType == MultiVersionKind::Target &&
10386 OldMVType != MultiVersionKind::Target)) {
10387 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10388 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10389 NewFD->setInvalidDecl();
10390 return true;
10391 }
10392
10393 ParsedTargetAttr NewParsed;
10394 if (NewTA) {
10395 NewParsed = NewTA->parse();
10396 llvm::sort(NewParsed.Features);
10397 }
10398
10399 bool UseMemberUsingDeclRules =
10400 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10401
10402 // Next, check ALL non-overloads to see if this is a redeclaration of a
10403 // previous member of the MultiVersion set.
10404 for (NamedDecl *ND : Previous) {
10405 FunctionDecl *CurFD = ND->getAsFunction();
10406 if (!CurFD)
10407 continue;
10408 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10409 continue;
10410
10411 if (NewMVType == MultiVersionKind::Target) {
10412 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10413 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10414 NewFD->setIsMultiVersion();
10415 Redeclaration = true;
10416 OldDecl = ND;
10417 return false;
10418 }
10419
10420 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10421 if (CurParsed == NewParsed) {
10422 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10423 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10424 NewFD->setInvalidDecl();
10425 return true;
10426 }
10427 } else {
10428 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10429 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10430 // Handle CPUDispatch/CPUSpecific versions.
10431 // Only 1 CPUDispatch function is allowed, this will make it go through
10432 // the redeclaration errors.
10433 if (NewMVType == MultiVersionKind::CPUDispatch &&
10434 CurFD->hasAttr<CPUDispatchAttr>()) {
10435 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10436 std::equal(
10437 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10438 NewCPUDisp->cpus_begin(),
10439 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10440 return Cur->getName() == New->getName();
10441 })) {
10442 NewFD->setIsMultiVersion();
10443 Redeclaration = true;
10444 OldDecl = ND;
10445 return false;
10446 }
10447
10448 // If the declarations don't match, this is an error condition.
10449 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10450 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10451 NewFD->setInvalidDecl();
10452 return true;
10453 }
10454 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10455
10456 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10457 std::equal(
10458 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10459 NewCPUSpec->cpus_begin(),
10460 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10461 return Cur->getName() == New->getName();
10462 })) {
10463 NewFD->setIsMultiVersion();
10464 Redeclaration = true;
10465 OldDecl = ND;
10466 return false;
10467 }
10468
10469 // Only 1 version of CPUSpecific is allowed for each CPU.
10470 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10471 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10472 if (CurII == NewII) {
10473 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10474 << NewII;
10475 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10476 NewFD->setInvalidDecl();
10477 return true;
10478 }
10479 }
10480 }
10481 }
10482 // If the two decls aren't the same MVType, there is no possible error
10483 // condition.
10484 }
10485 }
10486
10487 // Else, this is simply a non-redecl case. Checking the 'value' is only
10488 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10489 // handled in the attribute adding step.
10490 if (NewMVType == MultiVersionKind::Target &&
10491 CheckMultiVersionValue(S, NewFD)) {
10492 NewFD->setInvalidDecl();
10493 return true;
10494 }
10495
10496 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10497 !OldFD->isMultiVersion(), NewMVType)) {
10498 NewFD->setInvalidDecl();
10499 return true;
10500 }
10501
10502 // Permit forward declarations in the case where these two are compatible.
10503 if (!OldFD->isMultiVersion()) {
10504 OldFD->setIsMultiVersion();
10505 NewFD->setIsMultiVersion();
10506 Redeclaration = true;
10507 OldDecl = OldFD;
10508 return false;
10509 }
10510
10511 NewFD->setIsMultiVersion();
10512 Redeclaration = false;
10513 MergeTypeWithPrevious = false;
10514 OldDecl = nullptr;
10515 Previous.clear();
10516 return false;
10517}
10518
10519
10520/// Check the validity of a mulitversion function declaration.
10521/// Also sets the multiversion'ness' of the function itself.
10522///
10523/// This sets NewFD->isInvalidDecl() to true if there was an error.
10524///
10525/// Returns true if there was an error, false otherwise.
10526static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10527 bool &Redeclaration, NamedDecl *&OldDecl,
10528 bool &MergeTypeWithPrevious,
10529 LookupResult &Previous) {
10530 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10531 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10532 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10533
10534 // Mixing Multiversioning types is prohibited.
10535 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10536 (NewCPUDisp && NewCPUSpec)) {
10537 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10538 NewFD->setInvalidDecl();
10539 return true;
10540 }
10541
10542 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10543
10544 // Main isn't allowed to become a multiversion function, however it IS
10545 // permitted to have 'main' be marked with the 'target' optimization hint.
10546 if (NewFD->isMain()) {
10547 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10548 MVType == MultiVersionKind::CPUDispatch ||
10549 MVType == MultiVersionKind::CPUSpecific) {
10550 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10551 NewFD->setInvalidDecl();
10552 return true;
10553 }
10554 return false;
10555 }
10556
10557 if (!OldDecl || !OldDecl->getAsFunction() ||
10558 OldDecl->getDeclContext()->getRedeclContext() !=
10559 NewFD->getDeclContext()->getRedeclContext()) {
10560 // If there's no previous declaration, AND this isn't attempting to cause
10561 // multiversioning, this isn't an error condition.
10562 if (MVType == MultiVersionKind::None)
10563 return false;
10564 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10565 }
10566
10567 FunctionDecl *OldFD = OldDecl->getAsFunction();
10568
10569 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10570 return false;
10571
10572 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10573 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10574 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10575 NewFD->setInvalidDecl();
10576 return true;
10577 }
10578
10579 // Handle the target potentially causes multiversioning case.
10580 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10581 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10582 Redeclaration, OldDecl,
10583 MergeTypeWithPrevious, Previous);
10584
10585 // At this point, we have a multiversion function decl (in OldFD) AND an
10586 // appropriate attribute in the current function decl. Resolve that these are
10587 // still compatible with previous declarations.
10588 return CheckMultiVersionAdditionalDecl(
10589 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10590 OldDecl, MergeTypeWithPrevious, Previous);
10591}
10592
10593/// Perform semantic checking of a new function declaration.
10594///
10595/// Performs semantic analysis of the new function declaration
10596/// NewFD. This routine performs all semantic checking that does not
10597/// require the actual declarator involved in the declaration, and is
10598/// used both for the declaration of functions as they are parsed
10599/// (called via ActOnDeclarator) and for the declaration of functions
10600/// that have been instantiated via C++ template instantiation (called
10601/// via InstantiateDecl).
10602///
10603/// \param IsMemberSpecialization whether this new function declaration is
10604/// a member specialization (that replaces any definition provided by the
10605/// previous declaration).
10606///
10607/// This sets NewFD->isInvalidDecl() to true if there was an error.
10608///
10609/// \returns true if the function declaration is a redeclaration.
10610bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10611 LookupResult &Previous,
10612 bool IsMemberSpecialization) {
10613 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10614, __PRETTY_FUNCTION__))
10614 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10614, __PRETTY_FUNCTION__))
;
10615
10616 // Determine whether the type of this function should be merged with
10617 // a previous visible declaration. This never happens for functions in C++,
10618 // and always happens in C if the previous declaration was visible.
10619 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10620 !Previous.isShadowed();
10621
10622 bool Redeclaration = false;
10623 NamedDecl *OldDecl = nullptr;
10624 bool MayNeedOverloadableChecks = false;
10625
10626 // Merge or overload the declaration with an existing declaration of
10627 // the same name, if appropriate.
10628 if (!Previous.empty()) {
10629 // Determine whether NewFD is an overload of PrevDecl or
10630 // a declaration that requires merging. If it's an overload,
10631 // there's no more work to do here; we'll just add the new
10632 // function to the scope.
10633 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10634 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10635 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10636 Redeclaration = true;
10637 OldDecl = Candidate;
10638 }
10639 } else {
10640 MayNeedOverloadableChecks = true;
10641 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10642 /*NewIsUsingDecl*/ false)) {
10643 case Ovl_Match:
10644 Redeclaration = true;
10645 break;
10646
10647 case Ovl_NonFunction:
10648 Redeclaration = true;
10649 break;
10650
10651 case Ovl_Overload:
10652 Redeclaration = false;
10653 break;
10654 }
10655 }
10656 }
10657
10658 // Check for a previous extern "C" declaration with this name.
10659 if (!Redeclaration &&
10660 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10661 if (!Previous.empty()) {
10662 // This is an extern "C" declaration with the same name as a previous
10663 // declaration, and thus redeclares that entity...
10664 Redeclaration = true;
10665 OldDecl = Previous.getFoundDecl();
10666 MergeTypeWithPrevious = false;
10667
10668 // ... except in the presence of __attribute__((overloadable)).
10669 if (OldDecl->hasAttr<OverloadableAttr>() ||
10670 NewFD->hasAttr<OverloadableAttr>()) {
10671 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10672 MayNeedOverloadableChecks = true;
10673 Redeclaration = false;
10674 OldDecl = nullptr;
10675 }
10676 }
10677 }
10678 }
10679
10680 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10681 MergeTypeWithPrevious, Previous))
10682 return Redeclaration;
10683
10684 // C++11 [dcl.constexpr]p8:
10685 // A constexpr specifier for a non-static member function that is not
10686 // a constructor declares that member function to be const.
10687 //
10688 // This needs to be delayed until we know whether this is an out-of-line
10689 // definition of a static member function.
10690 //
10691 // This rule is not present in C++1y, so we produce a backwards
10692 // compatibility warning whenever it happens in C++11.
10693 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10694 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10695 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10696 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10697 CXXMethodDecl *OldMD = nullptr;
10698 if (OldDecl)
10699 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10700 if (!OldMD || !OldMD->isStatic()) {
10701 const FunctionProtoType *FPT =
10702 MD->getType()->castAs<FunctionProtoType>();
10703 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10704 EPI.TypeQuals.addConst();
10705 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10706 FPT->getParamTypes(), EPI));
10707
10708 // Warn that we did this, if we're not performing template instantiation.
10709 // In that case, we'll have warned already when the template was defined.
10710 if (!inTemplateInstantiation()) {
10711 SourceLocation AddConstLoc;
10712 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10713 .IgnoreParens().getAs<FunctionTypeLoc>())
10714 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10715
10716 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10717 << FixItHint::CreateInsertion(AddConstLoc, " const");
10718 }
10719 }
10720 }
10721
10722 if (Redeclaration) {
10723 // NewFD and OldDecl represent declarations that need to be
10724 // merged.
10725 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10726 NewFD->setInvalidDecl();
10727 return Redeclaration;
10728 }
10729
10730 Previous.clear();
10731 Previous.addDecl(OldDecl);
10732
10733 if (FunctionTemplateDecl *OldTemplateDecl =
10734 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10735 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10736 FunctionTemplateDecl *NewTemplateDecl
10737 = NewFD->getDescribedFunctionTemplate();
10738 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10738, __PRETTY_FUNCTION__))
;
10739
10740 // The call to MergeFunctionDecl above may have created some state in
10741 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10742 // can add it as a redeclaration.
10743 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10744
10745 NewFD->setPreviousDeclaration(OldFD);
10746 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10747 if (NewFD->isCXXClassMember()) {
10748 NewFD->setAccess(OldTemplateDecl->getAccess());
10749 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10750 }
10751
10752 // If this is an explicit specialization of a member that is a function
10753 // template, mark it as a member specialization.
10754 if (IsMemberSpecialization &&
10755 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10756 NewTemplateDecl->setMemberSpecialization();
10757 assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast
<void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10757, __PRETTY_FUNCTION__))
;
10758 // Explicit specializations of a member template do not inherit deleted
10759 // status from the parent member template that they are specializing.
10760 if (OldFD->isDeleted()) {
10761 // FIXME: This assert will not hold in the presence of modules.
10762 assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void
> (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10762, __PRETTY_FUNCTION__))
;
10763 // FIXME: We need an update record for this AST mutation.
10764 OldFD->setDeletedAsWritten(false);
10765 }
10766 }
10767
10768 } else {
10769 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10770 auto *OldFD = cast<FunctionDecl>(OldDecl);
10771 // This needs to happen first so that 'inline' propagates.
10772 NewFD->setPreviousDeclaration(OldFD);
10773 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10774 if (NewFD->isCXXClassMember())
10775 NewFD->setAccess(OldFD->getAccess());
10776 }
10777 }
10778 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10779 !NewFD->getAttr<OverloadableAttr>()) {
10780 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10785, __PRETTY_FUNCTION__))
10781 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10785, __PRETTY_FUNCTION__))
10782 [](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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10785, __PRETTY_FUNCTION__))
10783 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10785, __PRETTY_FUNCTION__))
10784 })) &&(((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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10785, __PRETTY_FUNCTION__))
10785 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10785, __PRETTY_FUNCTION__))
;
10786
10787 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10788 const auto *FD = dyn_cast<FunctionDecl>(ND);
10789 return FD && !FD->hasAttr<OverloadableAttr>();
10790 });
10791
10792 if (OtherUnmarkedIter != Previous.end()) {
10793 Diag(NewFD->getLocation(),
10794 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10795 Diag((*OtherUnmarkedIter)->getLocation(),
10796 diag::note_attribute_overloadable_prev_overload)
10797 << false;
10798
10799 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10800 }
10801 }
10802
10803 // Semantic checking for this function declaration (in isolation).
10804
10805 if (getLangOpts().CPlusPlus) {
10806 // C++-specific checks.
10807 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10808 CheckConstructor(Constructor);
10809 } else if (CXXDestructorDecl *Destructor =
10810 dyn_cast<CXXDestructorDecl>(NewFD)) {
10811 CXXRecordDecl *Record = Destructor->getParent();
10812 QualType ClassType = Context.getTypeDeclType(Record);
10813
10814 // FIXME: Shouldn't we be able to perform this check even when the class
10815 // type is dependent? Both gcc and edg can handle that.
10816 if (!ClassType->isDependentType()) {
10817 DeclarationName Name
10818 = Context.DeclarationNames.getCXXDestructorName(
10819 Context.getCanonicalType(ClassType));
10820 if (NewFD->getDeclName() != Name) {
10821 Diag(NewFD->getLocation(), diag::err_destructor_name);
10822 NewFD->setInvalidDecl();
10823 return Redeclaration;
10824 }
10825 }
10826 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10827 if (auto *TD = Guide->getDescribedFunctionTemplate())
10828 CheckDeductionGuideTemplate(TD);
10829
10830 // A deduction guide is not on the list of entities that can be
10831 // explicitly specialized.
10832 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10833 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10834 << /*explicit specialization*/ 1;
10835 }
10836
10837 // Find any virtual functions that this function overrides.
10838 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10839 if (!Method->isFunctionTemplateSpecialization() &&
10840 !Method->getDescribedFunctionTemplate() &&
10841 Method->isCanonicalDecl()) {
10842 AddOverriddenMethods(Method->getParent(), Method);
10843 }
10844 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10845 // C++2a [class.virtual]p6
10846 // A virtual method shall not have a requires-clause.
10847 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10848 diag::err_constrained_virtual_method);
10849
10850 if (Method->isStatic())
10851 checkThisInStaticMemberFunctionType(Method);
10852 }
10853
10854 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10855 ActOnConversionDeclarator(Conversion);
10856
10857 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10858 if (NewFD->isOverloadedOperator() &&
10859 CheckOverloadedOperatorDeclaration(NewFD)) {
10860 NewFD->setInvalidDecl();
10861 return Redeclaration;
10862 }
10863
10864 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10865 if (NewFD->getLiteralIdentifier() &&
10866 CheckLiteralOperatorDeclaration(NewFD)) {
10867 NewFD->setInvalidDecl();
10868 return Redeclaration;
10869 }
10870
10871 // In C++, check default arguments now that we have merged decls. Unless
10872 // the lexical context is the class, because in this case this is done
10873 // during delayed parsing anyway.
10874 if (!CurContext->isRecord())
10875 CheckCXXDefaultArguments(NewFD);
10876
10877 // If this function declares a builtin function, check the type of this
10878 // declaration against the expected type for the builtin.
10879 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10880 ASTContext::GetBuiltinTypeError Error;
10881 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10882 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10883 // If the type of the builtin differs only in its exception
10884 // specification, that's OK.
10885 // FIXME: If the types do differ in this way, it would be better to
10886 // retain the 'noexcept' form of the type.
10887 if (!T.isNull() &&
10888 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10889 NewFD->getType()))
10890 // The type of this function differs from the type of the builtin,
10891 // so forget about the builtin entirely.
10892 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10893 }
10894
10895 // If this function is declared as being extern "C", then check to see if
10896 // the function returns a UDT (class, struct, or union type) that is not C
10897 // compatible, and if it does, warn the user.
10898 // But, issue any diagnostic on the first declaration only.
10899 if (Previous.empty() && NewFD->isExternC()) {
10900 QualType R = NewFD->getReturnType();
10901 if (R->isIncompleteType() && !R->isVoidType())
10902 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10903 << NewFD << R;
10904 else if (!R.isPODType(Context) && !R->isVoidType() &&
10905 !R->isObjCObjectPointerType())
10906 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10907 }
10908
10909 // C++1z [dcl.fct]p6:
10910 // [...] whether the function has a non-throwing exception-specification
10911 // [is] part of the function type
10912 //
10913 // This results in an ABI break between C++14 and C++17 for functions whose
10914 // declared type includes an exception-specification in a parameter or
10915 // return type. (Exception specifications on the function itself are OK in
10916 // most cases, and exception specifications are not permitted in most other
10917 // contexts where they could make it into a mangling.)
10918 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10919 auto HasNoexcept = [&](QualType T) -> bool {
10920 // Strip off declarator chunks that could be between us and a function
10921 // type. We don't need to look far, exception specifications are very
10922 // restricted prior to C++17.
10923 if (auto *RT = T->getAs<ReferenceType>())
10924 T = RT->getPointeeType();
10925 else if (T->isAnyPointerType())
10926 T = T->getPointeeType();
10927 else if (auto *MPT = T->getAs<MemberPointerType>())
10928 T = MPT->getPointeeType();
10929 if (auto *FPT = T->getAs<FunctionProtoType>())
10930 if (FPT->isNothrow())
10931 return true;
10932 return false;
10933 };
10934
10935 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10936 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10937 for (QualType T : FPT->param_types())
10938 AnyNoexcept |= HasNoexcept(T);
10939 if (AnyNoexcept)
10940 Diag(NewFD->getLocation(),
10941 diag::warn_cxx17_compat_exception_spec_in_signature)
10942 << NewFD;
10943 }
10944
10945 if (!Redeclaration && LangOpts.CUDA)
10946 checkCUDATargetOverload(NewFD, Previous);
10947 }
10948 return Redeclaration;
10949}
10950
10951void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10952 // C++11 [basic.start.main]p3:
10953 // A program that [...] declares main to be inline, static or
10954 // constexpr is ill-formed.
10955 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10956 // appear in a declaration of main.
10957 // static main is not an error under C99, but we should warn about it.
10958 // We accept _Noreturn main as an extension.
10959 if (FD->getStorageClass() == SC_Static)
10960 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10961 ? diag::err_static_main : diag::warn_static_main)
10962 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10963 if (FD->isInlineSpecified())
10964 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10965 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10966 if (DS.isNoreturnSpecified()) {
10967 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10968 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10969 Diag(NoreturnLoc, diag::ext_noreturn_main);
10970 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10971 << FixItHint::CreateRemoval(NoreturnRange);
10972 }
10973 if (FD->isConstexpr()) {
10974 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10975 << FD->isConsteval()
10976 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10977 FD->setConstexprKind(CSK_unspecified);
10978 }
10979
10980 if (getLangOpts().OpenCL) {
10981 Diag(FD->getLocation(), diag::err_opencl_no_main)
10982 << FD->hasAttr<OpenCLKernelAttr>();
10983 FD->setInvalidDecl();
10984 return;
10985 }
10986
10987 QualType T = FD->getType();
10988 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 10988, __PRETTY_FUNCTION__))
;
10989 const FunctionType* FT = T->castAs<FunctionType>();
10990
10991 // Set default calling convention for main()
10992 if (FT->getCallConv() != CC_C) {
10993 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10994 FD->setType(QualType(FT, 0));
10995 T = Context.getCanonicalType(FD->getType());
10996 }
10997
10998 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10999 // In C with GNU extensions we allow main() to have non-integer return
11000 // type, but we should warn about the extension, and we disable the
11001 // implicit-return-zero rule.
11002
11003 // GCC in C mode accepts qualified 'int'.
11004 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11005 FD->setHasImplicitReturnZero(true);
11006 else {
11007 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11008 SourceRange RTRange = FD->getReturnTypeSourceRange();
11009 if (RTRange.isValid())
11010 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11011 << FixItHint::CreateReplacement(RTRange, "int");
11012 }
11013 } else {
11014 // In C and C++, main magically returns 0 if you fall off the end;
11015 // set the flag which tells us that.
11016 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11017
11018 // All the standards say that main() should return 'int'.
11019 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11020 FD->setHasImplicitReturnZero(true);
11021 else {
11022 // Otherwise, this is just a flat-out error.
11023 SourceRange RTRange = FD->getReturnTypeSourceRange();
11024 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11025 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11026 : FixItHint());
11027 FD->setInvalidDecl(true);
11028 }
11029 }
11030
11031 // Treat protoless main() as nullary.
11032 if (isa<FunctionNoProtoType>(FT)) return;
11033
11034 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11035 unsigned nparams = FTP->getNumParams();
11036 assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void>
(0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11036, __PRETTY_FUNCTION__))
;
11037
11038 bool HasExtraParameters = (nparams > 3);
11039
11040 if (FTP->isVariadic()) {
11041 Diag(FD->getLocation(), diag::ext_variadic_main);
11042 // FIXME: if we had information about the location of the ellipsis, we
11043 // could add a FixIt hint to remove it as a parameter.
11044 }
11045
11046 // Darwin passes an undocumented fourth argument of type char**. If
11047 // other platforms start sprouting these, the logic below will start
11048 // getting shifty.
11049 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11050 HasExtraParameters = false;
11051
11052 if (HasExtraParameters) {
11053 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11054 FD->setInvalidDecl(true);
11055 nparams = 3;
11056 }
11057
11058 // FIXME: a lot of the following diagnostics would be improved
11059 // if we had some location information about types.
11060
11061 QualType CharPP =
11062 Context.getPointerType(Context.getPointerType(Context.CharTy));
11063 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11064
11065 for (unsigned i = 0; i < nparams; ++i) {
11066 QualType AT = FTP->getParamType(i);
11067
11068 bool mismatch = true;
11069
11070 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11071 mismatch = false;
11072 else if (Expected[i] == CharPP) {
11073 // As an extension, the following forms are okay:
11074 // char const **
11075 // char const * const *
11076 // char * const *
11077
11078 QualifierCollector qs;
11079 const PointerType* PT;
11080 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11081 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11082 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11083 Context.CharTy)) {
11084 qs.removeConst();
11085 mismatch = !qs.empty();
11086 }
11087 }
11088
11089 if (mismatch) {
11090 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11091 // TODO: suggest replacing given type with expected type
11092 FD->setInvalidDecl(true);
11093 }
11094 }
11095
11096 if (nparams == 1 && !FD->isInvalidDecl()) {
11097 Diag(FD->getLocation(), diag::warn_main_one_arg);
11098 }
11099
11100 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11101 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11102 FD->setInvalidDecl();
11103 }
11104}
11105
11106void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11107 QualType T = FD->getType();
11108 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11108, __PRETTY_FUNCTION__))
;
11109 const FunctionType *FT = T->castAs<FunctionType>();
11110
11111 // Set an implicit return of 'zero' if the function can return some integral,
11112 // enumeration, pointer or nullptr type.
11113 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11114 FT->getReturnType()->isAnyPointerType() ||
11115 FT->getReturnType()->isNullPtrType())
11116 // DllMain is exempt because a return value of zero means it failed.
11117 if (FD->getName() != "DllMain")
11118 FD->setHasImplicitReturnZero(true);
11119
11120 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11121 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11122 FD->setInvalidDecl();
11123 }
11124}
11125
11126bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11127 // FIXME: Need strict checking. In C89, we need to check for
11128 // any assignment, increment, decrement, function-calls, or
11129 // commas outside of a sizeof. In C99, it's the same list,
11130 // except that the aforementioned are allowed in unevaluated
11131 // expressions. Everything else falls under the
11132 // "may accept other forms of constant expressions" exception.
11133 //
11134 // Regular C++ code will not end up here (exceptions: language extensions,
11135 // OpenCL C++ etc), so the constant expression rules there don't matter.
11136 if (Init->isValueDependent()) {
11137 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11138, __PRETTY_FUNCTION__))
11138 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11138, __PRETTY_FUNCTION__))
;
11139 return true;
11140 }
11141 const Expr *Culprit;
11142 if (Init->isConstantInitializer(Context, false, &Culprit))
11143 return false;
11144 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11145 << Culprit->getSourceRange();
11146 return true;
11147}
11148
11149namespace {
11150 // Visits an initialization expression to see if OrigDecl is evaluated in
11151 // its own initialization and throws a warning if it does.
11152 class SelfReferenceChecker
11153 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11154 Sema &S;
11155 Decl *OrigDecl;
11156 bool isRecordType;
11157 bool isPODType;
11158 bool isReferenceType;
11159
11160 bool isInitList;
11161 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11162
11163 public:
11164 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11165
11166 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11167 S(S), OrigDecl(OrigDecl) {
11168 isPODType = false;
11169 isRecordType = false;
11170 isReferenceType = false;
11171 isInitList = false;
11172 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11173 isPODType = VD->getType().isPODType(S.Context);
11174 isRecordType = VD->getType()->isRecordType();
11175 isReferenceType = VD->getType()->isReferenceType();
11176 }
11177 }
11178
11179 // For most expressions, just call the visitor. For initializer lists,
11180 // track the index of the field being initialized since fields are
11181 // initialized in order allowing use of previously initialized fields.
11182 void CheckExpr(Expr *E) {
11183 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11184 if (!InitList) {
11185 Visit(E);
11186 return;
11187 }
11188
11189 // Track and increment the index here.
11190 isInitList = true;
11191 InitFieldIndex.push_back(0);
11192 for (auto Child : InitList->children()) {
11193 CheckExpr(cast<Expr>(Child));
11194 ++InitFieldIndex.back();
11195 }
11196 InitFieldIndex.pop_back();
11197 }
11198
11199 // Returns true if MemberExpr is checked and no further checking is needed.
11200 // Returns false if additional checking is required.
11201 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11202 llvm::SmallVector<FieldDecl*, 4> Fields;
11203 Expr *Base = E;
11204 bool ReferenceField = false;
11205
11206 // Get the field members used.
11207 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11208 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11209 if (!FD)
11210 return false;
11211 Fields.push_back(FD);
11212 if (FD->getType()->isReferenceType())
11213 ReferenceField = true;
11214 Base = ME->getBase()->IgnoreParenImpCasts();
11215 }
11216
11217 // Keep checking only if the base Decl is the same.
11218 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11219 if (!DRE || DRE->getDecl() != OrigDecl)
11220 return false;
11221
11222 // A reference field can be bound to an unininitialized field.
11223 if (CheckReference && !ReferenceField)
11224 return true;
11225
11226 // Convert FieldDecls to their index number.
11227 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11228 for (const FieldDecl *I : llvm::reverse(Fields))
11229 UsedFieldIndex.push_back(I->getFieldIndex());
11230
11231 // See if a warning is needed by checking the first difference in index
11232 // numbers. If field being used has index less than the field being
11233 // initialized, then the use is safe.
11234 for (auto UsedIter = UsedFieldIndex.begin(),
11235 UsedEnd = UsedFieldIndex.end(),
11236 OrigIter = InitFieldIndex.begin(),
11237 OrigEnd = InitFieldIndex.end();
11238 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11239 if (*UsedIter < *OrigIter)
11240 return true;
11241 if (*UsedIter > *OrigIter)
11242 break;
11243 }
11244
11245 // TODO: Add a different warning which will print the field names.
11246 HandleDeclRefExpr(DRE);
11247 return true;
11248 }
11249
11250 // For most expressions, the cast is directly above the DeclRefExpr.
11251 // For conditional operators, the cast can be outside the conditional
11252 // operator if both expressions are DeclRefExpr's.
11253 void HandleValue(Expr *E) {
11254 E = E->IgnoreParens();
11255 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11256 HandleDeclRefExpr(DRE);
11257 return;
11258 }
11259
11260 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11261 Visit(CO->getCond());
11262 HandleValue(CO->getTrueExpr());
11263 HandleValue(CO->getFalseExpr());
11264 return;
11265 }
11266
11267 if (BinaryConditionalOperator *BCO =
11268 dyn_cast<BinaryConditionalOperator>(E)) {
11269 Visit(BCO->getCond());
11270 HandleValue(BCO->getFalseExpr());
11271 return;
11272 }
11273
11274 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11275 HandleValue(OVE->getSourceExpr());
11276 return;
11277 }
11278
11279 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11280 if (BO->getOpcode() == BO_Comma) {
11281 Visit(BO->getLHS());
11282 HandleValue(BO->getRHS());
11283 return;
11284 }
11285 }
11286
11287 if (isa<MemberExpr>(E)) {
11288 if (isInitList) {
11289 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11290 false /*CheckReference*/))
11291 return;
11292 }
11293
11294 Expr *Base = E->IgnoreParenImpCasts();
11295 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11296 // Check for static member variables and don't warn on them.
11297 if (!isa<FieldDecl>(ME->getMemberDecl()))
11298 return;
11299 Base = ME->getBase()->IgnoreParenImpCasts();
11300 }
11301 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11302 HandleDeclRefExpr(DRE);
11303 return;
11304 }
11305
11306 Visit(E);
11307 }
11308
11309 // Reference types not handled in HandleValue are handled here since all
11310 // uses of references are bad, not just r-value uses.
11311 void VisitDeclRefExpr(DeclRefExpr *E) {
11312 if (isReferenceType)
11313 HandleDeclRefExpr(E);
11314 }
11315
11316 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11317 if (E->getCastKind() == CK_LValueToRValue) {
11318 HandleValue(E->getSubExpr());
11319 return;
11320 }
11321
11322 Inherited::VisitImplicitCastExpr(E);
11323 }
11324
11325 void VisitMemberExpr(MemberExpr *E) {
11326 if (isInitList) {
11327 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11328 return;
11329 }
11330
11331 // Don't warn on arrays since they can be treated as pointers.
11332 if (E->getType()->canDecayToPointerType()) return;
11333
11334 // Warn when a non-static method call is followed by non-static member
11335 // field accesses, which is followed by a DeclRefExpr.
11336 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11337 bool Warn = (MD && !MD->isStatic());
11338 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11339 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11340 if (!isa<FieldDecl>(ME->getMemberDecl()))
11341 Warn = false;
11342 Base = ME->getBase()->IgnoreParenImpCasts();
11343 }
11344
11345 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11346 if (Warn)
11347 HandleDeclRefExpr(DRE);
11348 return;
11349 }
11350
11351 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11352 // Visit that expression.
11353 Visit(Base);
11354 }
11355
11356 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11357 Expr *Callee = E->getCallee();
11358
11359 if (isa<UnresolvedLookupExpr>(Callee))
11360 return Inherited::VisitCXXOperatorCallExpr(E);
11361
11362 Visit(Callee);
11363 for (auto Arg: E->arguments())
11364 HandleValue(Arg->IgnoreParenImpCasts());
11365 }
11366
11367 void VisitUnaryOperator(UnaryOperator *E) {
11368 // For POD record types, addresses of its own members are well-defined.
11369 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11370 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11371 if (!isPODType)
11372 HandleValue(E->getSubExpr());
11373 return;
11374 }
11375
11376 if (E->isIncrementDecrementOp()) {
11377 HandleValue(E->getSubExpr());
11378 return;
11379 }
11380
11381 Inherited::VisitUnaryOperator(E);
11382 }
11383
11384 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11385
11386 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11387 if (E->getConstructor()->isCopyConstructor()) {
11388 Expr *ArgExpr = E->getArg(0);
11389 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11390 if (ILE->getNumInits() == 1)
11391 ArgExpr = ILE->getInit(0);
11392 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11393 if (ICE->getCastKind() == CK_NoOp)
11394 ArgExpr = ICE->getSubExpr();
11395 HandleValue(ArgExpr);
11396 return;
11397 }
11398 Inherited::VisitCXXConstructExpr(E);
11399 }
11400
11401 void VisitCallExpr(CallExpr *E) {
11402 // Treat std::move as a use.
11403 if (E->isCallToStdMove()) {
11404 HandleValue(E->getArg(0));
11405 return;
11406 }
11407
11408 Inherited::VisitCallExpr(E);
11409 }
11410
11411 void VisitBinaryOperator(BinaryOperator *E) {
11412 if (E->isCompoundAssignmentOp()) {
11413 HandleValue(E->getLHS());
11414 Visit(E->getRHS());
11415 return;
11416 }
11417
11418 Inherited::VisitBinaryOperator(E);
11419 }
11420
11421 // A custom visitor for BinaryConditionalOperator is needed because the
11422 // regular visitor would check the condition and true expression separately
11423 // but both point to the same place giving duplicate diagnostics.
11424 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11425 Visit(E->getCond());
11426 Visit(E->getFalseExpr());
11427 }
11428
11429 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11430 Decl* ReferenceDecl = DRE->getDecl();
11431 if (OrigDecl != ReferenceDecl) return;
11432 unsigned diag;
11433 if (isReferenceType) {
11434 diag = diag::warn_uninit_self_reference_in_reference_init;
11435 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11436 diag = diag::warn_static_self_reference_in_init;
11437 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11438 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11439 DRE->getDecl()->getType()->isRecordType()) {
11440 diag = diag::warn_uninit_self_reference_in_init;
11441 } else {
11442 // Local variables will be handled by the CFG analysis.
11443 return;
11444 }
11445
11446 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11447 S.PDiag(diag)
11448 << DRE->getDecl() << OrigDecl->getLocation()
11449 << DRE->getSourceRange());
11450 }
11451 };
11452
11453 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11454 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11455 bool DirectInit) {
11456 // Parameters arguments are occassionially constructed with itself,
11457 // for instance, in recursive functions. Skip them.
11458 if (isa<ParmVarDecl>(OrigDecl))
11459 return;
11460
11461 E = E->IgnoreParens();
11462
11463 // Skip checking T a = a where T is not a record or reference type.
11464 // Doing so is a way to silence uninitialized warnings.
11465 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11466 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11467 if (ICE->getCastKind() == CK_LValueToRValue)
11468 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11469 if (DRE->getDecl() == OrigDecl)
11470 return;
11471
11472 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11473 }
11474} // end anonymous namespace
11475
11476namespace {
11477 // Simple wrapper to add the name of a variable or (if no variable is
11478 // available) a DeclarationName into a diagnostic.
11479 struct VarDeclOrName {
11480 VarDecl *VDecl;
11481 DeclarationName Name;
11482
11483 friend const Sema::SemaDiagnosticBuilder &
11484 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11485 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11486 }
11487 };
11488} // end anonymous namespace
11489
11490QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11491 DeclarationName Name, QualType Type,
11492 TypeSourceInfo *TSI,
11493 SourceRange Range, bool DirectInit,
11494 Expr *Init) {
11495 bool IsInitCapture = !VDecl;
11496 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11497, __PRETTY_FUNCTION__))
11497 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11497, __PRETTY_FUNCTION__))
;
11498
11499 VarDeclOrName VN{VDecl, Name};
11500
11501 DeducedType *Deduced = Type->getContainedDeducedType();
11502 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11502, __PRETTY_FUNCTION__))
;
11503
11504 // C++11 [dcl.spec.auto]p3
11505 if (!Init) {
11506 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11506, __PRETTY_FUNCTION__))
;
11507
11508 // Except for class argument deduction, and then for an initializing
11509 // declaration only, i.e. no static at class scope or extern.
11510 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11511 VDecl->hasExternalStorage() ||
11512 VDecl->isStaticDataMember()) {
11513 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11514 << VDecl->getDeclName() << Type;
11515 return QualType();
11516 }
11517 }
11518
11519 ArrayRef<Expr*> DeduceInits;
11520 if (Init)
11521 DeduceInits = Init;
11522
11523 if (DirectInit) {
11524 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11525 DeduceInits = PL->exprs();
11526 }
11527
11528 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11529 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11529, __PRETTY_FUNCTION__))
;
11530 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11531 InitializationKind Kind = InitializationKind::CreateForInit(
11532 VDecl->getLocation(), DirectInit, Init);
11533 // FIXME: Initialization should not be taking a mutable list of inits.
11534 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11535 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11536 InitsCopy);
11537 }
11538
11539 if (DirectInit) {
11540 if (auto *IL = dyn_cast<InitListExpr>(Init))
11541 DeduceInits = IL->inits();
11542 }
11543
11544 // Deduction only works if we have exactly one source expression.
11545 if (DeduceInits.empty()) {
11546 // It isn't possible to write this directly, but it is possible to
11547 // end up in this situation with "auto x(some_pack...);"
11548 Diag(Init->getBeginLoc(), IsInitCapture
11549 ? diag::err_init_capture_no_expression
11550 : diag::err_auto_var_init_no_expression)
11551 << VN << Type << Range;
11552 return QualType();
11553 }
11554
11555 if (DeduceInits.size() > 1) {
11556 Diag(DeduceInits[1]->getBeginLoc(),
11557 IsInitCapture ? diag::err_init_capture_multiple_expressions
11558 : diag::err_auto_var_init_multiple_expressions)
11559 << VN << Type << Range;
11560 return QualType();
11561 }
11562
11563 Expr *DeduceInit = DeduceInits[0];
11564 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11565 Diag(Init->getBeginLoc(), IsInitCapture
11566 ? diag::err_init_capture_paren_braces
11567 : diag::err_auto_var_init_paren_braces)
11568 << isa<InitListExpr>(Init) << VN << Type << Range;
11569 return QualType();
11570 }
11571
11572 // Expressions default to 'id' when we're in a debugger.
11573 bool DefaultedAnyToId = false;
11574 if (getLangOpts().DebuggerCastResultToId &&
11575 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11576 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11577 if (Result.isInvalid()) {
11578 return QualType();
11579 }
11580 Init = Result.get();
11581 DefaultedAnyToId = true;
11582 }
11583
11584 // C++ [dcl.decomp]p1:
11585 // If the assignment-expression [...] has array type A and no ref-qualifier
11586 // is present, e has type cv A
11587 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11588 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11589 DeduceInit->getType()->isConstantArrayType())
11590 return Context.getQualifiedType(DeduceInit->getType(),
11591 Type.getQualifiers());
11592
11593 QualType DeducedType;
11594 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11595 if (!IsInitCapture)
11596 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11597 else if (isa<InitListExpr>(Init))
11598 Diag(Range.getBegin(),
11599 diag::err_init_capture_deduction_failure_from_init_list)
11600 << VN
11601 << (DeduceInit->getType().isNull() ? TSI->getType()
11602 : DeduceInit->getType())
11603 << DeduceInit->getSourceRange();
11604 else
11605 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11606 << VN << TSI->getType()
11607 << (DeduceInit->getType().isNull() ? TSI->getType()
11608 : DeduceInit->getType())
11609 << DeduceInit->getSourceRange();
11610 }
11611
11612 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11613 // 'id' instead of a specific object type prevents most of our usual
11614 // checks.
11615 // We only want to warn outside of template instantiations, though:
11616 // inside a template, the 'id' could have come from a parameter.
11617 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11618 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11619 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11620 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11621 }
11622
11623 return DeducedType;
11624}
11625
11626bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11627 Expr *Init) {
11628 assert(!Init || !Init->containsErrors())((!Init || !Init->containsErrors()) ? static_cast<void>
(0) : __assert_fail ("!Init || !Init->containsErrors()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11628, __PRETTY_FUNCTION__))
;
11629 QualType DeducedType = deduceVarTypeFromInitializer(
11630 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11631 VDecl->getSourceRange(), DirectInit, Init);
11632 if (DeducedType.isNull()) {
11633 VDecl->setInvalidDecl();
11634 return true;
11635 }
11636
11637 VDecl->setType(DeducedType);
11638 assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) :
__assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11638, __PRETTY_FUNCTION__))
;
11639
11640 // In ARC, infer lifetime.
11641 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11642 VDecl->setInvalidDecl();
11643
11644 if (getLangOpts().OpenCL)
11645 deduceOpenCLAddressSpace(VDecl);
11646
11647 // If this is a redeclaration, check that the type we just deduced matches
11648 // the previously declared type.
11649 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11650 // We never need to merge the type, because we cannot form an incomplete
11651 // array of auto, nor deduce such a type.
11652 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11653 }
11654
11655 // Check the deduced type is valid for a variable declaration.
11656 CheckVariableDeclarationType(VDecl);
11657 return VDecl->isInvalidDecl();
11658}
11659
11660void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11661 SourceLocation Loc) {
11662 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11663 Init = EWC->getSubExpr();
11664
11665 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11666 Init = CE->getSubExpr();
11667
11668 QualType InitType = Init->getType();
11669 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11671, __PRETTY_FUNCTION__))
11670 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11671, __PRETTY_FUNCTION__))
11671 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11671, __PRETTY_FUNCTION__))
;
11672 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11673 for (auto I : ILE->inits()) {
11674 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11675 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11676 continue;
11677 SourceLocation SL = I->getExprLoc();
11678 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11679 }
11680 return;
11681 }
11682
11683 if (isa<ImplicitValueInitExpr>(Init)) {
11684 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11685 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11686 NTCUK_Init);
11687 } else {
11688 // Assume all other explicit initializers involving copying some existing
11689 // object.
11690 // TODO: ignore any explicit initializers where we can guarantee
11691 // copy-elision.
11692 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11693 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11694 }
11695}
11696
11697namespace {
11698
11699bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11700 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11701 // in the source code or implicitly by the compiler if it is in a union
11702 // defined in a system header and has non-trivial ObjC ownership
11703 // qualifications. We don't want those fields to participate in determining
11704 // whether the containing union is non-trivial.
11705 return FD->hasAttr<UnavailableAttr>();
11706}
11707
11708struct DiagNonTrivalCUnionDefaultInitializeVisitor
11709 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11710 void> {
11711 using Super =
11712 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11713 void>;
11714
11715 DiagNonTrivalCUnionDefaultInitializeVisitor(
11716 QualType OrigTy, SourceLocation OrigLoc,
11717 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11718 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11719
11720 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11721 const FieldDecl *FD, bool InNonTrivialUnion) {
11722 if (const auto *AT = S.Context.getAsArrayType(QT))
11723 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11724 InNonTrivialUnion);
11725 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11726 }
11727
11728 void visitARCStrong(QualType QT, const FieldDecl *FD,
11729 bool InNonTrivialUnion) {
11730 if (InNonTrivialUnion)
11731 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11732 << 1 << 0 << QT << FD->getName();
11733 }
11734
11735 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11736 if (InNonTrivialUnion)
11737 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11738 << 1 << 0 << QT << FD->getName();
11739 }
11740
11741 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11742 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11743 if (RD->isUnion()) {
11744 if (OrigLoc.isValid()) {
11745 bool IsUnion = false;
11746 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11747 IsUnion = OrigRD->isUnion();
11748 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11749 << 0 << OrigTy << IsUnion << UseContext;
11750 // Reset OrigLoc so that this diagnostic is emitted only once.
11751 OrigLoc = SourceLocation();
11752 }
11753 InNonTrivialUnion = true;
11754 }
11755
11756 if (InNonTrivialUnion)
11757 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11758 << 0 << 0 << QT.getUnqualifiedType() << "";
11759
11760 for (const FieldDecl *FD : RD->fields())
11761 if (!shouldIgnoreForRecordTriviality(FD))
11762 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11763 }
11764
11765 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11766
11767 // The non-trivial C union type or the struct/union type that contains a
11768 // non-trivial C union.
11769 QualType OrigTy;
11770 SourceLocation OrigLoc;
11771 Sema::NonTrivialCUnionContext UseContext;
11772 Sema &S;
11773};
11774
11775struct DiagNonTrivalCUnionDestructedTypeVisitor
11776 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11777 using Super =
11778 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11779
11780 DiagNonTrivalCUnionDestructedTypeVisitor(
11781 QualType OrigTy, SourceLocation OrigLoc,
11782 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11783 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11784
11785 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11786 const FieldDecl *FD, bool InNonTrivialUnion) {
11787 if (const auto *AT = S.Context.getAsArrayType(QT))
11788 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11789 InNonTrivialUnion);
11790 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11791 }
11792
11793 void visitARCStrong(QualType QT, const FieldDecl *FD,
11794 bool InNonTrivialUnion) {
11795 if (InNonTrivialUnion)
11796 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11797 << 1 << 1 << QT << FD->getName();
11798 }
11799
11800 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11801 if (InNonTrivialUnion)
11802 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11803 << 1 << 1 << QT << FD->getName();
11804 }
11805
11806 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11807 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11808 if (RD->isUnion()) {
11809 if (OrigLoc.isValid()) {
11810 bool IsUnion = false;
11811 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11812 IsUnion = OrigRD->isUnion();
11813 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11814 << 1 << OrigTy << IsUnion << UseContext;
11815 // Reset OrigLoc so that this diagnostic is emitted only once.
11816 OrigLoc = SourceLocation();
11817 }
11818 InNonTrivialUnion = true;
11819 }
11820
11821 if (InNonTrivialUnion)
11822 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11823 << 0 << 1 << QT.getUnqualifiedType() << "";
11824
11825 for (const FieldDecl *FD : RD->fields())
11826 if (!shouldIgnoreForRecordTriviality(FD))
11827 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11828 }
11829
11830 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11831 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11832 bool InNonTrivialUnion) {}
11833
11834 // The non-trivial C union type or the struct/union type that contains a
11835 // non-trivial C union.
11836 QualType OrigTy;
11837 SourceLocation OrigLoc;
11838 Sema::NonTrivialCUnionContext UseContext;
11839 Sema &S;
11840};
11841
11842struct DiagNonTrivalCUnionCopyVisitor
11843 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11844 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11845
11846 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11847 Sema::NonTrivialCUnionContext UseContext,
11848 Sema &S)
11849 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11850
11851 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11852 const FieldDecl *FD, bool InNonTrivialUnion) {
11853 if (const auto *AT = S.Context.getAsArrayType(QT))
11854 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11855 InNonTrivialUnion);
11856 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11857 }
11858
11859 void visitARCStrong(QualType QT, const FieldDecl *FD,
11860 bool InNonTrivialUnion) {
11861 if (InNonTrivialUnion)
11862 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11863 << 1 << 2 << QT << FD->getName();
11864 }
11865
11866 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11867 if (InNonTrivialUnion)
11868 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11869 << 1 << 2 << QT << FD->getName();
11870 }
11871
11872 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11873 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11874 if (RD->isUnion()) {
11875 if (OrigLoc.isValid()) {
11876 bool IsUnion = false;
11877 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11878 IsUnion = OrigRD->isUnion();
11879 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11880 << 2 << OrigTy << IsUnion << UseContext;
11881 // Reset OrigLoc so that this diagnostic is emitted only once.
11882 OrigLoc = SourceLocation();
11883 }
11884 InNonTrivialUnion = true;
11885 }
11886
11887 if (InNonTrivialUnion)
11888 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11889 << 0 << 2 << QT.getUnqualifiedType() << "";
11890
11891 for (const FieldDecl *FD : RD->fields())
11892 if (!shouldIgnoreForRecordTriviality(FD))
11893 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11894 }
11895
11896 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11897 const FieldDecl *FD, bool InNonTrivialUnion) {}
11898 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11899 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11900 bool InNonTrivialUnion) {}
11901
11902 // The non-trivial C union type or the struct/union type that contains a
11903 // non-trivial C union.
11904 QualType OrigTy;
11905 SourceLocation OrigLoc;
11906 Sema::NonTrivialCUnionContext UseContext;
11907 Sema &S;
11908};
11909
11910} // namespace
11911
11912void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11913 NonTrivialCUnionContext UseContext,
11914 unsigned NonTrivialKind) {
11915 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11918, __PRETTY_FUNCTION__))
11916 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11918, __PRETTY_FUNCTION__))
11917 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11918, __PRETTY_FUNCTION__))
11918 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11918, __PRETTY_FUNCTION__))
;
11919
11920 if ((NonTrivialKind & NTCUK_Init) &&
11921 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11922 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11923 .visit(QT, nullptr, false);
11924 if ((NonTrivialKind & NTCUK_Destruct) &&
11925 QT.hasNonTrivialToPrimitiveDestructCUnion())
11926 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11927 .visit(QT, nullptr, false);
11928 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11929 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11930 .visit(QT, nullptr, false);
11931}
11932
11933/// AddInitializerToDecl - Adds the initializer Init to the
11934/// declaration dcl. If DirectInit is true, this is C++ direct
11935/// initialization rather than copy initialization.
11936void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11937 // If there is no declaration, there was an error parsing it. Just ignore
11938 // the initializer.
11939 if (!RealDecl || RealDecl->isInvalidDecl()) {
11940 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11941 return;
11942 }
11943
11944 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11945 // Pure-specifiers are handled in ActOnPureSpecifier.
11946 Diag(Method->getLocation(), diag::err_member_function_initialization)
11947 << Method->getDeclName() << Init->getSourceRange();
11948 Method->setInvalidDecl();
11949 return;
11950 }
11951
11952 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11953 if (!VDecl) {
11954 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 11954, __PRETTY_FUNCTION__))
;
11955 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11956 RealDecl->setInvalidDecl();
11957 return;
11958 }
11959
11960 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11961 if (VDecl->getType()->isUndeducedType()) {
11962 // Attempt typo correction early so that the type of the init expression can
11963 // be deduced based on the chosen correction if the original init contains a
11964 // TypoExpr.
11965 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11966 if (!Res.isUsable()) {
11967 // There are unresolved typos in Init, just drop them.
11968 // FIXME: improve the recovery strategy to preserve the Init.
11969 RealDecl->setInvalidDecl();
11970 return;
11971 }
11972 if (Res.get()->containsErrors()) {
11973 // Invalidate the decl as we don't know the type for recovery-expr yet.
11974 RealDecl->setInvalidDecl();
11975 VDecl->setInit(Res.get());
11976 return;
11977 }
11978 Init = Res.get();
11979
11980 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
11981 return;
11982 }
11983
11984 // dllimport cannot be used on variable definitions.
11985 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11986 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11987 VDecl->setInvalidDecl();
11988 return;
11989 }
11990
11991 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11992 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11993 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11994 VDecl->setInvalidDecl();
11995 return;
11996 }
11997
11998 if (!VDecl->getType()->isDependentType()) {
11999 // A definition must end up with a complete type, which means it must be
12000 // complete with the restriction that an array type might be completed by
12001 // the initializer; note that later code assumes this restriction.
12002 QualType BaseDeclType = VDecl->getType();
12003 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12004 BaseDeclType = Array->getElementType();
12005 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12006 diag::err_typecheck_decl_incomplete_type)) {
12007 RealDecl->setInvalidDecl();
12008 return;
12009 }
12010
12011 // The variable can not have an abstract class type.
12012 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12013 diag::err_abstract_type_in_decl,
12014 AbstractVariableType))
12015 VDecl->setInvalidDecl();
12016 }
12017
12018 // If adding the initializer will turn this declaration into a definition,
12019 // and we already have a definition for this variable, diagnose or otherwise
12020 // handle the situation.
12021 VarDecl *Def;
12022 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12023 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12024 !VDecl->isThisDeclarationADemotedDefinition() &&
12025 checkVarDeclRedefinition(Def, VDecl))
12026 return;
12027
12028 if (getLangOpts().CPlusPlus) {
12029 // C++ [class.static.data]p4
12030 // If a static data member is of const integral or const
12031 // enumeration type, its declaration in the class definition can
12032 // specify a constant-initializer which shall be an integral
12033 // constant expression (5.19). In that case, the member can appear
12034 // in integral constant expressions. The member shall still be
12035 // defined in a namespace scope if it is used in the program and the
12036 // namespace scope definition shall not contain an initializer.
12037 //
12038 // We already performed a redefinition check above, but for static
12039 // data members we also need to check whether there was an in-class
12040 // declaration with an initializer.
12041 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12042 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12043 << VDecl->getDeclName();
12044 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12045 diag::note_previous_initializer)
12046 << 0;
12047 return;
12048 }
12049
12050 if (VDecl->hasLocalStorage())
12051 setFunctionHasBranchProtectedScope();
12052
12053 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12054 VDecl->setInvalidDecl();
12055 return;
12056 }
12057 }
12058
12059 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12060 // a kernel function cannot be initialized."
12061 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12062 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12063 VDecl->setInvalidDecl();
12064 return;
12065 }
12066
12067 // The LoaderUninitialized attribute acts as a definition (of undef).
12068 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12069 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12070 VDecl->setInvalidDecl();
12071 return;
12072 }
12073
12074 // Get the decls type and save a reference for later, since
12075 // CheckInitializerTypes may change it.
12076 QualType DclT = VDecl->getType(), SavT = DclT;
12077
12078 // Expressions default to 'id' when we're in a debugger
12079 // and we are assigning it to a variable of Objective-C pointer type.
12080 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12081 Init->getType() == Context.UnknownAnyTy) {
12082 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12083 if (Result.isInvalid()) {
12084 VDecl->setInvalidDecl();
12085 return;
12086 }
12087 Init = Result.get();
12088 }
12089
12090 // Perform the initialization.
12091 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12092 if (!VDecl->isInvalidDecl()) {
12093 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12094 InitializationKind Kind = InitializationKind::CreateForInit(
12095 VDecl->getLocation(), DirectInit, Init);
12096
12097 MultiExprArg Args = Init;
12098 if (CXXDirectInit)
12099 Args = MultiExprArg(CXXDirectInit->getExprs(),
12100 CXXDirectInit->getNumExprs());
12101
12102 // Try to correct any TypoExprs in the initialization arguments.
12103 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12104 ExprResult Res = CorrectDelayedTyposInExpr(
12105 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12106 [this, Entity, Kind](Expr *E) {
12107 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12108 return Init.Failed() ? ExprError() : E;
12109 });
12110 if (Res.isInvalid()) {
12111 VDecl->setInvalidDecl();
12112 } else if (Res.get() != Args[Idx]) {
12113 Args[Idx] = Res.get();
12114 }
12115 }
12116 if (VDecl->isInvalidDecl())
12117 return;
12118
12119 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12120 /*TopLevelOfInitList=*/false,
12121 /*TreatUnavailableAsInvalid=*/false);
12122 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12123 if (Result.isInvalid()) {
12124 // If the provied initializer fails to initialize the var decl,
12125 // we attach a recovery expr for better recovery.
12126 auto RecoveryExpr =
12127 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12128 if (RecoveryExpr.get())
12129 VDecl->setInit(RecoveryExpr.get());
12130 return;
12131 }
12132
12133 Init = Result.getAs<Expr>();
12134 }
12135
12136 // Check for self-references within variable initializers.
12137 // Variables declared within a function/method body (except for references)
12138 // are handled by a dataflow analysis.
12139 // This is undefined behavior in C++, but valid in C.
12140 if (getLangOpts().CPlusPlus) {
12141 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12142 VDecl->getType()->isReferenceType()) {
12143 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12144 }
12145 }
12146
12147 // If the type changed, it means we had an incomplete type that was
12148 // completed by the initializer. For example:
12149 // int ary[] = { 1, 3, 5 };
12150 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12151 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12152 VDecl->setType(DclT);
12153
12154 if (!VDecl->isInvalidDecl()) {
12155 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12156
12157 if (VDecl->hasAttr<BlocksAttr>())
12158 checkRetainCycles(VDecl, Init);
12159
12160 // It is safe to assign a weak reference into a strong variable.
12161 // Although this code can still have problems:
12162 // id x = self.weakProp;
12163 // id y = self.weakProp;
12164 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12165 // paths through the function. This should be revisited if
12166 // -Wrepeated-use-of-weak is made flow-sensitive.
12167 if (FunctionScopeInfo *FSI = getCurFunction())
12168 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12169 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12170 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12171 Init->getBeginLoc()))
12172 FSI->markSafeWeakUse(Init);
12173 }
12174
12175 // The initialization is usually a full-expression.
12176 //
12177 // FIXME: If this is a braced initialization of an aggregate, it is not
12178 // an expression, and each individual field initializer is a separate
12179 // full-expression. For instance, in:
12180 //
12181 // struct Temp { ~Temp(); };
12182 // struct S { S(Temp); };
12183 // struct T { S a, b; } t = { Temp(), Temp() }
12184 //
12185 // we should destroy the first Temp before constructing the second.
12186 ExprResult Result =
12187 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12188 /*DiscardedValue*/ false, VDecl->isConstexpr());
12189 if (Result.isInvalid()) {
12190 VDecl->setInvalidDecl();
12191 return;
12192 }
12193 Init = Result.get();
12194
12195 // Attach the initializer to the decl.
12196 VDecl->setInit(Init);
12197
12198 if (VDecl->isLocalVarDecl()) {
12199 // Don't check the initializer if the declaration is malformed.
12200 if (VDecl->isInvalidDecl()) {
12201 // do nothing
12202
12203 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12204 // This is true even in C++ for OpenCL.
12205 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12206 CheckForConstantInitializer(Init, DclT);
12207
12208 // Otherwise, C++ does not restrict the initializer.
12209 } else if (getLangOpts().CPlusPlus) {
12210 // do nothing
12211
12212 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12213 // static storage duration shall be constant expressions or string literals.
12214 } else if (VDecl->getStorageClass() == SC_Static) {
12215 CheckForConstantInitializer(Init, DclT);
12216
12217 // C89 is stricter than C99 for aggregate initializers.
12218 // C89 6.5.7p3: All the expressions [...] in an initializer list
12219 // for an object that has aggregate or union type shall be
12220 // constant expressions.
12221 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12222 isa<InitListExpr>(Init)) {
12223 const Expr *Culprit;
12224 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12225 Diag(Culprit->getExprLoc(),
12226 diag::ext_aggregate_init_not_constant)
12227 << Culprit->getSourceRange();
12228 }
12229 }
12230
12231 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12232 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12233 if (VDecl->hasLocalStorage())
12234 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12235 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12236 VDecl->getLexicalDeclContext()->isRecord()) {
12237 // This is an in-class initialization for a static data member, e.g.,
12238 //
12239 // struct S {
12240 // static const int value = 17;
12241 // };
12242
12243 // C++ [class.mem]p4:
12244 // A member-declarator can contain a constant-initializer only
12245 // if it declares a static member (9.4) of const integral or
12246 // const enumeration type, see 9.4.2.
12247 //
12248 // C++11 [class.static.data]p3:
12249 // If a non-volatile non-inline const static data member is of integral
12250 // or enumeration type, its declaration in the class definition can
12251 // specify a brace-or-equal-initializer in which every initializer-clause
12252 // that is an assignment-expression is a constant expression. A static
12253 // data member of literal type can be declared in the class definition
12254 // with the constexpr specifier; if so, its declaration shall specify a
12255 // brace-or-equal-initializer in which every initializer-clause that is
12256 // an assignment-expression is a constant expression.
12257
12258 // Do nothing on dependent types.
12259 if (DclT->isDependentType()) {
12260
12261 // Allow any 'static constexpr' members, whether or not they are of literal
12262 // type. We separately check that every constexpr variable is of literal
12263 // type.
12264 } else if (VDecl->isConstexpr()) {
12265
12266 // Require constness.
12267 } else if (!DclT.isConstQualified()) {
12268 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12269 << Init->getSourceRange();
12270 VDecl->setInvalidDecl();
12271
12272 // We allow integer constant expressions in all cases.
12273 } else if (DclT->isIntegralOrEnumerationType()) {
12274 // Check whether the expression is a constant expression.
12275 SourceLocation Loc;
12276 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12277 // In C++11, a non-constexpr const static data member with an
12278 // in-class initializer cannot be volatile.
12279 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12280 else if (Init->isValueDependent())
12281 ; // Nothing to check.
12282 else if (Init->isIntegerConstantExpr(Context, &Loc))
12283 ; // Ok, it's an ICE!
12284 else if (Init->getType()->isScopedEnumeralType() &&
12285 Init->isCXX11ConstantExpr(Context))
12286 ; // Ok, it is a scoped-enum constant expression.
12287 else if (Init->isEvaluatable(Context)) {
12288 // If we can constant fold the initializer through heroics, accept it,
12289 // but report this as a use of an extension for -pedantic.
12290 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12291 << Init->getSourceRange();
12292 } else {
12293 // Otherwise, this is some crazy unknown case. Report the issue at the
12294 // location provided by the isIntegerConstantExpr failed check.
12295 Diag(Loc, diag::err_in_class_initializer_non_constant)
12296 << Init->getSourceRange();
12297 VDecl->setInvalidDecl();
12298 }
12299
12300 // We allow foldable floating-point constants as an extension.
12301 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12302 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12303 // it anyway and provide a fixit to add the 'constexpr'.
12304 if (getLangOpts().CPlusPlus11) {
12305 Diag(VDecl->getLocation(),
12306 diag::ext_in_class_initializer_float_type_cxx11)
12307 << DclT << Init->getSourceRange();
12308 Diag(VDecl->getBeginLoc(),
12309 diag::note_in_class_initializer_float_type_cxx11)
12310 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12311 } else {
12312 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12313 << DclT << Init->getSourceRange();
12314
12315 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12316 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12317 << Init->getSourceRange();
12318 VDecl->setInvalidDecl();
12319 }
12320 }
12321
12322 // Suggest adding 'constexpr' in C++11 for literal types.
12323 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12324 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12325 << DclT << Init->getSourceRange()
12326 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12327 VDecl->setConstexpr(true);
12328
12329 } else {
12330 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12331 << DclT << Init->getSourceRange();
12332 VDecl->setInvalidDecl();
12333 }
12334 } else if (VDecl->isFileVarDecl()) {
12335 // In C, extern is typically used to avoid tentative definitions when
12336 // declaring variables in headers, but adding an intializer makes it a
12337 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12338 // In C++, extern is often used to give implictly static const variables
12339 // external linkage, so don't warn in that case. If selectany is present,
12340 // this might be header code intended for C and C++ inclusion, so apply the
12341 // C++ rules.
12342 if (VDecl->getStorageClass() == SC_Extern &&
12343 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12344 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12345 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12346 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12347 Diag(VDecl->getLocation(), diag::warn_extern_init);
12348
12349 // In Microsoft C++ mode, a const variable defined in namespace scope has
12350 // external linkage by default if the variable is declared with
12351 // __declspec(dllexport).
12352 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12353 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12354 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12355 VDecl->setStorageClass(SC_Extern);
12356
12357 // C99 6.7.8p4. All file scoped initializers need to be constant.
12358 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12359 CheckForConstantInitializer(Init, DclT);
12360 }
12361
12362 QualType InitType = Init->getType();
12363 if (!InitType.isNull() &&
12364 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12365 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12366 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12367
12368 // We will represent direct-initialization similarly to copy-initialization:
12369 // int x(1); -as-> int x = 1;
12370 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12371 //
12372 // Clients that want to distinguish between the two forms, can check for
12373 // direct initializer using VarDecl::getInitStyle().
12374 // A major benefit is that clients that don't particularly care about which
12375 // exactly form was it (like the CodeGen) can handle both cases without
12376 // special case code.
12377
12378 // C++ 8.5p11:
12379 // The form of initialization (using parentheses or '=') is generally
12380 // insignificant, but does matter when the entity being initialized has a
12381 // class type.
12382 if (CXXDirectInit) {
12383 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 12383, __PRETTY_FUNCTION__))
;
12384 VDecl->setInitStyle(VarDecl::CallInit);
12385 } else if (DirectInit) {
12386 // This must be list-initialization. No other way is direct-initialization.
12387 VDecl->setInitStyle(VarDecl::ListInit);
12388 }
12389
12390 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12391 DeclsToCheckForDeferredDiags.push_back(VDecl);
12392 CheckCompleteVariableDeclaration(VDecl);
12393}
12394
12395/// ActOnInitializerError - Given that there was an error parsing an
12396/// initializer for the given declaration, try to return to some form
12397/// of sanity.
12398void Sema::ActOnInitializerError(Decl *D) {
12399 // Our main concern here is re-establishing invariants like "a
12400 // variable's type is either dependent or complete".
12401 if (!D || D->isInvalidDecl()) return;
12402
12403 VarDecl *VD = dyn_cast<VarDecl>(D);
12404 if (!VD) return;
12405
12406 // Bindings are not usable if we can't make sense of the initializer.
12407 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12408 for (auto *BD : DD->bindings())
12409 BD->setInvalidDecl();
12410
12411 // Auto types are meaningless if we can't make sense of the initializer.
12412 if (VD->getType()->isUndeducedType()) {
12413 D->setInvalidDecl();
12414 return;
12415 }
12416
12417 QualType Ty = VD->getType();
12418 if (Ty->isDependentType()) return;
12419
12420 // Require a complete type.
12421 if (RequireCompleteType(VD->getLocation(),
12422 Context.getBaseElementType(Ty),
12423 diag::err_typecheck_decl_incomplete_type)) {
12424 VD->setInvalidDecl();
12425 return;
12426 }
12427
12428 // Require a non-abstract type.
12429 if (RequireNonAbstractType(VD->getLocation(), Ty,
12430 diag::err_abstract_type_in_decl,
12431 AbstractVariableType)) {
12432 VD->setInvalidDecl();
12433 return;
12434 }
12435
12436 // Don't bother complaining about constructors or destructors,
12437 // though.
12438}
12439
12440void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12441 // If there is no declaration, there was an error parsing it. Just ignore it.
12442 if (!RealDecl)
12443 return;
12444
12445 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12446 QualType Type = Var->getType();
12447
12448 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12449 if (isa<DecompositionDecl>(RealDecl)) {
12450 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12451 Var->setInvalidDecl();
12452 return;
12453 }
12454
12455 if (Type->isUndeducedType() &&
12456 DeduceVariableDeclarationType(Var, false, nullptr))
12457 return;
12458
12459 // C++11 [class.static.data]p3: A static data member can be declared with
12460 // the constexpr specifier; if so, its declaration shall specify
12461 // a brace-or-equal-initializer.
12462 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12463 // the definition of a variable [...] or the declaration of a static data
12464 // member.
12465 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12466 !Var->isThisDeclarationADemotedDefinition()) {
12467 if (Var->isStaticDataMember()) {
12468 // C++1z removes the relevant rule; the in-class declaration is always
12469 // a definition there.
12470 if (!getLangOpts().CPlusPlus17 &&
12471 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12472 Diag(Var->getLocation(),
12473 diag::err_constexpr_static_mem_var_requires_init)
12474 << Var;
12475 Var->setInvalidDecl();
12476 return;
12477 }
12478 } else {
12479 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12480 Var->setInvalidDecl();
12481 return;
12482 }
12483 }
12484
12485 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12486 // be initialized.
12487 if (!Var->isInvalidDecl() &&
12488 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12489 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12490 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12491 Var->setInvalidDecl();
12492 return;
12493 }
12494
12495 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12496 if (Var->getStorageClass() == SC_Extern) {
12497 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12498 << Var;
12499 Var->setInvalidDecl();
12500 return;
12501 }
12502 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12503 diag::err_typecheck_decl_incomplete_type)) {
12504 Var->setInvalidDecl();
12505 return;
12506 }
12507 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12508 if (!RD->hasTrivialDefaultConstructor()) {
12509 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12510 Var->setInvalidDecl();
12511 return;
12512 }
12513 }
12514 }
12515
12516 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12517 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12518 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12519 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12520 NTCUC_DefaultInitializedObject, NTCUK_Init);
12521
12522
12523 switch (DefKind) {
12524 case VarDecl::Definition:
12525 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12526 break;
12527
12528 // We have an out-of-line definition of a static data member
12529 // that has an in-class initializer, so we type-check this like
12530 // a declaration.
12531 //
12532 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12533
12534 case VarDecl::DeclarationOnly:
12535 // It's only a declaration.
12536
12537 // Block scope. C99 6.7p7: If an identifier for an object is
12538 // declared with no linkage (C99 6.2.2p6), the type for the
12539 // object shall be complete.
12540 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12541 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12542 RequireCompleteType(Var->getLocation(), Type,
12543 diag::err_typecheck_decl_incomplete_type))
12544 Var->setInvalidDecl();
12545
12546 // Make sure that the type is not abstract.
12547 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12548 RequireNonAbstractType(Var->getLocation(), Type,
12549 diag::err_abstract_type_in_decl,
12550 AbstractVariableType))
12551 Var->setInvalidDecl();
12552 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12553 Var->getStorageClass() == SC_PrivateExtern) {
12554 Diag(Var->getLocation(), diag::warn_private_extern);
12555 Diag(Var->getLocation(), diag::note_private_extern);
12556 }
12557
12558 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12559 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12560 ExternalDeclarations.push_back(Var);
12561
12562 return;
12563
12564 case VarDecl::TentativeDefinition:
12565 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12566 // object that has file scope without an initializer, and without a
12567 // storage-class specifier or with the storage-class specifier "static",
12568 // constitutes a tentative definition. Note: A tentative definition with
12569 // external linkage is valid (C99 6.2.2p5).
12570 if (!Var->isInvalidDecl()) {
12571 if (const IncompleteArrayType *ArrayT
12572 = Context.getAsIncompleteArrayType(Type)) {
12573 if (RequireCompleteSizedType(
12574 Var->getLocation(), ArrayT->getElementType(),
12575 diag::err_array_incomplete_or_sizeless_type))
12576 Var->setInvalidDecl();
12577 } else if (Var->getStorageClass() == SC_Static) {
12578 // C99 6.9.2p3: If the declaration of an identifier for an object is
12579 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12580 // declared type shall not be an incomplete type.
12581 // NOTE: code such as the following
12582 // static struct s;
12583 // struct s { int a; };
12584 // is accepted by gcc. Hence here we issue a warning instead of
12585 // an error and we do not invalidate the static declaration.
12586 // NOTE: to avoid multiple warnings, only check the first declaration.
12587 if (Var->isFirstDecl())
12588 RequireCompleteType(Var->getLocation(), Type,
12589 diag::ext_typecheck_decl_incomplete_type);
12590 }
12591 }
12592
12593 // Record the tentative definition; we're done.
12594 if (!Var->isInvalidDecl())
12595 TentativeDefinitions.push_back(Var);
12596 return;
12597 }
12598
12599 // Provide a specific diagnostic for uninitialized variable
12600 // definitions with incomplete array type.
12601 if (Type->isIncompleteArrayType()) {
12602 Diag(Var->getLocation(),
12603 diag::err_typecheck_incomplete_array_needs_initializer);
12604 Var->setInvalidDecl();
12605 return;
12606 }
12607
12608 // Provide a specific diagnostic for uninitialized variable
12609 // definitions with reference type.
12610 if (Type->isReferenceType()) {
12611 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12612 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12613 Var->setInvalidDecl();
12614 return;
12615 }
12616
12617 // Do not attempt to type-check the default initializer for a
12618 // variable with dependent type.
12619 if (Type->isDependentType())
12620 return;
12621
12622 if (Var->isInvalidDecl())
12623 return;
12624
12625 if (!Var->hasAttr<AliasAttr>()) {
12626 if (RequireCompleteType(Var->getLocation(),
12627 Context.getBaseElementType(Type),
12628 diag::err_typecheck_decl_incomplete_type)) {
12629 Var->setInvalidDecl();
12630 return;
12631 }
12632 } else {
12633 return;
12634 }
12635
12636 // The variable can not have an abstract class type.
12637 if (RequireNonAbstractType(Var->getLocation(), Type,
12638 diag::err_abstract_type_in_decl,
12639 AbstractVariableType)) {
12640 Var->setInvalidDecl();
12641 return;
12642 }
12643
12644 // Check for jumps past the implicit initializer. C++0x
12645 // clarifies that this applies to a "variable with automatic
12646 // storage duration", not a "local variable".
12647 // C++11 [stmt.dcl]p3
12648 // A program that jumps from a point where a variable with automatic
12649 // storage duration is not in scope to a point where it is in scope is
12650 // ill-formed unless the variable has scalar type, class type with a
12651 // trivial default constructor and a trivial destructor, a cv-qualified
12652 // version of one of these types, or an array of one of the preceding
12653 // types and is declared without an initializer.
12654 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12655 if (const RecordType *Record
12656 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12657 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12658 // Mark the function (if we're in one) for further checking even if the
12659 // looser rules of C++11 do not require such checks, so that we can
12660 // diagnose incompatibilities with C++98.
12661 if (!CXXRecord->isPOD())
12662 setFunctionHasBranchProtectedScope();
12663 }
12664 }
12665 // In OpenCL, we can't initialize objects in the __local address space,
12666 // even implicitly, so don't synthesize an implicit initializer.
12667 if (getLangOpts().OpenCL &&
12668 Var->getType().getAddressSpace() == LangAS::opencl_local)
12669 return;
12670 // C++03 [dcl.init]p9:
12671 // If no initializer is specified for an object, and the
12672 // object is of (possibly cv-qualified) non-POD class type (or
12673 // array thereof), the object shall be default-initialized; if
12674 // the object is of const-qualified type, the underlying class
12675 // type shall have a user-declared default
12676 // constructor. Otherwise, if no initializer is specified for
12677 // a non- static object, the object and its subobjects, if
12678 // any, have an indeterminate initial value); if the object
12679 // or any of its subobjects are of const-qualified type, the
12680 // program is ill-formed.
12681 // C++0x [dcl.init]p11:
12682 // If no initializer is specified for an object, the object is
12683 // default-initialized; [...].
12684 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12685 InitializationKind Kind
12686 = InitializationKind::CreateDefault(Var->getLocation());
12687
12688 InitializationSequence InitSeq(*this, Entity, Kind, None);
12689 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12690
12691 if (Init.get()) {
12692 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12693 // This is important for template substitution.
12694 Var->setInitStyle(VarDecl::CallInit);
12695 } else if (Init.isInvalid()) {
12696 // If default-init fails, attach a recovery-expr initializer to track
12697 // that initialization was attempted and failed.
12698 auto RecoveryExpr =
12699 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12700 if (RecoveryExpr.get())
12701 Var->setInit(RecoveryExpr.get());
12702 }
12703
12704 CheckCompleteVariableDeclaration(Var);
12705 }
12706}
12707
12708void Sema::ActOnCXXForRangeDecl(Decl *D) {
12709 // If there is no declaration, there was an error parsing it. Ignore it.
12710 if (!D)
12711 return;
12712
12713 VarDecl *VD = dyn_cast<VarDecl>(D);
12714 if (!VD) {
12715 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12716 D->setInvalidDecl();
12717 return;
12718 }
12719
12720 VD->setCXXForRangeDecl(true);
12721
12722 // for-range-declaration cannot be given a storage class specifier.
12723 int Error = -1;
12724 switch (VD->getStorageClass()) {
12725 case SC_None:
12726 break;
12727 case SC_Extern:
12728 Error = 0;
12729 break;
12730 case SC_Static:
12731 Error = 1;
12732 break;
12733 case SC_PrivateExtern:
12734 Error = 2;
12735 break;
12736 case SC_Auto:
12737 Error = 3;
12738 break;
12739 case SC_Register:
12740 Error = 4;
12741 break;
12742 }
12743 if (Error != -1) {
12744 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12745 << VD << Error;
12746 D->setInvalidDecl();
12747 }
12748}
12749
12750StmtResult
12751Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12752 IdentifierInfo *Ident,
12753 ParsedAttributes &Attrs,
12754 SourceLocation AttrEnd) {
12755 // C++1y [stmt.iter]p1:
12756 // A range-based for statement of the form
12757 // for ( for-range-identifier : for-range-initializer ) statement
12758 // is equivalent to
12759 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12760 DeclSpec DS(Attrs.getPool().getFactory());
12761
12762 const char *PrevSpec;
12763 unsigned DiagID;
12764 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12765 getPrintingPolicy());
12766
12767 Declarator D(DS, DeclaratorContext::ForContext);
12768 D.SetIdentifier(Ident, IdentLoc);
12769 D.takeAttributes(Attrs, AttrEnd);
12770
12771 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12772 IdentLoc);
12773 Decl *Var = ActOnDeclarator(S, D);
12774 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12775 FinalizeDeclaration(Var);
12776 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12777 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12778}
12779
12780void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12781 if (var->isInvalidDecl()) return;
12782
12783 if (getLangOpts().OpenCL) {
12784 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12785 // initialiser
12786 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12787 !var->hasInit()) {
12788 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12789 << 1 /*Init*/;
12790 var->setInvalidDecl();
12791 return;
12792 }
12793 }
12794
12795 // In Objective-C, don't allow jumps past the implicit initialization of a
12796 // local retaining variable.
12797 if (getLangOpts().ObjC &&
12798 var->hasLocalStorage()) {
12799 switch (var->getType().getObjCLifetime()) {
12800 case Qualifiers::OCL_None:
12801 case Qualifiers::OCL_ExplicitNone:
12802 case Qualifiers::OCL_Autoreleasing:
12803 break;
12804
12805 case Qualifiers::OCL_Weak:
12806 case Qualifiers::OCL_Strong:
12807 setFunctionHasBranchProtectedScope();
12808 break;
12809 }
12810 }
12811
12812 if (var->hasLocalStorage() &&
12813 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12814 setFunctionHasBranchProtectedScope();
12815
12816 // Warn about externally-visible variables being defined without a
12817 // prior declaration. We only want to do this for global
12818 // declarations, but we also specifically need to avoid doing it for
12819 // class members because the linkage of an anonymous class can
12820 // change if it's later given a typedef name.
12821 if (var->isThisDeclarationADefinition() &&
12822 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12823 var->isExternallyVisible() && var->hasLinkage() &&
12824 !var->isInline() && !var->getDescribedVarTemplate() &&
12825 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12826 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12827 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12828 var->getLocation())) {
12829 // Find a previous declaration that's not a definition.
12830 VarDecl *prev = var->getPreviousDecl();
12831 while (prev && prev->isThisDeclarationADefinition())
12832 prev = prev->getPreviousDecl();
12833
12834 if (!prev) {
12835 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12836 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12837 << /* variable */ 0;
12838 }
12839 }
12840
12841 // Cache the result of checking for constant initialization.
12842 Optional<bool> CacheHasConstInit;
12843 const Expr *CacheCulprit = nullptr;
12844 auto checkConstInit = [&]() mutable {
12845 if (!CacheHasConstInit)
12846 CacheHasConstInit = var->getInit()->isConstantInitializer(
12847 Context, var->getType()->isReferenceType(), &CacheCulprit);
12848 return *CacheHasConstInit;
12849 };
12850
12851 if (var->getTLSKind() == VarDecl::TLS_Static) {
12852 if (var->getType().isDestructedType()) {
12853 // GNU C++98 edits for __thread, [basic.start.term]p3:
12854 // The type of an object with thread storage duration shall not
12855 // have a non-trivial destructor.
12856 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12857 if (getLangOpts().CPlusPlus11)
12858 Diag(var->getLocation(), diag::note_use_thread_local);
12859 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12860 if (!checkConstInit()) {
12861 // GNU C++98 edits for __thread, [basic.start.init]p4:
12862 // An object of thread storage duration shall not require dynamic
12863 // initialization.
12864 // FIXME: Need strict checking here.
12865 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12866 << CacheCulprit->getSourceRange();
12867 if (getLangOpts().CPlusPlus11)
12868 Diag(var->getLocation(), diag::note_use_thread_local);
12869 }
12870 }
12871 }
12872
12873 // Apply section attributes and pragmas to global variables.
12874 bool GlobalStorage = var->hasGlobalStorage();
12875 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12876 !inTemplateInstantiation()) {
12877 PragmaStack<StringLiteral *> *Stack = nullptr;
12878 int SectionFlags = ASTContext::PSF_Read;
12879 if (var->getType().isConstQualified())
12880 Stack = &ConstSegStack;
12881 else if (!var->getInit()) {
12882 Stack = &BSSSegStack;
12883 SectionFlags |= ASTContext::PSF_Write;
12884 } else {
12885 Stack = &DataSegStack;
12886 SectionFlags |= ASTContext::PSF_Write;
12887 }
12888 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12889 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12890 SectionFlags |= ASTContext::PSF_Implicit;
12891 UnifySection(SA->getName(), SectionFlags, var);
12892 } else if (Stack->CurrentValue) {
12893 SectionFlags |= ASTContext::PSF_Implicit;
12894 auto SectionName = Stack->CurrentValue->getString();
12895 var->addAttr(SectionAttr::CreateImplicit(
12896 Context, SectionName, Stack->CurrentPragmaLocation,
12897 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12898 if (UnifySection(SectionName, SectionFlags, var))
12899 var->dropAttr<SectionAttr>();
12900 }
12901
12902 // Apply the init_seg attribute if this has an initializer. If the
12903 // initializer turns out to not be dynamic, we'll end up ignoring this
12904 // attribute.
12905 if (CurInitSeg && var->getInit())
12906 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12907 CurInitSegLoc,
12908 AttributeCommonInfo::AS_Pragma));
12909 }
12910
12911 if (!var->getType()->isStructureType() && var->hasInit() &&
12912 isa<InitListExpr>(var->getInit())) {
12913 const auto *ILE = cast<InitListExpr>(var->getInit());
12914 unsigned NumInits = ILE->getNumInits();
12915 if (NumInits > 2)
12916 for (unsigned I = 0; I < NumInits; ++I) {
12917 const auto *Init = ILE->getInit(I);
12918 if (!Init)
12919 break;
12920 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12921 if (!SL)
12922 break;
12923
12924 unsigned NumConcat = SL->getNumConcatenated();
12925 // Diagnose missing comma in string array initialization.
12926 // Do not warn when all the elements in the initializer are concatenated
12927 // together. Do not warn for macros too.
12928 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12929 bool OnlyOneMissingComma = true;
12930 for (unsigned J = I + 1; J < NumInits; ++J) {
12931 const auto *Init = ILE->getInit(J);
12932 if (!Init)
12933 break;
12934 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12935 if (!SLJ || SLJ->getNumConcatenated() > 1) {
12936 OnlyOneMissingComma = false;
12937 break;
12938 }
12939 }
12940
12941 if (OnlyOneMissingComma) {
12942 SmallVector<FixItHint, 1> Hints;
12943 for (unsigned i = 0; i < NumConcat - 1; ++i)
12944 Hints.push_back(FixItHint::CreateInsertion(
12945 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12946
12947 Diag(SL->getStrTokenLoc(1),
12948 diag::warn_concatenated_literal_array_init)
12949 << Hints;
12950 Diag(SL->getBeginLoc(),
12951 diag::note_concatenated_string_literal_silence);
12952 }
12953 // In any case, stop now.
12954 break;
12955 }
12956 }
12957 }
12958
12959 // All the following checks are C++ only.
12960 if (!getLangOpts().CPlusPlus) {
12961 // If this variable must be emitted, add it as an initializer for the
12962 // current module.
12963 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12964 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12965 return;
12966 }
12967
12968 QualType type = var->getType();
12969
12970 if (var->hasAttr<BlocksAttr>())
12971 getCurFunction()->addByrefBlockVar(var);
12972
12973 Expr *Init = var->getInit();
12974 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12975 QualType baseType = Context.getBaseElementType(type);
12976
12977 // Check whether the initializer is sufficiently constant.
12978 if (!type->isDependentType() && Init && !Init->isValueDependent() &&
12979 (GlobalStorage || var->isConstexpr() ||
12980 var->mightBeUsableInConstantExpressions(Context))) {
12981 // If this variable might have a constant initializer or might be usable in
12982 // constant expressions, check whether or not it actually is now. We can't
12983 // do this lazily, because the result might depend on things that change
12984 // later, such as which constexpr functions happen to be defined.
12985 SmallVector<PartialDiagnosticAt, 8> Notes;
12986 bool HasConstInit;
12987 if (!getLangOpts().CPlusPlus11) {
12988 // Prior to C++11, in contexts where a constant initializer is required,
12989 // the set of valid constant initializers is described by syntactic rules
12990 // in [expr.const]p2-6.
12991 // FIXME: Stricter checking for these rules would be useful for constinit /
12992 // -Wglobal-constructors.
12993 HasConstInit = checkConstInit();
12994
12995 // Compute and cache the constant value, and remember that we have a
12996 // constant initializer.
12997 if (HasConstInit) {
12998 (void)var->checkForConstantInitialization(Notes);
12999 Notes.clear();
13000 } else if (CacheCulprit) {
13001 Notes.emplace_back(CacheCulprit->getExprLoc(),
13002 PDiag(diag::note_invalid_subexpr_in_const_expr));
13003 Notes.back().second << CacheCulprit->getSourceRange();
13004 }
13005 } else {
13006 // Evaluate the initializer to see if it's a constant initializer.
13007 HasConstInit = var->checkForConstantInitialization(Notes);
13008 }
13009
13010 if (HasConstInit) {
13011 // FIXME: Consider replacing the initializer with a ConstantExpr.
13012 } else if (var->isConstexpr()) {
13013 SourceLocation DiagLoc = var->getLocation();
13014 // If the note doesn't add any useful information other than a source
13015 // location, fold it into the primary diagnostic.
13016 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13017 diag::note_invalid_subexpr_in_const_expr) {
13018 DiagLoc = Notes[0].first;
13019 Notes.clear();
13020 }
13021 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13022 << var << Init->getSourceRange();
13023 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13024 Diag(Notes[I].first, Notes[I].second);
13025 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13026 auto *Attr = var->getAttr<ConstInitAttr>();
13027 Diag(var->getLocation(), diag::err_require_constant_init_failed)
13028 << Init->getSourceRange();
13029 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13030 << Attr->getRange() << Attr->isConstinit();
13031 for (auto &it : Notes)
13032 Diag(it.first, it.second);
13033 } else if (IsGlobal &&
13034 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13035 var->getLocation())) {
13036 // Warn about globals which don't have a constant initializer. Don't
13037 // warn about globals with a non-trivial destructor because we already
13038 // warned about them.
13039 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13040 if (!(RD && !RD->hasTrivialDestructor())) {
13041 // checkConstInit() here permits trivial default initialization even in
13042 // C++11 onwards, where such an initializer is not a constant initializer
13043 // but nonetheless doesn't require a global constructor.
13044 if (!checkConstInit())
13045 Diag(var->getLocation(), diag::warn_global_constructor)
13046 << Init->getSourceRange();
13047 }
13048 }
13049 }
13050
13051 // Require the destructor.
13052 if (!type->isDependentType())
13053 if (const RecordType *recordType = baseType->getAs<RecordType>())
13054 FinalizeVarWithDestructor(var, recordType);
13055
13056 // If this variable must be emitted, add it as an initializer for the current
13057 // module.
13058 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13059 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13060
13061 // Build the bindings if this is a structured binding declaration.
13062 if (auto *DD = dyn_cast<DecompositionDecl>(var))
13063 CheckCompleteDecompositionDeclaration(DD);
13064}
13065
13066/// Determines if a variable's alignment is dependent.
13067static bool hasDependentAlignment(VarDecl *VD) {
13068 if (VD->getType()->isDependentType())
13069 return true;
13070 for (auto *I : VD->specific_attrs<AlignedAttr>())
13071 if (I->isAlignmentDependent())
13072 return true;
13073 return false;
13074}
13075
13076/// Check if VD needs to be dllexport/dllimport due to being in a
13077/// dllexport/import function.
13078void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13079 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 13079, __PRETTY_FUNCTION__))
;
13080
13081 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13082
13083 // Find outermost function when VD is in lambda function.
13084 while (FD && !getDLLAttr(FD) &&
13085 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13086 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13087 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13088 }
13089
13090 if (!FD)
13091 return;
13092
13093 // Static locals inherit dll attributes from their function.
13094 if (Attr *A = getDLLAttr(FD)) {
13095 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13096 NewAttr->setInherited(true);
13097 VD->addAttr(NewAttr);
13098 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13099 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13100 NewAttr->setInherited(true);
13101 VD->addAttr(NewAttr);
13102
13103 // Export this function to enforce exporting this static variable even
13104 // if it is not used in this compilation unit.
13105 if (!FD->hasAttr<DLLExportAttr>())
13106 FD->addAttr(NewAttr);
13107
13108 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13109 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13110 NewAttr->setInherited(true);
13111 VD->addAttr(NewAttr);
13112 }
13113}
13114
13115/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13116/// any semantic actions necessary after any initializer has been attached.
13117void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13118 // Note that we are no longer parsing the initializer for this declaration.
13119 ParsingInitForAutoVars.erase(ThisDecl);
13120
13121 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13122 if (!VD)
13123 return;
13124
13125 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13126 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13127 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13128 if (PragmaClangBSSSection.Valid)
13129 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13130 Context, PragmaClangBSSSection.SectionName,
13131 PragmaClangBSSSection.PragmaLocation,
13132 AttributeCommonInfo::AS_Pragma));
13133 if (PragmaClangDataSection.Valid)
13134 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13135 Context, PragmaClangDataSection.SectionName,
13136 PragmaClangDataSection.PragmaLocation,
13137 AttributeCommonInfo::AS_Pragma));
13138 if (PragmaClangRodataSection.Valid)
13139 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13140 Context, PragmaClangRodataSection.SectionName,
13141 PragmaClangRodataSection.PragmaLocation,
13142 AttributeCommonInfo::AS_Pragma));
13143 if (PragmaClangRelroSection.Valid)
13144 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13145 Context, PragmaClangRelroSection.SectionName,
13146 PragmaClangRelroSection.PragmaLocation,
13147 AttributeCommonInfo::AS_Pragma));
13148 }
13149
13150 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13151 for (auto *BD : DD->bindings()) {
13152 FinalizeDeclaration(BD);
13153 }
13154 }
13155
13156 checkAttributesAfterMerging(*this, *VD);
13157
13158 // Perform TLS alignment check here after attributes attached to the variable
13159 // which may affect the alignment have been processed. Only perform the check
13160 // if the target has a maximum TLS alignment (zero means no constraints).
13161 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13162 // Protect the check so that it's not performed on dependent types and
13163 // dependent alignments (we can't determine the alignment in that case).
13164 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13165 !VD->isInvalidDecl()) {
13166 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13167 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13168 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13169 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13170 << (unsigned)MaxAlignChars.getQuantity();
13171 }
13172 }
13173 }
13174
13175 if (VD->isStaticLocal()) {
13176 CheckStaticLocalForDllExport(VD);
13177
13178 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13179 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13180 // function, only __shared__ variables or variables without any device
13181 // memory qualifiers may be declared with static storage class.
13182 // Note: It is unclear how a function-scope non-const static variable
13183 // without device memory qualifier is implemented, therefore only static
13184 // const variable without device memory qualifier is allowed.
13185 [&]() {
13186 if (!getLangOpts().CUDA)
13187 return;
13188 if (VD->hasAttr<CUDASharedAttr>())
13189 return;
13190 if (VD->getType().isConstQualified() &&
13191 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13192 return;
13193 if (CUDADiagIfDeviceCode(VD->getLocation(),
13194 diag::err_device_static_local_var)
13195 << CurrentCUDATarget())
13196 VD->setInvalidDecl();
13197 }();
13198 }
13199 }
13200
13201 // Perform check for initializers of device-side global variables.
13202 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13203 // 7.5). We must also apply the same checks to all __shared__
13204 // variables whether they are local or not. CUDA also allows
13205 // constant initializers for __constant__ and __device__ variables.
13206 if (getLangOpts().CUDA)
13207 checkAllowedCUDAInitializer(VD);
13208
13209 // Grab the dllimport or dllexport attribute off of the VarDecl.
13210 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13211
13212 // Imported static data members cannot be defined out-of-line.
13213 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13214 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13215 VD->isThisDeclarationADefinition()) {
13216 // We allow definitions of dllimport class template static data members
13217 // with a warning.
13218 CXXRecordDecl *Context =
13219 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13220 bool IsClassTemplateMember =
13221 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13222 Context->getDescribedClassTemplate();
13223
13224 Diag(VD->getLocation(),
13225 IsClassTemplateMember
13226 ? diag::warn_attribute_dllimport_static_field_definition
13227 : diag::err_attribute_dllimport_static_field_definition);
13228 Diag(IA->getLocation(), diag::note_attribute);
13229 if (!IsClassTemplateMember)
13230 VD->setInvalidDecl();
13231 }
13232 }
13233
13234 // dllimport/dllexport variables cannot be thread local, their TLS index
13235 // isn't exported with the variable.
13236 if (DLLAttr && VD->getTLSKind()) {
13237 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13238 if (F && getDLLAttr(F)) {
13239 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 13239, __PRETTY_FUNCTION__))
;
13240 // But if this is a static local in a dlimport/dllexport function, the
13241 // function will never be inlined, which means the var would never be
13242 // imported, so having it marked import/export is safe.
13243 } else {
13244 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13245 << DLLAttr;
13246 VD->setInvalidDecl();
13247 }
13248 }
13249
13250 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13251 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13252 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13253 VD->dropAttr<UsedAttr>();
13254 }
13255 }
13256
13257 const DeclContext *DC = VD->getDeclContext();
13258 // If there's a #pragma GCC visibility in scope, and this isn't a class
13259 // member, set the visibility of this variable.
13260 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13261 AddPushedVisibilityAttribute(VD);
13262
13263 // FIXME: Warn on unused var template partial specializations.
13264 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13265 MarkUnusedFileScopedDecl(VD);
13266
13267 // Now we have parsed the initializer and can update the table of magic
13268 // tag values.
13269 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13270 !VD->getType()->isIntegralOrEnumerationType())
13271 return;
13272
13273 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13274 const Expr *MagicValueExpr = VD->getInit();
13275 if (!MagicValueExpr) {
13276 continue;
13277 }
13278 Optional<llvm::APSInt> MagicValueInt;
13279 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13280 Diag(I->getRange().getBegin(),
13281 diag::err_type_tag_for_datatype_not_ice)
13282 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13283 continue;
13284 }
13285 if (MagicValueInt->getActiveBits() > 64) {
13286 Diag(I->getRange().getBegin(),
13287 diag::err_type_tag_for_datatype_too_large)
13288 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13289 continue;
13290 }
13291 uint64_t MagicValue = MagicValueInt->getZExtValue();
13292 RegisterTypeTagForDatatype(I->getArgumentKind(),
13293 MagicValue,
13294 I->getMatchingCType(),
13295 I->getLayoutCompatible(),
13296 I->getMustBeNull());
13297 }
13298}
13299
13300static bool hasDeducedAuto(DeclaratorDecl *DD) {
13301 auto *VD = dyn_cast<VarDecl>(DD);
13302 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13303}
13304
13305Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13306 ArrayRef<Decl *> Group) {
13307 SmallVector<Decl*, 8> Decls;
13308
13309 if (DS.isTypeSpecOwned())
13310 Decls.push_back(DS.getRepAsDecl());
13311
13312 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13313 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13314 bool DiagnosedMultipleDecomps = false;
13315 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13316 bool DiagnosedNonDeducedAuto = false;
13317
13318 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13319 if (Decl *D = Group[i]) {
13320 // For declarators, there are some additional syntactic-ish checks we need
13321 // to perform.
13322 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13323 if (!FirstDeclaratorInGroup)
13324 FirstDeclaratorInGroup = DD;
13325 if (!FirstDecompDeclaratorInGroup)
13326 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13327 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13328 !hasDeducedAuto(DD))
13329 FirstNonDeducedAutoInGroup = DD;
13330
13331 if (FirstDeclaratorInGroup != DD) {
13332 // A decomposition declaration cannot be combined with any other
13333 // declaration in the same group.
13334 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13335 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13336 diag::err_decomp_decl_not_alone)
13337 << FirstDeclaratorInGroup->getSourceRange()
13338 << DD->getSourceRange();
13339 DiagnosedMultipleDecomps = true;
13340 }
13341
13342 // A declarator that uses 'auto' in any way other than to declare a
13343 // variable with a deduced type cannot be combined with any other
13344 // declarator in the same group.
13345 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13346 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13347 diag::err_auto_non_deduced_not_alone)
13348 << FirstNonDeducedAutoInGroup->getType()
13349 ->hasAutoForTrailingReturnType()
13350 << FirstDeclaratorInGroup->getSourceRange()
13351 << DD->getSourceRange();
13352 DiagnosedNonDeducedAuto = true;
13353 }
13354 }
13355 }
13356
13357 Decls.push_back(D);
13358 }
13359 }
13360
13361 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13362 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13363 handleTagNumbering(Tag, S);
13364 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13365 getLangOpts().CPlusPlus)
13366 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13367 }
13368 }
13369
13370 return BuildDeclaratorGroup(Decls);
13371}
13372
13373/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13374/// group, performing any necessary semantic checking.
13375Sema::DeclGroupPtrTy
13376Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13377 // C++14 [dcl.spec.auto]p7: (DR1347)
13378 // If the type that replaces the placeholder type is not the same in each
13379 // deduction, the program is ill-formed.
13380 if (Group.size() > 1) {
13381 QualType Deduced;
13382 VarDecl *DeducedDecl = nullptr;
13383 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13384 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13385 if (!D || D->isInvalidDecl())
13386 break;
13387 DeducedType *DT = D->getType()->getContainedDeducedType();
13388 if (!DT || DT->getDeducedType().isNull())
13389 continue;
13390 if (Deduced.isNull()) {
13391 Deduced = DT->getDeducedType();
13392 DeducedDecl = D;
13393 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13394 auto *AT = dyn_cast<AutoType>(DT);
13395 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13396 diag::err_auto_different_deductions)
13397 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13398 << DeducedDecl->getDeclName() << DT->getDeducedType()
13399 << D->getDeclName();
13400 if (DeducedDecl->hasInit())
13401 Dia << DeducedDecl->getInit()->getSourceRange();
13402 if (D->getInit())
13403 Dia << D->getInit()->getSourceRange();
13404 D->setInvalidDecl();
13405 break;
13406 }
13407 }
13408 }
13409
13410 ActOnDocumentableDecls(Group);
13411
13412 return DeclGroupPtrTy::make(
13413 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13414}
13415
13416void Sema::ActOnDocumentableDecl(Decl *D) {
13417 ActOnDocumentableDecls(D);
13418}
13419
13420void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13421 // Don't parse the comment if Doxygen diagnostics are ignored.
13422 if (Group.empty() || !Group[0])
13423 return;
13424
13425 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13426 Group[0]->getLocation()) &&
13427 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13428 Group[0]->getLocation()))
13429 return;
13430
13431 if (Group.size() >= 2) {
13432 // This is a decl group. Normally it will contain only declarations
13433 // produced from declarator list. But in case we have any definitions or
13434 // additional declaration references:
13435 // 'typedef struct S {} S;'
13436 // 'typedef struct S *S;'
13437 // 'struct S *pS;'
13438 // FinalizeDeclaratorGroup adds these as separate declarations.
13439 Decl *MaybeTagDecl = Group[0];
13440 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13441 Group = Group.slice(1);
13442 }
13443 }
13444
13445 // FIMXE: We assume every Decl in the group is in the same file.
13446 // This is false when preprocessor constructs the group from decls in
13447 // different files (e. g. macros or #include).
13448 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13449}
13450
13451/// Common checks for a parameter-declaration that should apply to both function
13452/// parameters and non-type template parameters.
13453void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13454 // Check that there are no default arguments inside the type of this
13455 // parameter.
13456 if (getLangOpts().CPlusPlus)
13457 CheckExtraCXXDefaultArguments(D);
13458
13459 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13460 if (D.getCXXScopeSpec().isSet()) {
13461 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13462 << D.getCXXScopeSpec().getRange();
13463 }
13464
13465 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13466 // simple identifier except [...irrelevant cases...].
13467 switch (D.getName().getKind()) {
13468 case UnqualifiedIdKind::IK_Identifier:
13469 break;
13470
13471 case UnqualifiedIdKind::IK_OperatorFunctionId:
13472 case UnqualifiedIdKind::IK_ConversionFunctionId:
13473 case UnqualifiedIdKind::IK_LiteralOperatorId:
13474 case UnqualifiedIdKind::IK_ConstructorName:
13475 case UnqualifiedIdKind::IK_DestructorName:
13476 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13477 case UnqualifiedIdKind::IK_DeductionGuideName:
13478 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13479 << GetNameForDeclarator(D).getName();
13480 break;
13481
13482 case UnqualifiedIdKind::IK_TemplateId:
13483 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13484 // GetNameForDeclarator would not produce a useful name in this case.
13485 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13486 break;
13487 }
13488}
13489
13490/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13491/// to introduce parameters into function prototype scope.
13492Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13493 const DeclSpec &DS = D.getDeclSpec();
13494
13495 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13496
13497 // C++03 [dcl.stc]p2 also permits 'auto'.
13498 StorageClass SC = SC_None;
13499 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13500 SC = SC_Register;
13501 // In C++11, the 'register' storage class specifier is deprecated.
13502 // In C++17, it is not allowed, but we tolerate it as an extension.
13503 if (getLangOpts().CPlusPlus11) {
13504 Diag(DS.getStorageClassSpecLoc(),
13505 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13506 : diag::warn_deprecated_register)
13507 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13508 }
13509 } else if (getLangOpts().CPlusPlus &&
13510 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13511 SC = SC_Auto;
13512 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13513 Diag(DS.getStorageClassSpecLoc(),
13514 diag::err_invalid_storage_class_in_func_decl);
13515 D.getMutableDeclSpec().ClearStorageClassSpecs();
13516 }
13517
13518 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13519 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13520 << DeclSpec::getSpecifierName(TSCS);
13521 if (DS.isInlineSpecified())
13522 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13523 << getLangOpts().CPlusPlus17;
13524 if (DS.hasConstexprSpecifier())
13525 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13526 << 0 << D.getDeclSpec().getConstexprSpecifier();
13527
13528 DiagnoseFunctionSpecifiers(DS);
13529
13530 CheckFunctionOrTemplateParamDeclarator(S, D);
13531
13532 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13533 QualType parmDeclType = TInfo->getType();
13534
13535 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13536 IdentifierInfo *II = D.getIdentifier();
13537 if (II) {
13538 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13539 ForVisibleRedeclaration);
13540 LookupName(R, S);
13541 if (R.isSingleResult()) {
13542 NamedDecl *PrevDecl = R.getFoundDecl();
13543 if (PrevDecl->isTemplateParameter()) {
13544 // Maybe we will complain about the shadowed template parameter.
13545 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13546 // Just pretend that we didn't see the previous declaration.
13547 PrevDecl = nullptr;
13548 } else if (S->isDeclScope(PrevDecl)) {
13549 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13550 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13551
13552 // Recover by removing the name
13553 II = nullptr;
13554 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13555 D.setInvalidType(true);
13556 }
13557 }
13558 }
13559
13560 // Temporarily put parameter variables in the translation unit, not
13561 // the enclosing context. This prevents them from accidentally
13562 // looking like class members in C++.
13563 ParmVarDecl *New =
13564 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13565 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13566
13567 if (D.isInvalidType())
13568 New->setInvalidDecl();
13569
13570 assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void>
(0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 13570, __PRETTY_FUNCTION__))
;
13571 assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast<
void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 13571, __PRETTY_FUNCTION__))
;
13572 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13573 S->getNextFunctionPrototypeIndex());
13574
13575 // Add the parameter declaration into this scope.
13576 S->AddDecl(New);
13577 if (II)
13578 IdResolver.AddDecl(New);
13579
13580 ProcessDeclAttributes(S, New, D);
13581
13582 if (D.getDeclSpec().isModulePrivateSpecified())
13583 Diag(New->getLocation(), diag::err_module_private_local)
13584 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13585 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13586
13587 if (New->hasAttr<BlocksAttr>()) {
13588 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13589 }
13590
13591 if (getLangOpts().OpenCL)
13592 deduceOpenCLAddressSpace(New);
13593
13594 return New;
13595}
13596
13597/// Synthesizes a variable for a parameter arising from a
13598/// typedef.
13599ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13600 SourceLocation Loc,
13601 QualType T) {
13602 /* FIXME: setting StartLoc == Loc.
13603 Would it be worth to modify callers so as to provide proper source
13604 location for the unnamed parameters, embedding the parameter's type? */
13605 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13606 T, Context.getTrivialTypeSourceInfo(T, Loc),
13607 SC_None, nullptr);
13608 Param->setImplicit();
13609 return Param;
13610}
13611
13612void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13613 // Don't diagnose unused-parameter errors in template instantiations; we
13614 // will already have done so in the template itself.
13615 if (inTemplateInstantiation())
13616 return;
13617
13618 for (const ParmVarDecl *Parameter : Parameters) {
13619 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13620 !Parameter->hasAttr<UnusedAttr>()) {
13621 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13622 << Parameter->getDeclName();
13623 }
13624 }
13625}
13626
13627void Sema::DiagnoseSizeOfParametersAndReturnValue(
13628 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13629 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13630 return;
13631
13632 // Warn if the return value is pass-by-value and larger than the specified
13633 // threshold.
13634 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13635 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13636 if (Size > LangOpts.NumLargeByValueCopy)
13637 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13638 }
13639
13640 // Warn if any parameter is pass-by-value and larger than the specified
13641 // threshold.
13642 for (const ParmVarDecl *Parameter : Parameters) {
13643 QualType T = Parameter->getType();
13644 if (T->isDependentType() || !T.isPODType(Context))
13645 continue;
13646 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13647 if (Size > LangOpts.NumLargeByValueCopy)
13648 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13649 << Parameter << Size;
13650 }
13651}
13652
13653ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13654 SourceLocation NameLoc, IdentifierInfo *Name,
13655 QualType T, TypeSourceInfo *TSInfo,
13656 StorageClass SC) {
13657 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13658 if (getLangOpts().ObjCAutoRefCount &&
13659 T.getObjCLifetime() == Qualifiers::OCL_None &&
13660 T->isObjCLifetimeType()) {
13661
13662 Qualifiers::ObjCLifetime lifetime;
13663
13664 // Special cases for arrays:
13665 // - if it's const, use __unsafe_unretained
13666 // - otherwise, it's an error
13667 if (T->isArrayType()) {
13668 if (!T.isConstQualified()) {
13669 if (DelayedDiagnostics.shouldDelayDiagnostics())
13670 DelayedDiagnostics.add(
13671 sema::DelayedDiagnostic::makeForbiddenType(
13672 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13673 else
13674 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13675 << TSInfo->getTypeLoc().getSourceRange();
13676 }
13677 lifetime = Qualifiers::OCL_ExplicitNone;
13678 } else {
13679 lifetime = T->getObjCARCImplicitLifetime();
13680 }
13681 T = Context.getLifetimeQualifiedType(T, lifetime);
13682 }
13683
13684 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13685 Context.getAdjustedParameterType(T),
13686 TSInfo, SC, nullptr);
13687
13688 // Make a note if we created a new pack in the scope of a lambda, so that
13689 // we know that references to that pack must also be expanded within the
13690 // lambda scope.
13691 if (New->isParameterPack())
13692 if (auto *LSI = getEnclosingLambda())
13693 LSI->LocalPacks.push_back(New);
13694
13695 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13696 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13697 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13698 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13699
13700 // Parameters can not be abstract class types.
13701 // For record types, this is done by the AbstractClassUsageDiagnoser once
13702 // the class has been completely parsed.
13703 if (!CurContext->isRecord() &&
13704 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13705 AbstractParamType))
13706 New->setInvalidDecl();
13707
13708 // Parameter declarators cannot be interface types. All ObjC objects are
13709 // passed by reference.
13710 if (T->isObjCObjectType()) {
13711 SourceLocation TypeEndLoc =
13712 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13713 Diag(NameLoc,
13714 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13715 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13716 T = Context.getObjCObjectPointerType(T);
13717 New->setType(T);
13718 }
13719
13720 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13721 // duration shall not be qualified by an address-space qualifier."
13722 // Since all parameters have automatic store duration, they can not have
13723 // an address space.
13724 if (T.getAddressSpace() != LangAS::Default &&
13725 // OpenCL allows function arguments declared to be an array of a type
13726 // to be qualified with an address space.
13727 !(getLangOpts().OpenCL &&
13728 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13729 Diag(NameLoc, diag::err_arg_with_address_space);
13730 New->setInvalidDecl();
13731 }
13732
13733 return New;
13734}
13735
13736void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13737 SourceLocation LocAfterDecls) {
13738 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13739
13740 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13741 // for a K&R function.
13742 if (!FTI.hasPrototype) {
13743 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13744 --i;
13745 if (FTI.Params[i].Param == nullptr) {
13746 SmallString<256> Code;
13747 llvm::raw_svector_ostream(Code)
13748 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13749 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13750 << FTI.Params[i].Ident
13751 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13752
13753 // Implicitly declare the argument as type 'int' for lack of a better
13754 // type.
13755 AttributeFactory attrs;
13756 DeclSpec DS(attrs);
13757 const char* PrevSpec; // unused
13758 unsigned DiagID; // unused
13759 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13760 DiagID, Context.getPrintingPolicy());
13761 // Use the identifier location for the type source range.
13762 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13763 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13764 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13765 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13766 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13767 }
13768 }
13769 }
13770}
13771
13772Decl *
13773Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13774 MultiTemplateParamsArg TemplateParameterLists,
13775 SkipBodyInfo *SkipBody) {
13776 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 13776, __PRETTY_FUNCTION__))
;
13777 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 13777, __PRETTY_FUNCTION__))
;
13778 Scope *ParentScope = FnBodyScope->getParent();
13779
13780 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13781 // we define a non-templated function definition, we will create a declaration
13782 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13783 // The base function declaration will have the equivalent of an `omp declare
13784 // variant` annotation which specifies the mangled definition as a
13785 // specialization function under the OpenMP context defined as part of the
13786 // `omp begin declare variant`.
13787 SmallVector<FunctionDecl *, 4> Bases;
13788 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13789 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13790 ParentScope, D, TemplateParameterLists, Bases);
13791
13792 D.setFunctionDefinitionKind(FDK_Definition);
13793 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13794 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13795
13796 if (!Bases.empty())
13797 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13798
13799 return Dcl;
13800}
13801
13802void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13803 Consumer.HandleInlineFunctionDefinition(D);
13804}
13805
13806static bool
13807ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13808 const FunctionDecl *&PossiblePrototype) {
13809 // Don't warn about invalid declarations.
13810 if (FD->isInvalidDecl())
13811 return false;
13812
13813 // Or declarations that aren't global.
13814 if (!FD->isGlobal())
13815 return false;
13816
13817 // Don't warn about C++ member functions.
13818 if (isa<CXXMethodDecl>(FD))
13819 return false;
13820
13821 // Don't warn about 'main'.
13822 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13823 if (IdentifierInfo *II = FD->getIdentifier())
13824 if (II->isStr("main"))
13825 return false;
13826
13827 // Don't warn about inline functions.
13828 if (FD->isInlined())
13829 return false;
13830
13831 // Don't warn about function templates.
13832 if (FD->getDescribedFunctionTemplate())
13833 return false;
13834
13835 // Don't warn about function template specializations.
13836 if (FD->isFunctionTemplateSpecialization())
13837 return false;
13838
13839 // Don't warn for OpenCL kernels.
13840 if (FD->hasAttr<OpenCLKernelAttr>())
13841 return false;
13842
13843 // Don't warn on explicitly deleted functions.
13844 if (FD->isDeleted())
13845 return false;
13846
13847 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13848 Prev; Prev = Prev->getPreviousDecl()) {
13849 // Ignore any declarations that occur in function or method
13850 // scope, because they aren't visible from the header.
13851 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13852 continue;
13853
13854 PossiblePrototype = Prev;
13855 return Prev->getType()->isFunctionNoProtoType();
13856 }
13857
13858 return true;
13859}
13860
13861void
13862Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13863 const FunctionDecl *EffectiveDefinition,
13864 SkipBodyInfo *SkipBody) {
13865 const FunctionDecl *Definition = EffectiveDefinition;
13866 if (!Definition &&
13867 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
13868 return;
13869
13870 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
13871 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
13872 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13873 // A merged copy of the same function, instantiated as a member of
13874 // the same class, is OK.
13875 if (declaresSameEntity(OrigFD, OrigDef) &&
13876 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
13877 cast<Decl>(FD->getLexicalDeclContext())))
13878 return;
13879 }
13880 }
13881 }
13882
13883 if (canRedefineFunction(Definition, getLangOpts()))
13884 return;
13885
13886 // Don't emit an error when this is redefinition of a typo-corrected
13887 // definition.
13888 if (TypoCorrectedFunctionDefinitions.count(Definition))
13889 return;
13890
13891 // If we don't have a visible definition of the function, and it's inline or
13892 // a template, skip the new definition.
13893 if (SkipBody && !hasVisibleDefinition(Definition) &&
13894 (Definition->getFormalLinkage() == InternalLinkage ||
13895 Definition->isInlined() ||
13896 Definition->getDescribedFunctionTemplate() ||
13897 Definition->getNumTemplateParameterLists())) {
13898 SkipBody->ShouldSkip = true;
13899 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13900 if (auto *TD = Definition->getDescribedFunctionTemplate())
13901 makeMergedDefinitionVisible(TD);
13902 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13903 return;
13904 }
13905
13906 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13907 Definition->getStorageClass() == SC_Extern)
13908 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13909 << FD << getLangOpts().CPlusPlus;
13910 else
13911 Diag(FD->getLocation(), diag::err_redefinition) << FD;
13912
13913 Diag(Definition->getLocation(), diag::note_previous_definition);
13914 FD->setInvalidDecl();
13915}
13916
13917static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13918 Sema &S) {
13919 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13920
13921 LambdaScopeInfo *LSI = S.PushLambdaScope();
13922 LSI->CallOperator = CallOperator;
13923 LSI->Lambda = LambdaClass;
13924 LSI->ReturnType = CallOperator->getReturnType();
13925 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13926
13927 if (LCD == LCD_None)
13928 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13929 else if (LCD == LCD_ByCopy)
13930 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13931 else if (LCD == LCD_ByRef)
13932 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13933 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13934
13935 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13936 LSI->Mutable = !CallOperator->isConst();
13937
13938 // Add the captures to the LSI so they can be noted as already
13939 // captured within tryCaptureVar.
13940 auto I = LambdaClass->field_begin();
13941 for (const auto &C : LambdaClass->captures()) {
13942 if (C.capturesVariable()) {
13943 VarDecl *VD = C.getCapturedVar();
13944 if (VD->isInitCapture())
13945 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13946 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13947 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13948 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13949 /*EllipsisLoc*/C.isPackExpansion()
13950 ? C.getEllipsisLoc() : SourceLocation(),
13951 I->getType(), /*Invalid*/false);
13952
13953 } else if (C.capturesThis()) {
13954 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13955 C.getCaptureKind() == LCK_StarThis);
13956 } else {
13957 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13958 I->getType());
13959 }
13960 ++I;
13961 }
13962}
13963
13964Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13965 SkipBodyInfo *SkipBody) {
13966 if (!D) {
13967 // Parsing the function declaration failed in some way. Push on a fake scope
13968 // anyway so we can try to parse the function body.
13969 PushFunctionScope();
13970 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13971 return D;
13972 }
13973
13974 FunctionDecl *FD = nullptr;
13975
13976 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13977 FD = FunTmpl->getTemplatedDecl();
13978 else
13979 FD = cast<FunctionDecl>(D);
13980
13981 // Do not push if it is a lambda because one is already pushed when building
13982 // the lambda in ActOnStartOfLambdaDefinition().
13983 if (!isLambdaCallOperator(FD))
13984 PushExpressionEvaluationContext(
13985 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
13986 : ExprEvalContexts.back().Context);
13987
13988 // Check for defining attributes before the check for redefinition.
13989 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
13990 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
13991 FD->dropAttr<AliasAttr>();
13992 FD->setInvalidDecl();
13993 }
13994 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
13995 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
13996 FD->dropAttr<IFuncAttr>();
13997 FD->setInvalidDecl();
13998 }
13999
14000 // See if this is a redefinition. If 'will have body' (or similar) is already
14001 // set, then these checks were already performed when it was set.
14002 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14003 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14004 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14005
14006 // If we're skipping the body, we're done. Don't enter the scope.
14007 if (SkipBody && SkipBody->ShouldSkip)
14008 return D;
14009 }
14010
14011 // Mark this function as "will have a body eventually". This lets users to
14012 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14013 // this function.
14014 FD->setWillHaveBody();
14015
14016 // If we are instantiating a generic lambda call operator, push
14017 // a LambdaScopeInfo onto the function stack. But use the information
14018 // that's already been calculated (ActOnLambdaExpr) to prime the current
14019 // LambdaScopeInfo.
14020 // When the template operator is being specialized, the LambdaScopeInfo,
14021 // has to be properly restored so that tryCaptureVariable doesn't try
14022 // and capture any new variables. In addition when calculating potential
14023 // captures during transformation of nested lambdas, it is necessary to
14024 // have the LSI properly restored.
14025 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14026 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14028, __PRETTY_FUNCTION__))
14027 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14028, __PRETTY_FUNCTION__))
14028 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14028, __PRETTY_FUNCTION__))
;
14029 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14030 } else {
14031 // Enter a new function scope
14032 PushFunctionScope();
14033 }
14034
14035 // Builtin functions cannot be defined.
14036 if (unsigned BuiltinID = FD->getBuiltinID()) {
14037 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14038 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14039 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14040 FD->setInvalidDecl();
14041 }
14042 }
14043
14044 // The return type of a function definition must be complete
14045 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14046 QualType ResultType = FD->getReturnType();
14047 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14048 !FD->isInvalidDecl() &&
14049 RequireCompleteType(FD->getLocation(), ResultType,
14050 diag::err_func_def_incomplete_result))
14051 FD->setInvalidDecl();
14052
14053 if (FnBodyScope)
14054 PushDeclContext(FnBodyScope, FD);
14055
14056 // Check the validity of our function parameters
14057 CheckParmsForFunctionDef(FD->parameters(),
14058 /*CheckParameterNames=*/true);
14059
14060 // Add non-parameter declarations already in the function to the current
14061 // scope.
14062 if (FnBodyScope) {
14063 for (Decl *NPD : FD->decls()) {
14064 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14065 if (!NonParmDecl)
14066 continue;
14067 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14068, __PRETTY_FUNCTION__))
14068 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14068, __PRETTY_FUNCTION__))
;
14069
14070 // If the decl has a name, make it accessible in the current scope.
14071 if (NonParmDecl->getDeclName())
14072 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14073
14074 // Similarly, dive into enums and fish their constants out, making them
14075 // accessible in this scope.
14076 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14077 for (auto *EI : ED->enumerators())
14078 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14079 }
14080 }
14081 }
14082
14083 // Introduce our parameters into the function scope
14084 for (auto Param : FD->parameters()) {
14085 Param->setOwningFunction(FD);
14086
14087 // If this has an identifier, add it to the scope stack.
14088 if (Param->getIdentifier() && FnBodyScope) {
14089 CheckShadow(FnBodyScope, Param);
14090
14091 PushOnScopeChains(Param, FnBodyScope);
14092 }
14093 }
14094
14095 // Ensure that the function's exception specification is instantiated.
14096 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14097 ResolveExceptionSpec(D->getLocation(), FPT);
14098
14099 // dllimport cannot be applied to non-inline function definitions.
14100 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14101 !FD->isTemplateInstantiation()) {
14102 assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void
> (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14102, __PRETTY_FUNCTION__))
;
14103 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14104 FD->setInvalidDecl();
14105 return D;
14106 }
14107 // We want to attach documentation to original Decl (which might be
14108 // a function template).
14109 ActOnDocumentableDecl(D);
14110 if (getCurLexicalContext()->isObjCContainer() &&
14111 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14112 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14113 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14114
14115 return D;
14116}
14117
14118/// Given the set of return statements within a function body,
14119/// compute the variables that are subject to the named return value
14120/// optimization.
14121///
14122/// Each of the variables that is subject to the named return value
14123/// optimization will be marked as NRVO variables in the AST, and any
14124/// return statement that has a marked NRVO variable as its NRVO candidate can
14125/// use the named return value optimization.
14126///
14127/// This function applies a very simplistic algorithm for NRVO: if every return
14128/// statement in the scope of a variable has the same NRVO candidate, that
14129/// candidate is an NRVO variable.
14130void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14131 ReturnStmt **Returns = Scope->Returns.data();
14132
14133 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14134 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14135 if (!NRVOCandidate->isNRVOVariable())
14136 Returns[I]->setNRVOCandidate(nullptr);
14137 }
14138 }
14139}
14140
14141bool Sema::canDelayFunctionBody(const Declarator &D) {
14142 // We can't delay parsing the body of a constexpr function template (yet).
14143 if (D.getDeclSpec().hasConstexprSpecifier())
14144 return false;
14145
14146 // We can't delay parsing the body of a function template with a deduced
14147 // return type (yet).
14148 if (D.getDeclSpec().hasAutoTypeSpec()) {
14149 // If the placeholder introduces a non-deduced trailing return type,
14150 // we can still delay parsing it.
14151 if (D.getNumTypeObjects()) {
14152 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14153 if (Outer.Kind == DeclaratorChunk::Function &&
14154 Outer.Fun.hasTrailingReturnType()) {
14155 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14156 return Ty.isNull() || !Ty->isUndeducedType();
14157 }
14158 }
14159 return false;
14160 }
14161
14162 return true;
14163}
14164
14165bool Sema::canSkipFunctionBody(Decl *D) {
14166 // We cannot skip the body of a function (or function template) which is
14167 // constexpr, since we may need to evaluate its body in order to parse the
14168 // rest of the file.
14169 // We cannot skip the body of a function with an undeduced return type,
14170 // because any callers of that function need to know the type.
14171 if (const FunctionDecl *FD = D->getAsFunction()) {
14172 if (FD->isConstexpr())
14173 return false;
14174 // We can't simply call Type::isUndeducedType here, because inside template
14175 // auto can be deduced to a dependent type, which is not considered
14176 // "undeduced".
14177 if (FD->getReturnType()->getContainedDeducedType())
14178 return false;
14179 }
14180 return Consumer.shouldSkipFunctionBody(D);
14181}
14182
14183Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14184 if (!Decl)
14185 return nullptr;
14186 if (FunctionDecl *FD = Decl->getAsFunction())
14187 FD->setHasSkippedBody();
14188 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14189 MD->setHasSkippedBody();
14190 return Decl;
14191}
14192
14193Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14194 return ActOnFinishFunctionBody(D, BodyArg, false);
14195}
14196
14197/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14198/// body.
14199class ExitFunctionBodyRAII {
14200public:
14201 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14202 ~ExitFunctionBodyRAII() {
14203 if (!IsLambda)
14204 S.PopExpressionEvaluationContext();
14205 }
14206
14207private:
14208 Sema &S;
14209 bool IsLambda = false;
14210};
14211
14212static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14213 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14214
14215 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14216 if (EscapeInfo.count(BD))
14217 return EscapeInfo[BD];
14218
14219 bool R = false;
14220 const BlockDecl *CurBD = BD;
14221
14222 do {
14223 R = !CurBD->doesNotEscape();
14224 if (R)
14225 break;
14226 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14227 } while (CurBD);
14228
14229 return EscapeInfo[BD] = R;
14230 };
14231
14232 // If the location where 'self' is implicitly retained is inside a escaping
14233 // block, emit a diagnostic.
14234 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14235 S.ImplicitlyRetainedSelfLocs)
14236 if (IsOrNestedInEscapingBlock(P.second))
14237 S.Diag(P.first, diag::warn_implicitly_retains_self)
14238 << FixItHint::CreateInsertion(P.first, "self->");
14239}
14240
14241Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14242 bool IsInstantiation) {
14243 FunctionScopeInfo *FSI = getCurFunction();
14244 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14245
14246 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14247 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14248
14249 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14250 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14251
14252 if (getLangOpts().Coroutines && FSI->isCoroutine())
14253 CheckCompletedCoroutineBody(FD, Body);
14254
14255 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14256 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14257 // meant to pop the context added in ActOnStartOfFunctionDef().
14258 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14259
14260 if (FD) {
14261 FD->setBody(Body);
14262 FD->setWillHaveBody(false);
14263
14264 if (getLangOpts().CPlusPlus14) {
14265 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14266 FD->getReturnType()->isUndeducedType()) {
14267 // If the function has a deduced result type but contains no 'return'
14268 // statements, the result type as written must be exactly 'auto', and
14269 // the deduced result type is 'void'.
14270 if (!FD->getReturnType()->getAs<AutoType>()) {
14271 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14272 << FD->getReturnType();
14273 FD->setInvalidDecl();
14274 } else {
14275 // Substitute 'void' for the 'auto' in the type.
14276 TypeLoc ResultType = getReturnTypeLoc(FD);
14277 Context.adjustDeducedFunctionResultType(
14278 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14279 }
14280 }
14281 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14282 // In C++11, we don't use 'auto' deduction rules for lambda call
14283 // operators because we don't support return type deduction.
14284 auto *LSI = getCurLambda();
14285 if (LSI->HasImplicitReturnType) {
14286 deduceClosureReturnType(*LSI);
14287
14288 // C++11 [expr.prim.lambda]p4:
14289 // [...] if there are no return statements in the compound-statement
14290 // [the deduced type is] the type void
14291 QualType RetType =
14292 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14293
14294 // Update the return type to the deduced type.
14295 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14296 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14297 Proto->getExtProtoInfo()));
14298 }
14299 }
14300
14301 // If the function implicitly returns zero (like 'main') or is naked,
14302 // don't complain about missing return statements.
14303 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14304 WP.disableCheckFallThrough();
14305
14306 // MSVC permits the use of pure specifier (=0) on function definition,
14307 // defined at class scope, warn about this non-standard construct.
14308 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14309 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14310
14311 if (!FD->isInvalidDecl()) {
14312 // Don't diagnose unused parameters of defaulted or deleted functions.
14313 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14314 DiagnoseUnusedParameters(FD->parameters());
14315 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14316 FD->getReturnType(), FD);
14317
14318 // If this is a structor, we need a vtable.
14319 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14320 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14321 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14322 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14323
14324 // Try to apply the named return value optimization. We have to check
14325 // if we can do this here because lambdas keep return statements around
14326 // to deduce an implicit return type.
14327 if (FD->getReturnType()->isRecordType() &&
14328 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14329 computeNRVO(Body, FSI);
14330 }
14331
14332 // GNU warning -Wmissing-prototypes:
14333 // Warn if a global function is defined without a previous
14334 // prototype declaration. This warning is issued even if the
14335 // definition itself provides a prototype. The aim is to detect
14336 // global functions that fail to be declared in header files.
14337 const FunctionDecl *PossiblePrototype = nullptr;
14338 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14339 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14340
14341 if (PossiblePrototype) {
14342 // We found a declaration that is not a prototype,
14343 // but that could be a zero-parameter prototype
14344 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14345 TypeLoc TL = TI->getTypeLoc();
14346 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14347 Diag(PossiblePrototype->getLocation(),
14348 diag::note_declaration_not_a_prototype)
14349 << (FD->getNumParams() != 0)
14350 << (FD->getNumParams() == 0
14351 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14352 : FixItHint{});
14353 }
14354 } else {
14355 // Returns true if the token beginning at this Loc is `const`.
14356 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14357 const LangOptions &LangOpts) {
14358 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14359 if (LocInfo.first.isInvalid())
14360 return false;
14361
14362 bool Invalid = false;
14363 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14364 if (Invalid)
14365 return false;
14366
14367 if (LocInfo.second > Buffer.size())
14368 return false;
14369
14370 const char *LexStart = Buffer.data() + LocInfo.second;
14371 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14372
14373 return StartTok.consume_front("const") &&
14374 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14375 StartTok.startswith("/*") || StartTok.startswith("//"));
14376 };
14377
14378 auto findBeginLoc = [&]() {
14379 // If the return type has `const` qualifier, we want to insert
14380 // `static` before `const` (and not before the typename).
14381 if ((FD->getReturnType()->isAnyPointerType() &&
14382 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14383 FD->getReturnType().isConstQualified()) {
14384 // But only do this if we can determine where the `const` is.
14385
14386 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14387 getLangOpts()))
14388
14389 return FD->getBeginLoc();
14390 }
14391 return FD->getTypeSpecStartLoc();
14392 };
14393 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14394 << /* function */ 1
14395 << (FD->getStorageClass() == SC_None
14396 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14397 : FixItHint{});
14398 }
14399
14400 // GNU warning -Wstrict-prototypes
14401 // Warn if K&R function is defined without a previous declaration.
14402 // This warning is issued only if the definition itself does not provide
14403 // a prototype. Only K&R definitions do not provide a prototype.
14404 if (!FD->hasWrittenPrototype()) {
14405 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14406 TypeLoc TL = TI->getTypeLoc();
14407 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14408 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14409 }
14410 }
14411
14412 // Warn on CPUDispatch with an actual body.
14413 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14414 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14415 if (!CmpndBody->body_empty())
14416 Diag(CmpndBody->body_front()->getBeginLoc(),
14417 diag::warn_dispatch_body_ignored);
14418
14419 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14420 const CXXMethodDecl *KeyFunction;
14421 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14422 MD->isVirtual() &&
14423 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14424 MD == KeyFunction->getCanonicalDecl()) {
14425 // Update the key-function state if necessary for this ABI.
14426 if (FD->isInlined() &&
14427 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14428 Context.setNonKeyFunction(MD);
14429
14430 // If the newly-chosen key function is already defined, then we
14431 // need to mark the vtable as used retroactively.
14432 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14433 const FunctionDecl *Definition;
14434 if (KeyFunction && KeyFunction->isDefined(Definition))
14435 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14436 } else {
14437 // We just defined they key function; mark the vtable as used.
14438 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14439 }
14440 }
14441 }
14442
14443 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14444, __PRETTY_FUNCTION__))
14444 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14444, __PRETTY_FUNCTION__))
;
14445 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14446 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14446, __PRETTY_FUNCTION__))
;
14447 MD->setBody(Body);
14448 if (!MD->isInvalidDecl()) {
14449 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14450 MD->getReturnType(), MD);
14451
14452 if (Body)
14453 computeNRVO(Body, FSI);
14454 }
14455 if (FSI->ObjCShouldCallSuper) {
14456 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14457 << MD->getSelector().getAsString();
14458 FSI->ObjCShouldCallSuper = false;
14459 }
14460 if (FSI->ObjCWarnForNoDesignatedInitChain) {
14461 const ObjCMethodDecl *InitMethod = nullptr;
14462 bool isDesignated =
14463 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14464 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14464, __PRETTY_FUNCTION__))
;
14465 (void)isDesignated;
14466
14467 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14468 auto IFace = MD->getClassInterface();
14469 if (!IFace)
14470 return false;
14471 auto SuperD = IFace->getSuperClass();
14472 if (!SuperD)
14473 return false;
14474 return SuperD->getIdentifier() ==
14475 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14476 };
14477 // Don't issue this warning for unavailable inits or direct subclasses
14478 // of NSObject.
14479 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14480 Diag(MD->getLocation(),
14481 diag::warn_objc_designated_init_missing_super_call);
14482 Diag(InitMethod->getLocation(),
14483 diag::note_objc_designated_init_marked_here);
14484 }
14485 FSI->ObjCWarnForNoDesignatedInitChain = false;
14486 }
14487 if (FSI->ObjCWarnForNoInitDelegation) {
14488 // Don't issue this warning for unavaialable inits.
14489 if (!MD->isUnavailable())
14490 Diag(MD->getLocation(),
14491 diag::warn_objc_secondary_init_missing_init_call);
14492 FSI->ObjCWarnForNoInitDelegation = false;
14493 }
14494
14495 diagnoseImplicitlyRetainedSelf(*this);
14496 } else {
14497 // Parsing the function declaration failed in some way. Pop the fake scope
14498 // we pushed on.
14499 PopFunctionScopeInfo(ActivePolicy, dcl);
14500 return nullptr;
14501 }
14502
14503 if (Body && FSI->HasPotentialAvailabilityViolations)
14504 DiagnoseUnguardedAvailabilityViolations(dcl);
14505
14506 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14508, __PRETTY_FUNCTION__))
14507 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14508, __PRETTY_FUNCTION__))
14508 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14508, __PRETTY_FUNCTION__))
;
14509
14510 // Verify and clean out per-function state.
14511 if (Body && (!FD || !FD->isDefaulted())) {
14512 // C++ constructors that have function-try-blocks can't have return
14513 // statements in the handlers of that block. (C++ [except.handle]p14)
14514 // Verify this.
14515 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14516 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14517
14518 // Verify that gotos and switch cases don't jump into scopes illegally.
14519 if (FSI->NeedsScopeChecking() &&
14520 !PP.isCodeCompletionEnabled())
14521 DiagnoseInvalidJumps(Body);
14522
14523 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14524 if (!Destructor->getParent()->isDependentType())
14525 CheckDestructor(Destructor);
14526
14527 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14528 Destructor->getParent());
14529 }
14530
14531 // If any errors have occurred, clear out any temporaries that may have
14532 // been leftover. This ensures that these temporaries won't be picked up for
14533 // deletion in some later function.
14534 if (hasUncompilableErrorOccurred() ||
14535 getDiagnostics().getSuppressAllDiagnostics()) {
14536 DiscardCleanupsInEvaluationContext();
14537 }
14538 if (!hasUncompilableErrorOccurred() &&
14539 !isa<FunctionTemplateDecl>(dcl)) {
14540 // Since the body is valid, issue any analysis-based warnings that are
14541 // enabled.
14542 ActivePolicy = &WP;
14543 }
14544
14545 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14546 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14547 FD->setInvalidDecl();
14548
14549 if (FD && FD->hasAttr<NakedAttr>()) {
14550 for (const Stmt *S : Body->children()) {
14551 // Allow local register variables without initializer as they don't
14552 // require prologue.
14553 bool RegisterVariables = false;
14554 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14555 for (const auto *Decl : DS->decls()) {
14556 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14557 RegisterVariables =
14558 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14559 if (!RegisterVariables)
14560 break;
14561 }
14562 }
14563 }
14564 if (RegisterVariables)
14565 continue;
14566 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14567 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14568 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14569 FD->setInvalidDecl();
14570 break;
14571 }
14572 }
14573 }
14574
14575 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14577, __PRETTY_FUNCTION__))
14576 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14577, __PRETTY_FUNCTION__))
14577 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14577, __PRETTY_FUNCTION__))
;
14578 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14578, __PRETTY_FUNCTION__))
;
14579 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14580, __PRETTY_FUNCTION__))
14580 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14580, __PRETTY_FUNCTION__))
;
14581 }
14582
14583 if (!IsInstantiation)
14584 PopDeclContext();
14585
14586 PopFunctionScopeInfo(ActivePolicy, dcl);
14587 // If any errors have occurred, clear out any temporaries that may have
14588 // been leftover. This ensures that these temporaries won't be picked up for
14589 // deletion in some later function.
14590 if (hasUncompilableErrorOccurred()) {
14591 DiscardCleanupsInEvaluationContext();
14592 }
14593
14594 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14595 auto ES = getEmissionStatus(FD);
14596 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14597 ES == Sema::FunctionEmissionStatus::Unknown)
14598 DeclsToCheckForDeferredDiags.push_back(FD);
14599 }
14600
14601 return dcl;
14602}
14603
14604/// When we finish delayed parsing of an attribute, we must attach it to the
14605/// relevant Decl.
14606void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14607 ParsedAttributes &Attrs) {
14608 // Always attach attributes to the underlying decl.
14609 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14610 D = TD->getTemplatedDecl();
14611 ProcessDeclAttributeList(S, D, Attrs);
14612
14613 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14614 if (Method->isStatic())
14615 checkThisInStaticMemberFunctionAttributes(Method);
14616}
14617
14618/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14619/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14620NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14621 IdentifierInfo &II, Scope *S) {
14622 // Find the scope in which the identifier is injected and the corresponding
14623 // DeclContext.
14624 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14625 // In that case, we inject the declaration into the translation unit scope
14626 // instead.
14627 Scope *BlockScope = S;
14628 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14629 BlockScope = BlockScope->getParent();
14630
14631 Scope *ContextScope = BlockScope;
14632 while (!ContextScope->getEntity())
14633 ContextScope = ContextScope->getParent();
14634 ContextRAII SavedContext(*this, ContextScope->getEntity());
14635
14636 // Before we produce a declaration for an implicitly defined
14637 // function, see whether there was a locally-scoped declaration of
14638 // this name as a function or variable. If so, use that
14639 // (non-visible) declaration, and complain about it.
14640 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14641 if (ExternCPrev) {
14642 // We still need to inject the function into the enclosing block scope so
14643 // that later (non-call) uses can see it.
14644 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14645
14646 // C89 footnote 38:
14647 // If in fact it is not defined as having type "function returning int",
14648 // the behavior is undefined.
14649 if (!isa<FunctionDecl>(ExternCPrev) ||
14650 !Context.typesAreCompatible(
14651 cast<FunctionDecl>(ExternCPrev)->getType(),
14652 Context.getFunctionNoProtoType(Context.IntTy))) {
14653 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14654 << ExternCPrev << !getLangOpts().C99;
14655 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14656 return ExternCPrev;
14657 }
14658 }
14659
14660 // Extension in C99. Legal in C90, but warn about it.
14661 unsigned diag_id;
14662 if (II.getName().startswith("__builtin_"))
14663 diag_id = diag::warn_builtin_unknown;
14664 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14665 else if (getLangOpts().OpenCL)
14666 diag_id = diag::err_opencl_implicit_function_decl;
14667 else if (getLangOpts().C99)
14668 diag_id = diag::ext_implicit_function_decl;
14669 else
14670 diag_id = diag::warn_implicit_function_decl;
14671 Diag(Loc, diag_id) << &II;
14672
14673 // If we found a prior declaration of this function, don't bother building
14674 // another one. We've already pushed that one into scope, so there's nothing
14675 // more to do.
14676 if (ExternCPrev)
14677 return ExternCPrev;
14678
14679 // Because typo correction is expensive, only do it if the implicit
14680 // function declaration is going to be treated as an error.
14681 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14682 TypoCorrection Corrected;
14683 DeclFilterCCC<FunctionDecl> CCC{};
14684 if (S && (Corrected =
14685 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14686 S, nullptr, CCC, CTK_NonError)))
14687 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14688 /*ErrorRecovery*/false);
14689 }
14690
14691 // Set a Declarator for the implicit definition: int foo();
14692 const char *Dummy;
14693 AttributeFactory attrFactory;
14694 DeclSpec DS(attrFactory);
14695 unsigned DiagID;
14696 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14697 Context.getPrintingPolicy());
14698 (void)Error; // Silence warning.
14699 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14699, __PRETTY_FUNCTION__))
;
14700 SourceLocation NoLoc;
14701 Declarator D(DS, DeclaratorContext::BlockContext);
14702 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14703 /*IsAmbiguous=*/false,
14704 /*LParenLoc=*/NoLoc,
14705 /*Params=*/nullptr,
14706 /*NumParams=*/0,
14707 /*EllipsisLoc=*/NoLoc,
14708 /*RParenLoc=*/NoLoc,
14709 /*RefQualifierIsLvalueRef=*/true,
14710 /*RefQualifierLoc=*/NoLoc,
14711 /*MutableLoc=*/NoLoc, EST_None,
14712 /*ESpecRange=*/SourceRange(),
14713 /*Exceptions=*/nullptr,
14714 /*ExceptionRanges=*/nullptr,
14715 /*NumExceptions=*/0,
14716 /*NoexceptExpr=*/nullptr,
14717 /*ExceptionSpecTokens=*/nullptr,
14718 /*DeclsInPrototype=*/None, Loc,
14719 Loc, D),
14720 std::move(DS.getAttributes()), SourceLocation());
14721 D.SetIdentifier(&II, Loc);
14722
14723 // Insert this function into the enclosing block scope.
14724 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14725 FD->setImplicit();
14726
14727 AddKnownFunctionAttributes(FD);
14728
14729 return FD;
14730}
14731
14732/// If this function is a C++ replaceable global allocation function
14733/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14734/// adds any function attributes that we know a priori based on the standard.
14735///
14736/// We need to check for duplicate attributes both here and where user-written
14737/// attributes are applied to declarations.
14738void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14739 FunctionDecl *FD) {
14740 if (FD->isInvalidDecl())
14741 return;
14742
14743 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14744 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14745 return;
14746
14747 Optional<unsigned> AlignmentParam;
14748 bool IsNothrow = false;
14749 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14750 return;
14751
14752 // C++2a [basic.stc.dynamic.allocation]p4:
14753 // An allocation function that has a non-throwing exception specification
14754 // indicates failure by returning a null pointer value. Any other allocation
14755 // function never returns a null pointer value and indicates failure only by
14756 // throwing an exception [...]
14757 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14758 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14759
14760 // C++2a [basic.stc.dynamic.allocation]p2:
14761 // An allocation function attempts to allocate the requested amount of
14762 // storage. [...] If the request succeeds, the value returned by a
14763 // replaceable allocation function is a [...] pointer value p0 different
14764 // from any previously returned value p1 [...]
14765 //
14766 // However, this particular information is being added in codegen,
14767 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14768
14769 // C++2a [basic.stc.dynamic.allocation]p2:
14770 // An allocation function attempts to allocate the requested amount of
14771 // storage. If it is successful, it returns the address of the start of a
14772 // block of storage whose length in bytes is at least as large as the
14773 // requested size.
14774 if (!FD->hasAttr<AllocSizeAttr>()) {
14775 FD->addAttr(AllocSizeAttr::CreateImplicit(
14776 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14777 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14778 }
14779
14780 // C++2a [basic.stc.dynamic.allocation]p3:
14781 // For an allocation function [...], the pointer returned on a successful
14782 // call shall represent the address of storage that is aligned as follows:
14783 // (3.1) If the allocation function takes an argument of type
14784 // std​::​align_­val_­t, the storage will have the alignment
14785 // specified by the value of this argument.
14786 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14787 FD->addAttr(AllocAlignAttr::CreateImplicit(
14788 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14789 }
14790
14791 // FIXME:
14792 // C++2a [basic.stc.dynamic.allocation]p3:
14793 // For an allocation function [...], the pointer returned on a successful
14794 // call shall represent the address of storage that is aligned as follows:
14795 // (3.2) Otherwise, if the allocation function is named operator new[],
14796 // the storage is aligned for any object that does not have
14797 // new-extended alignment ([basic.align]) and is no larger than the
14798 // requested size.
14799 // (3.3) Otherwise, the storage is aligned for any object that does not
14800 // have new-extended alignment and is of the requested size.
14801}
14802
14803/// Adds any function attributes that we know a priori based on
14804/// the declaration of this function.
14805///
14806/// These attributes can apply both to implicitly-declared builtins
14807/// (like __builtin___printf_chk) or to library-declared functions
14808/// like NSLog or printf.
14809///
14810/// We need to check for duplicate attributes both here and where user-written
14811/// attributes are applied to declarations.
14812void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14813 if (FD->isInvalidDecl())
14814 return;
14815
14816 // If this is a built-in function, map its builtin attributes to
14817 // actual attributes.
14818 if (unsigned BuiltinID = FD->getBuiltinID()) {
14819 // Handle printf-formatting attributes.
14820 unsigned FormatIdx;
14821 bool HasVAListArg;
14822 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14823 if (!FD->hasAttr<FormatAttr>()) {
14824 const char *fmt = "printf";
14825 unsigned int NumParams = FD->getNumParams();
14826 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14827 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14828 fmt = "NSString";
14829 FD->addAttr(FormatAttr::CreateImplicit(Context,
14830 &Context.Idents.get(fmt),
14831 FormatIdx+1,
14832 HasVAListArg ? 0 : FormatIdx+2,
14833 FD->getLocation()));
14834 }
14835 }
14836 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14837 HasVAListArg)) {
14838 if (!FD->hasAttr<FormatAttr>())
14839 FD->addAttr(FormatAttr::CreateImplicit(Context,
14840 &Context.Idents.get("scanf"),
14841 FormatIdx+1,
14842 HasVAListArg ? 0 : FormatIdx+2,
14843 FD->getLocation()));
14844 }
14845
14846 // Handle automatically recognized callbacks.
14847 SmallVector<int, 4> Encoding;
14848 if (!FD->hasAttr<CallbackAttr>() &&
14849 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14850 FD->addAttr(CallbackAttr::CreateImplicit(
14851 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14852
14853 // Mark const if we don't care about errno and that is the only thing
14854 // preventing the function from being const. This allows IRgen to use LLVM
14855 // intrinsics for such functions.
14856 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14857 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14858 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14859
14860 // We make "fma" on some platforms const because we know it does not set
14861 // errno in those environments even though it could set errno based on the
14862 // C standard.
14863 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14864 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14865 !FD->hasAttr<ConstAttr>()) {
14866 switch (BuiltinID) {
14867 case Builtin::BI__builtin_fma:
14868 case Builtin::BI__builtin_fmaf:
14869 case Builtin::BI__builtin_fmal:
14870 case Builtin::BIfma:
14871 case Builtin::BIfmaf:
14872 case Builtin::BIfmal:
14873 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14874 break;
14875 default:
14876 break;
14877 }
14878 }
14879
14880 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14881 !FD->hasAttr<ReturnsTwiceAttr>())
14882 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14883 FD->getLocation()));
14884 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14885 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14886 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14887 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14888 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14889 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14890 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14891 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14892 // Add the appropriate attribute, depending on the CUDA compilation mode
14893 // and which target the builtin belongs to. For example, during host
14894 // compilation, aux builtins are __device__, while the rest are __host__.
14895 if (getLangOpts().CUDAIsDevice !=
14896 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14897 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14898 else
14899 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14900 }
14901 }
14902
14903 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14904
14905 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14906 // throw, add an implicit nothrow attribute to any extern "C" function we come
14907 // across.
14908 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14909 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14910 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14911 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14912 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14913 }
14914
14915 IdentifierInfo *Name = FD->getIdentifier();
14916 if (!Name)
14917 return;
14918 if ((!getLangOpts().CPlusPlus &&
14919 FD->getDeclContext()->isTranslationUnit()) ||
14920 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14921 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14922 LinkageSpecDecl::lang_c)) {
14923 // Okay: this could be a libc/libm/Objective-C function we know
14924 // about.
14925 } else
14926 return;
14927
14928 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14929 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14930 // target-specific builtins, perhaps?
14931 if (!FD->hasAttr<FormatAttr>())
14932 FD->addAttr(FormatAttr::CreateImplicit(Context,
14933 &Context.Idents.get("printf"), 2,
14934 Name->isStr("vasprintf") ? 0 : 3,
14935 FD->getLocation()));
14936 }
14937
14938 if (Name->isStr("__CFStringMakeConstantString")) {
14939 // We already have a __builtin___CFStringMakeConstantString,
14940 // but builds that use -fno-constant-cfstrings don't go through that.
14941 if (!FD->hasAttr<FormatArgAttr>())
14942 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14943 FD->getLocation()));
14944 }
14945}
14946
14947TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14948 TypeSourceInfo *TInfo) {
14949 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14949, __PRETTY_FUNCTION__))
;
14950 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14950, __PRETTY_FUNCTION__))
;
14951
14952 if (!TInfo) {
14953 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 14953, __PRETTY_FUNCTION__))
;
14954 TInfo = Context.getTrivialTypeSourceInfo(T);
14955 }
14956
14957 // Scope manipulation handled by caller.
14958 TypedefDecl *NewTD =
14959 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14960 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14961
14962 // Bail out immediately if we have an invalid declaration.
14963 if (D.isInvalidType()) {
14964 NewTD->setInvalidDecl();
14965 return NewTD;
14966 }
14967
14968 if (D.getDeclSpec().isModulePrivateSpecified()) {
14969 if (CurContext->isFunctionOrMethod())
14970 Diag(NewTD->getLocation(), diag::err_module_private_local)
14971 << 2 << NewTD
14972 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14973 << FixItHint::CreateRemoval(
14974 D.getDeclSpec().getModulePrivateSpecLoc());
14975 else
14976 NewTD->setModulePrivate();
14977 }
14978
14979 // C++ [dcl.typedef]p8:
14980 // If the typedef declaration defines an unnamed class (or
14981 // enum), the first typedef-name declared by the declaration
14982 // to be that class type (or enum type) is used to denote the
14983 // class type (or enum type) for linkage purposes only.
14984 // We need to check whether the type was declared in the declaration.
14985 switch (D.getDeclSpec().getTypeSpecType()) {
14986 case TST_enum:
14987 case TST_struct:
14988 case TST_interface:
14989 case TST_union:
14990 case TST_class: {
14991 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
14992 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
14993 break;
14994 }
14995
14996 default:
14997 break;
14998 }
14999
15000 return NewTD;
15001}
15002
15003/// Check that this is a valid underlying type for an enum declaration.
15004bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15005 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15006 QualType T = TI->getType();
15007
15008 if (T->isDependentType())
15009 return false;
15010
15011 // This doesn't use 'isIntegralType' despite the error message mentioning
15012 // integral type because isIntegralType would also allow enum types in C.
15013 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15014 if (BT->isInteger())
15015 return false;
15016
15017 if (T->isExtIntType())
15018 return false;
15019
15020 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15021}
15022
15023/// Check whether this is a valid redeclaration of a previous enumeration.
15024/// \return true if the redeclaration was invalid.
15025bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15026 QualType EnumUnderlyingTy, bool IsFixed,
15027 const EnumDecl *Prev) {
15028 if (IsScoped != Prev->isScoped()) {
15029 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15030 << Prev->isScoped();
15031 Diag(Prev->getLocation(), diag::note_previous_declaration);
15032 return true;
15033 }
15034
15035 if (IsFixed && Prev->isFixed()) {
15036 if (!EnumUnderlyingTy->isDependentType() &&
15037 !Prev->getIntegerType()->isDependentType() &&
15038 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15039 Prev->getIntegerType())) {
15040 // TODO: Highlight the underlying type of the redeclaration.
15041 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15042 << EnumUnderlyingTy << Prev->getIntegerType();
15043 Diag(Prev->getLocation(), diag::note_previous_declaration)
15044 << Prev->getIntegerTypeRange();
15045 return true;
15046 }
15047 } else if (IsFixed != Prev->isFixed()) {
15048 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15049 << Prev->isFixed();
15050 Diag(Prev->getLocation(), diag::note_previous_declaration);
15051 return true;
15052 }
15053
15054 return false;
15055}
15056
15057/// Get diagnostic %select index for tag kind for
15058/// redeclaration diagnostic message.
15059/// WARNING: Indexes apply to particular diagnostics only!
15060///
15061/// \returns diagnostic %select index.
15062static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15063 switch (Tag) {
15064 case TTK_Struct: return 0;
15065 case TTK_Interface: return 1;
15066 case TTK_Class: return 2;
15067 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15067)
;
15068 }
15069}
15070
15071/// Determine if tag kind is a class-key compatible with
15072/// class for redeclaration (class, struct, or __interface).
15073///
15074/// \returns true iff the tag kind is compatible.
15075static bool isClassCompatTagKind(TagTypeKind Tag)
15076{
15077 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15078}
15079
15080Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15081 TagTypeKind TTK) {
15082 if (isa<TypedefDecl>(PrevDecl))
15083 return NTK_Typedef;
15084 else if (isa<TypeAliasDecl>(PrevDecl))
15085 return NTK_TypeAlias;
15086 else if (isa<ClassTemplateDecl>(PrevDecl))
15087 return NTK_Template;
15088 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15089 return NTK_TypeAliasTemplate;
15090 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15091 return NTK_TemplateTemplateArgument;
15092 switch (TTK) {
15093 case TTK_Struct:
15094 case TTK_Interface:
15095 case TTK_Class:
15096 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15097 case TTK_Union:
15098 return NTK_NonUnion;
15099 case TTK_Enum:
15100 return NTK_NonEnum;
15101 }
15102 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15102)
;
15103}
15104
15105/// Determine whether a tag with a given kind is acceptable
15106/// as a redeclaration of the given tag declaration.
15107///
15108/// \returns true if the new tag kind is acceptable, false otherwise.
15109bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15110 TagTypeKind NewTag, bool isDefinition,
15111 SourceLocation NewTagLoc,
15112 const IdentifierInfo *Name) {
15113 // C++ [dcl.type.elab]p3:
15114 // The class-key or enum keyword present in the
15115 // elaborated-type-specifier shall agree in kind with the
15116 // declaration to which the name in the elaborated-type-specifier
15117 // refers. This rule also applies to the form of
15118 // elaborated-type-specifier that declares a class-name or
15119 // friend class since it can be construed as referring to the
15120 // definition of the class. Thus, in any
15121 // elaborated-type-specifier, the enum keyword shall be used to
15122 // refer to an enumeration (7.2), the union class-key shall be
15123 // used to refer to a union (clause 9), and either the class or
15124 // struct class-key shall be used to refer to a class (clause 9)
15125 // declared using the class or struct class-key.
15126 TagTypeKind OldTag = Previous->getTagKind();
15127 if (OldTag != NewTag &&
15128 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15129 return false;
15130
15131 // Tags are compatible, but we might still want to warn on mismatched tags.
15132 // Non-class tags can't be mismatched at this point.
15133 if (!isClassCompatTagKind(NewTag))
15134 return true;
15135
15136 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15137 // by our warning analysis. We don't want to warn about mismatches with (eg)
15138 // declarations in system headers that are designed to be specialized, but if
15139 // a user asks us to warn, we should warn if their code contains mismatched
15140 // declarations.
15141 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15142 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15143 Loc);
15144 };
15145 if (IsIgnoredLoc(NewTagLoc))
15146 return true;
15147
15148 auto IsIgnored = [&](const TagDecl *Tag) {
15149 return IsIgnoredLoc(Tag->getLocation());
15150 };
15151 while (IsIgnored(Previous)) {
15152 Previous = Previous->getPreviousDecl();
15153 if (!Previous)
15154 return true;
15155 OldTag = Previous->getTagKind();
15156 }
15157
15158 bool isTemplate = false;
15159 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15160 isTemplate = Record->getDescribedClassTemplate();
15161
15162 if (inTemplateInstantiation()) {
15163 if (OldTag != NewTag) {
15164 // In a template instantiation, do not offer fix-its for tag mismatches
15165 // since they usually mess up the template instead of fixing the problem.
15166 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15167 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15168 << getRedeclDiagFromTagKind(OldTag);
15169 // FIXME: Note previous location?
15170 }
15171 return true;
15172 }
15173
15174 if (isDefinition) {
15175 // On definitions, check all previous tags and issue a fix-it for each
15176 // one that doesn't match the current tag.
15177 if (Previous->getDefinition()) {
15178 // Don't suggest fix-its for redefinitions.
15179 return true;
15180 }
15181
15182 bool previousMismatch = false;
15183 for (const TagDecl *I : Previous->redecls()) {
15184 if (I->getTagKind() != NewTag) {
15185 // Ignore previous declarations for which the warning was disabled.
15186 if (IsIgnored(I))
15187 continue;
15188
15189 if (!previousMismatch) {
15190 previousMismatch = true;
15191 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15192 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15193 << getRedeclDiagFromTagKind(I->getTagKind());
15194 }
15195 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15196 << getRedeclDiagFromTagKind(NewTag)
15197 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15198 TypeWithKeyword::getTagTypeKindName(NewTag));
15199 }
15200 }
15201 return true;
15202 }
15203
15204 // Identify the prevailing tag kind: this is the kind of the definition (if
15205 // there is a non-ignored definition), or otherwise the kind of the prior
15206 // (non-ignored) declaration.
15207 const TagDecl *PrevDef = Previous->getDefinition();
15208 if (PrevDef && IsIgnored(PrevDef))
15209 PrevDef = nullptr;
15210 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15211 if (Redecl->getTagKind() != NewTag) {
15212 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15213 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15214 << getRedeclDiagFromTagKind(OldTag);
15215 Diag(Redecl->getLocation(), diag::note_previous_use);
15216
15217 // If there is a previous definition, suggest a fix-it.
15218 if (PrevDef) {
15219 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15220 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15221 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15222 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15223 }
15224 }
15225
15226 return true;
15227}
15228
15229/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15230/// from an outer enclosing namespace or file scope inside a friend declaration.
15231/// This should provide the commented out code in the following snippet:
15232/// namespace N {
15233/// struct X;
15234/// namespace M {
15235/// struct Y { friend struct /*N::*/ X; };
15236/// }
15237/// }
15238static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15239 SourceLocation NameLoc) {
15240 // While the decl is in a namespace, do repeated lookup of that name and see
15241 // if we get the same namespace back. If we do not, continue until
15242 // translation unit scope, at which point we have a fully qualified NNS.
15243 SmallVector<IdentifierInfo *, 4> Namespaces;
15244 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15245 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15246 // This tag should be declared in a namespace, which can only be enclosed by
15247 // other namespaces. Bail if there's an anonymous namespace in the chain.
15248 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15249 if (!Namespace || Namespace->isAnonymousNamespace())
15250 return FixItHint();
15251 IdentifierInfo *II = Namespace->getIdentifier();
15252 Namespaces.push_back(II);
15253 NamedDecl *Lookup = SemaRef.LookupSingleName(
15254 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15255 if (Lookup == Namespace)
15256 break;
15257 }
15258
15259 // Once we have all the namespaces, reverse them to go outermost first, and
15260 // build an NNS.
15261 SmallString<64> Insertion;
15262 llvm::raw_svector_ostream OS(Insertion);
15263 if (DC->isTranslationUnit())
15264 OS << "::";
15265 std::reverse(Namespaces.begin(), Namespaces.end());
15266 for (auto *II : Namespaces)
15267 OS << II->getName() << "::";
15268 return FixItHint::CreateInsertion(NameLoc, Insertion);
15269}
15270
15271/// Determine whether a tag originally declared in context \p OldDC can
15272/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15273/// found a declaration in \p OldDC as a previous decl, perhaps through a
15274/// using-declaration).
15275static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15276 DeclContext *NewDC) {
15277 OldDC = OldDC->getRedeclContext();
15278 NewDC = NewDC->getRedeclContext();
15279
15280 if (OldDC->Equals(NewDC))
15281 return true;
15282
15283 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15284 // encloses the other).
15285 if (S.getLangOpts().MSVCCompat &&
15286 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15287 return true;
15288
15289 return false;
15290}
15291
15292/// This is invoked when we see 'struct foo' or 'struct {'. In the
15293/// former case, Name will be non-null. In the later case, Name will be null.
15294/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15295/// reference/declaration/definition of a tag.
15296///
15297/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15298/// trailing-type-specifier) other than one in an alias-declaration.
15299///
15300/// \param SkipBody If non-null, will be set to indicate if the caller should
15301/// skip the definition of this tag and treat it as if it were a declaration.
15302Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15303 SourceLocation KWLoc, CXXScopeSpec &SS,
15304 IdentifierInfo *Name, SourceLocation NameLoc,
15305 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15306 SourceLocation ModulePrivateLoc,
15307 MultiTemplateParamsArg TemplateParameterLists,
15308 bool &OwnedDecl, bool &IsDependent,
15309 SourceLocation ScopedEnumKWLoc,
15310 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15311 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15312 SkipBodyInfo *SkipBody) {
15313 // If this is not a definition, it must have a name.
15314 IdentifierInfo *OrigName = Name;
15315 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15316, __PRETTY_FUNCTION__))
15316 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15316, __PRETTY_FUNCTION__))
;
15317 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15317, __PRETTY_FUNCTION__))
;
15318
15319 OwnedDecl = false;
15320 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15321 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15322
15323 // FIXME: Check member specializations more carefully.
15324 bool isMemberSpecialization = false;
15325 bool Invalid = false;
15326
15327 // We only need to do this matching if we have template parameters
15328 // or a scope specifier, which also conveniently avoids this work
15329 // for non-C++ cases.
15330 if (TemplateParameterLists.size() > 0 ||
15331 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15332 if (TemplateParameterList *TemplateParams =
15333 MatchTemplateParametersToScopeSpecifier(
15334 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15335 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15336 if (Kind == TTK_Enum) {
15337 Diag(KWLoc, diag::err_enum_template);
15338 return nullptr;
15339 }
15340
15341 if (TemplateParams->size() > 0) {
15342 // This is a declaration or definition of a class template (which may
15343 // be a member of another template).
15344
15345 if (Invalid)
15346 return nullptr;
15347
15348 OwnedDecl = false;
15349 DeclResult Result = CheckClassTemplate(
15350 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15351 AS, ModulePrivateLoc,
15352 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15353 TemplateParameterLists.data(), SkipBody);
15354 return Result.get();
15355 } else {
15356 // The "template<>" header is extraneous.
15357 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15358 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15359 isMemberSpecialization = true;
15360 }
15361 }
15362
15363 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15364 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15365 return nullptr;
15366 }
15367
15368 // Figure out the underlying type if this a enum declaration. We need to do
15369 // this early, because it's needed to detect if this is an incompatible
15370 // redeclaration.
15371 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15372 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15373
15374 if (Kind == TTK_Enum) {
15375 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15376 // No underlying type explicitly specified, or we failed to parse the
15377 // type, default to int.
15378 EnumUnderlying = Context.IntTy.getTypePtr();
15379 } else if (UnderlyingType.get()) {
15380 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15381 // integral type; any cv-qualification is ignored.
15382 TypeSourceInfo *TI = nullptr;
15383 GetTypeFromParser(UnderlyingType.get(), &TI);
15384 EnumUnderlying = TI;
15385
15386 if (CheckEnumUnderlyingType(TI))
15387 // Recover by falling back to int.
15388 EnumUnderlying = Context.IntTy.getTypePtr();
15389
15390 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15391 UPPC_FixedUnderlyingType))
15392 EnumUnderlying = Context.IntTy.getTypePtr();
15393
15394 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15395 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15396 // of 'int'. However, if this is an unfixed forward declaration, don't set
15397 // the underlying type unless the user enables -fms-compatibility. This
15398 // makes unfixed forward declared enums incomplete and is more conforming.
15399 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15400 EnumUnderlying = Context.IntTy.getTypePtr();
15401 }
15402 }
15403
15404 DeclContext *SearchDC = CurContext;
15405 DeclContext *DC = CurContext;
15406 bool isStdBadAlloc = false;
15407 bool isStdAlignValT = false;
15408
15409 RedeclarationKind Redecl = forRedeclarationInCurContext();
15410 if (TUK == TUK_Friend || TUK == TUK_Reference)
15411 Redecl = NotForRedeclaration;
15412
15413 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15414 /// implemented asks for structural equivalence checking, the returned decl
15415 /// here is passed back to the parser, allowing the tag body to be parsed.
15416 auto createTagFromNewDecl = [&]() -> TagDecl * {
15417 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15417, __PRETTY_FUNCTION__))
;
15418 // If there is an identifier, use the location of the identifier as the
15419 // location of the decl, otherwise use the location of the struct/union
15420 // keyword.
15421 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15422 TagDecl *New = nullptr;
15423
15424 if (Kind == TTK_Enum) {
15425 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15426 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15427 // If this is an undefined enum, bail.
15428 if (TUK != TUK_Definition && !Invalid)
15429 return nullptr;
15430 if (EnumUnderlying) {
15431 EnumDecl *ED = cast<EnumDecl>(New);
15432 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15433 ED->setIntegerTypeSourceInfo(TI);
15434 else
15435 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15436 ED->setPromotionType(ED->getIntegerType());
15437 }
15438 } else { // struct/union
15439 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15440 nullptr);
15441 }
15442
15443 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15444 // Add alignment attributes if necessary; these attributes are checked
15445 // when the ASTContext lays out the structure.
15446 //
15447 // It is important for implementing the correct semantics that this
15448 // happen here (in ActOnTag). The #pragma pack stack is
15449 // maintained as a result of parser callbacks which can occur at
15450 // many points during the parsing of a struct declaration (because
15451 // the #pragma tokens are effectively skipped over during the
15452 // parsing of the struct).
15453 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15454 AddAlignmentAttributesForRecord(RD);
15455 AddMsStructLayoutForRecord(RD);
15456 }
15457 }
15458 New->setLexicalDeclContext(CurContext);
15459 return New;
15460 };
15461
15462 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15463 if (Name && SS.isNotEmpty()) {
15464 // We have a nested-name tag ('struct foo::bar').
15465
15466 // Check for invalid 'foo::'.
15467 if (SS.isInvalid()) {
15468 Name = nullptr;
15469 goto CreateNewDecl;
15470 }
15471
15472 // If this is a friend or a reference to a class in a dependent
15473 // context, don't try to make a decl for it.
15474 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15475 DC = computeDeclContext(SS, false);
15476 if (!DC) {
15477 IsDependent = true;
15478 return nullptr;
15479 }
15480 } else {
15481 DC = computeDeclContext(SS, true);
15482 if (!DC) {
15483 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15484 << SS.getRange();
15485 return nullptr;
15486 }
15487 }
15488
15489 if (RequireCompleteDeclContext(SS, DC))
15490 return nullptr;
15491
15492 SearchDC = DC;
15493 // Look-up name inside 'foo::'.
15494 LookupQualifiedName(Previous, DC);
15495
15496 if (Previous.isAmbiguous())
15497 return nullptr;
15498
15499 if (Previous.empty()) {
15500 // Name lookup did not find anything. However, if the
15501 // nested-name-specifier refers to the current instantiation,
15502 // and that current instantiation has any dependent base
15503 // classes, we might find something at instantiation time: treat
15504 // this as a dependent elaborated-type-specifier.
15505 // But this only makes any sense for reference-like lookups.
15506 if (Previous.wasNotFoundInCurrentInstantiation() &&
15507 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15508 IsDependent = true;
15509 return nullptr;
15510 }
15511
15512 // A tag 'foo::bar' must already exist.
15513 Diag(NameLoc, diag::err_not_tag_in_scope)
15514 << Kind << Name << DC << SS.getRange();
15515 Name = nullptr;
15516 Invalid = true;
15517 goto CreateNewDecl;
15518 }
15519 } else if (Name) {
15520 // C++14 [class.mem]p14:
15521 // If T is the name of a class, then each of the following shall have a
15522 // name different from T:
15523 // -- every member of class T that is itself a type
15524 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15525 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15526 return nullptr;
15527
15528 // If this is a named struct, check to see if there was a previous forward
15529 // declaration or definition.
15530 // FIXME: We're looking into outer scopes here, even when we
15531 // shouldn't be. Doing so can result in ambiguities that we
15532 // shouldn't be diagnosing.
15533 LookupName(Previous, S);
15534
15535 // When declaring or defining a tag, ignore ambiguities introduced
15536 // by types using'ed into this scope.
15537 if (Previous.isAmbiguous() &&
15538 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15539 LookupResult::Filter F = Previous.makeFilter();
15540 while (F.hasNext()) {
15541 NamedDecl *ND = F.next();
15542 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15543 SearchDC->getRedeclContext()))
15544 F.erase();
15545 }
15546 F.done();
15547 }
15548
15549 // C++11 [namespace.memdef]p3:
15550 // If the name in a friend declaration is neither qualified nor
15551 // a template-id and the declaration is a function or an
15552 // elaborated-type-specifier, the lookup to determine whether
15553 // the entity has been previously declared shall not consider
15554 // any scopes outside the innermost enclosing namespace.
15555 //
15556 // MSVC doesn't implement the above rule for types, so a friend tag
15557 // declaration may be a redeclaration of a type declared in an enclosing
15558 // scope. They do implement this rule for friend functions.
15559 //
15560 // Does it matter that this should be by scope instead of by
15561 // semantic context?
15562 if (!Previous.empty() && TUK == TUK_Friend) {
15563 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15564 LookupResult::Filter F = Previous.makeFilter();
15565 bool FriendSawTagOutsideEnclosingNamespace = false;
15566 while (F.hasNext()) {
15567 NamedDecl *ND = F.next();
15568 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15569 if (DC->isFileContext() &&
15570 !EnclosingNS->Encloses(ND->getDeclContext())) {
15571 if (getLangOpts().MSVCCompat)
15572 FriendSawTagOutsideEnclosingNamespace = true;
15573 else
15574 F.erase();
15575 }
15576 }
15577 F.done();
15578
15579 // Diagnose this MSVC extension in the easy case where lookup would have
15580 // unambiguously found something outside the enclosing namespace.
15581 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15582 NamedDecl *ND = Previous.getFoundDecl();
15583 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15584 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15585 }
15586 }
15587
15588 // Note: there used to be some attempt at recovery here.
15589 if (Previous.isAmbiguous())
15590 return nullptr;
15591
15592 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15593 // FIXME: This makes sure that we ignore the contexts associated
15594 // with C structs, unions, and enums when looking for a matching
15595 // tag declaration or definition. See the similar lookup tweak
15596 // in Sema::LookupName; is there a better way to deal with this?
15597 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15598 SearchDC = SearchDC->getParent();
15599 }
15600 }
15601
15602 if (Previous.isSingleResult() &&
15603 Previous.getFoundDecl()->isTemplateParameter()) {
15604 // Maybe we will complain about the shadowed template parameter.
15605 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15606 // Just pretend that we didn't see the previous declaration.
15607 Previous.clear();
15608 }
15609
15610 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15611 DC->Equals(getStdNamespace())) {
15612 if (Name->isStr("bad_alloc")) {
15613 // This is a declaration of or a reference to "std::bad_alloc".
15614 isStdBadAlloc = true;
15615
15616 // If std::bad_alloc has been implicitly declared (but made invisible to
15617 // name lookup), fill in this implicit declaration as the previous
15618 // declaration, so that the declarations get chained appropriately.
15619 if (Previous.empty() && StdBadAlloc)
15620 Previous.addDecl(getStdBadAlloc());
15621 } else if (Name->isStr("align_val_t")) {
15622 isStdAlignValT = true;
15623 if (Previous.empty() && StdAlignValT)
15624 Previous.addDecl(getStdAlignValT());
15625 }
15626 }
15627
15628 // If we didn't find a previous declaration, and this is a reference
15629 // (or friend reference), move to the correct scope. In C++, we
15630 // also need to do a redeclaration lookup there, just in case
15631 // there's a shadow friend decl.
15632 if (Name && Previous.empty() &&
15633 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15634 if (Invalid) goto CreateNewDecl;
15635 assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15635, __PRETTY_FUNCTION__))
;
15636
15637 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15638 // C++ [basic.scope.pdecl]p5:
15639 // -- for an elaborated-type-specifier of the form
15640 //
15641 // class-key identifier
15642 //
15643 // if the elaborated-type-specifier is used in the
15644 // decl-specifier-seq or parameter-declaration-clause of a
15645 // function defined in namespace scope, the identifier is
15646 // declared as a class-name in the namespace that contains
15647 // the declaration; otherwise, except as a friend
15648 // declaration, the identifier is declared in the smallest
15649 // non-class, non-function-prototype scope that contains the
15650 // declaration.
15651 //
15652 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15653 // C structs and unions.
15654 //
15655 // It is an error in C++ to declare (rather than define) an enum
15656 // type, including via an elaborated type specifier. We'll
15657 // diagnose that later; for now, declare the enum in the same
15658 // scope as we would have picked for any other tag type.
15659 //
15660 // GNU C also supports this behavior as part of its incomplete
15661 // enum types extension, while GNU C++ does not.
15662 //
15663 // Find the context where we'll be declaring the tag.
15664 // FIXME: We would like to maintain the current DeclContext as the
15665 // lexical context,
15666 SearchDC = getTagInjectionContext(SearchDC);
15667
15668 // Find the scope where we'll be declaring the tag.
15669 S = getTagInjectionScope(S, getLangOpts());
15670 } else {
15671 assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 15671, __PRETTY_FUNCTION__))
;
15672 // C++ [namespace.memdef]p3:
15673 // If a friend declaration in a non-local class first declares a
15674 // class or function, the friend class or function is a member of
15675 // the innermost enclosing namespace.
15676 SearchDC = SearchDC->getEnclosingNamespaceContext();
15677 }
15678
15679 // In C++, we need to do a redeclaration lookup to properly
15680 // diagnose some problems.
15681 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15682 // hidden declaration so that we don't get ambiguity errors when using a
15683 // type declared by an elaborated-type-specifier. In C that is not correct
15684 // and we should instead merge compatible types found by lookup.
15685 if (getLangOpts().CPlusPlus) {
15686 // FIXME: This can perform qualified lookups into function contexts,
15687 // which are meaningless.
15688 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15689 LookupQualifiedName(Previous, SearchDC);
15690 } else {
15691 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15692 LookupName(Previous, S);
15693 }
15694 }
15695
15696 // If we have a known previous declaration to use, then use it.
15697 if (Previous.empty() && SkipBody && SkipBody->Previous)
15698 Previous.addDecl(SkipBody->Previous);
15699
15700 if (!Previous.empty()) {
15701 NamedDecl *PrevDecl = Previous.getFoundDecl();
15702 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15703
15704 // It's okay to have a tag decl in the same scope as a typedef
15705 // which hides a tag decl in the same scope. Finding this
15706 // insanity with a redeclaration lookup can only actually happen
15707 // in C++.
15708 //
15709 // This is also okay for elaborated-type-specifiers, which is
15710 // technically forbidden by the current standard but which is
15711 // okay according to the likely resolution of an open issue;
15712 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15713 if (getLangOpts().CPlusPlus) {
15714 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15715 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15716 TagDecl *Tag = TT->getDecl();
15717 if (Tag->getDeclName() == Name &&
15718 Tag->getDeclContext()->getRedeclContext()
15719 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15720 PrevDecl = Tag;
15721 Previous.clear();
15722 Previous.addDecl(Tag);
15723 Previous.resolveKind();
15724 }
15725 }
15726 }
15727 }
15728
15729 // If this is a redeclaration of a using shadow declaration, it must
15730 // declare a tag in the same context. In MSVC mode, we allow a
15731 // redefinition if either context is within the other.
15732 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15733 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15734 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15735 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15736 !(OldTag && isAcceptableTagRedeclContext(
15737 *this, OldTag->getDeclContext(), SearchDC))) {
15738 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15739 Diag(Shadow->getTargetDecl()->getLocation(),
15740 diag::note_using_decl_target);
15741 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15742 << 0;
15743 // Recover by ignoring the old declaration.
15744 Previous.clear();
15745 goto CreateNewDecl;
15746 }
15747 }
15748
15749 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15750 // If this is a use of a previous tag, or if the tag is already declared
15751 // in the same scope (so that the definition/declaration completes or
15752 // rementions the tag), reuse the decl.
15753 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15754 isDeclInScope(DirectPrevDecl, SearchDC, S,
15755 SS.isNotEmpty() || isMemberSpecialization)) {
15756 // Make sure that this wasn't declared as an enum and now used as a
15757 // struct or something similar.
15758 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15759 TUK == TUK_Definition, KWLoc,
15760 Name)) {
15761 bool SafeToContinue
15762 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15763 Kind != TTK_Enum);
15764 if (SafeToContinue)
15765 Diag(KWLoc, diag::err_use_with_wrong_tag)
15766 << Name
15767 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15768 PrevTagDecl->getKindName());
15769 else
15770 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15771 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15772
15773 if (SafeToContinue)
15774 Kind = PrevTagDecl->getTagKind();
15775 else {
15776 // Recover by making this an anonymous redefinition.
15777 Name = nullptr;
15778 Previous.clear();
15779 Invalid = true;
15780 }
15781 }
15782
15783 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15784 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15785 if (TUK == TUK_Reference || TUK == TUK_Friend)
15786 return PrevTagDecl;
15787
15788 QualType EnumUnderlyingTy;
15789 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15790 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15791 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15792 EnumUnderlyingTy = QualType(T, 0);
15793
15794 // All conflicts with previous declarations are recovered by
15795 // returning the previous declaration, unless this is a definition,
15796 // in which case we want the caller to bail out.
15797 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15798 ScopedEnum, EnumUnderlyingTy,
15799 IsFixed, PrevEnum))
15800 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15801 }
15802
15803 // C++11 [class.mem]p1:
15804 // A member shall not be declared twice in the member-specification,
15805 // except that a nested class or member class template can be declared
15806 // and then later defined.
15807 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15808 S->isDeclScope(PrevDecl)) {
15809 Diag(NameLoc, diag::ext_member_redeclared);
15810 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15811 }
15812
15813 if (!Invalid) {
15814 // If this is a use, just return the declaration we found, unless
15815 // we have attributes.
15816 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15817 if (!Attrs.empty()) {
15818 // FIXME: Diagnose these attributes. For now, we create a new
15819 // declaration to hold them.
15820 } else if (TUK == TUK_Reference &&
15821 (PrevTagDecl->getFriendObjectKind() ==
15822 Decl::FOK_Undeclared ||
15823 PrevDecl->getOwningModule() != getCurrentModule()) &&
15824 SS.isEmpty()) {
15825 // This declaration is a reference to an existing entity, but
15826 // has different visibility from that entity: it either makes
15827 // a friend visible or it makes a type visible in a new module.
15828 // In either case, create a new declaration. We only do this if
15829 // the declaration would have meant the same thing if no prior
15830 // declaration were found, that is, if it was found in the same
15831 // scope where we would have injected a declaration.
15832 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15833 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15834 return PrevTagDecl;
15835 // This is in the injected scope, create a new declaration in
15836 // that scope.
15837 S = getTagInjectionScope(S, getLangOpts());
15838 } else {
15839 return PrevTagDecl;
15840 }
15841 }
15842
15843 // Diagnose attempts to redefine a tag.
15844 if (TUK == TUK_Definition) {
15845 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15846 // If we're defining a specialization and the previous definition
15847 // is from an implicit instantiation, don't emit an error
15848 // here; we'll catch this in the general case below.
15849 bool IsExplicitSpecializationAfterInstantiation = false;
15850 if (isMemberSpecialization) {
15851 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15852 IsExplicitSpecializationAfterInstantiation =
15853 RD->getTemplateSpecializationKind() !=
15854 TSK_ExplicitSpecialization;
15855 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15856 IsExplicitSpecializationAfterInstantiation =
15857 ED->getTemplateSpecializationKind() !=
15858 TSK_ExplicitSpecialization;
15859 }
15860
15861 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15862 // not keep more that one definition around (merge them). However,
15863 // ensure the decl passes the structural compatibility check in
15864 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15865 NamedDecl *Hidden = nullptr;
15866 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15867 // There is a definition of this tag, but it is not visible. We
15868 // explicitly make use of C++'s one definition rule here, and
15869 // assume that this definition is identical to the hidden one
15870 // we already have. Make the existing definition visible and
15871 // use it in place of this one.
15872 if (!getLangOpts().CPlusPlus) {
15873 // Postpone making the old definition visible until after we
15874 // complete parsing the new one and do the structural
15875 // comparison.
15876 SkipBody->CheckSameAsPrevious = true;
15877 SkipBody->New = createTagFromNewDecl();
15878 SkipBody->Previous = Def;
15879 return Def;
15880 } else {
15881 SkipBody->ShouldSkip = true;
15882 SkipBody->Previous = Def;
15883 makeMergedDefinitionVisible(Hidden);
15884 // Carry on and handle it like a normal definition. We'll
15885 // skip starting the definitiion later.
15886 }
15887 } else if (!IsExplicitSpecializationAfterInstantiation) {
15888 // A redeclaration in function prototype scope in C isn't
15889 // visible elsewhere, so merely issue a warning.
15890 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15891 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15892 else
15893 Diag(NameLoc, diag::err_redefinition) << Name;
15894 notePreviousDefinition(Def,
15895 NameLoc.isValid() ? NameLoc : KWLoc);
15896 // If this is a redefinition, recover by making this
15897 // struct be anonymous, which will make any later
15898 // references get the previous definition.
15899 Name = nullptr;
15900 Previous.clear();
15901 Invalid = true;
15902 }
15903 } else {
15904 // If the type is currently being defined, complain
15905 // about a nested redefinition.
15906 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15907 if (TD->isBeingDefined()) {
15908 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15909 Diag(PrevTagDecl->getLocation(),
15910 diag::note_previous_definition);
15911 Name = nullptr;
15912 Previous.clear();
15913 Invalid = true;
15914 }
15915 }
15916
15917 // Okay, this is definition of a previously declared or referenced
15918 // tag. We're going to create a new Decl for it.
15919 }
15920
15921 // Okay, we're going to make a redeclaration. If this is some kind
15922 // of reference, make sure we build the redeclaration in the same DC
15923 // as the original, and ignore the current access specifier.
15924 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15925 SearchDC = PrevTagDecl->getDeclContext();
15926 AS = AS_none;
15927 }
15928 }
15929 // If we get here we have (another) forward declaration or we
15930 // have a definition. Just create a new decl.
15931
15932 } else {
15933 // If we get here, this is a definition of a new tag type in a nested
15934 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15935 // new decl/type. We set PrevDecl to NULL so that the entities
15936 // have distinct types.
15937 Previous.clear();
15938 }
15939 // If we get here, we're going to create a new Decl. If PrevDecl
15940 // is non-NULL, it's a definition of the tag declared by
15941 // PrevDecl. If it's NULL, we have a new definition.
15942
15943 // Otherwise, PrevDecl is not a tag, but was found with tag
15944 // lookup. This is only actually possible in C++, where a few
15945 // things like templates still live in the tag namespace.
15946 } else {
15947 // Use a better diagnostic if an elaborated-type-specifier
15948 // found the wrong kind of type on the first
15949 // (non-redeclaration) lookup.
15950 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15951 !Previous.isForRedeclaration()) {
15952 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15953 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15954 << Kind;
15955 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15956 Invalid = true;
15957
15958 // Otherwise, only diagnose if the declaration is in scope.
15959 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15960 SS.isNotEmpty() || isMemberSpecialization)) {
15961 // do nothing
15962
15963 // Diagnose implicit declarations introduced by elaborated types.
15964 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15965 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15966 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15967 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15968 Invalid = true;
15969
15970 // Otherwise it's a declaration. Call out a particularly common
15971 // case here.
15972 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15973 unsigned Kind = 0;
15974 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15975 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15976 << Name << Kind << TND->getUnderlyingType();
15977 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15978 Invalid = true;
15979
15980 // Otherwise, diagnose.
15981 } else {
15982 // The tag name clashes with something else in the target scope,
15983 // issue an error and recover by making this tag be anonymous.
15984 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
15985 notePreviousDefinition(PrevDecl, NameLoc);
15986 Name = nullptr;
15987 Invalid = true;
15988 }
15989
15990 // The existing declaration isn't relevant to us; we're in a
15991 // new scope, so clear out the previous declaration.
15992 Previous.clear();
15993 }
15994 }
15995
15996CreateNewDecl:
15997
15998 TagDecl *PrevDecl = nullptr;
15999 if (Previous.isSingleResult())
16000 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16001
16002 // If there is an identifier, use the location of the identifier as the
16003 // location of the decl, otherwise use the location of the struct/union
16004 // keyword.
16005 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16006
16007 // Otherwise, create a new declaration. If there is a previous
16008 // declaration of the same entity, the two will be linked via
16009 // PrevDecl.
16010 TagDecl *New;
16011
16012 if (Kind == TTK_Enum) {
16013 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16014 // enum X { A, B, C } D; D should chain to X.
16015 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16016 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16017 ScopedEnumUsesClassTag, IsFixed);
16018
16019 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16020 StdAlignValT = cast<EnumDecl>(New);
16021
16022 // If this is an undefined enum, warn.
16023 if (TUK != TUK_Definition && !Invalid) {
16024 TagDecl *Def;
16025 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16026 // C++0x: 7.2p2: opaque-enum-declaration.
16027 // Conflicts are diagnosed above. Do nothing.
16028 }
16029 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16030 Diag(Loc, diag::ext_forward_ref_enum_def)
16031 << New;
16032 Diag(Def->getLocation(), diag::note_previous_definition);
16033 } else {
16034 unsigned DiagID = diag::ext_forward_ref_enum;
16035 if (getLangOpts().MSVCCompat)
16036 DiagID = diag::ext_ms_forward_ref_enum;
16037 else if (getLangOpts().CPlusPlus)
16038 DiagID = diag::err_forward_ref_enum;
16039 Diag(Loc, DiagID);
16040 }
16041 }
16042
16043 if (EnumUnderlying) {
16044 EnumDecl *ED = cast<EnumDecl>(New);
16045 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16046 ED->setIntegerTypeSourceInfo(TI);
16047 else
16048 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16049 ED->setPromotionType(ED->getIntegerType());
16050 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16050, __PRETTY_FUNCTION__))
;
16051 }
16052 } else {
16053 // struct/union/class
16054
16055 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16056 // struct X { int A; } D; D should chain to X.
16057 if (getLangOpts().CPlusPlus) {
16058 // FIXME: Look for a way to use RecordDecl for simple structs.
16059 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16060 cast_or_null<CXXRecordDecl>(PrevDecl));
16061
16062 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16063 StdBadAlloc = cast<CXXRecordDecl>(New);
16064 } else
16065 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16066 cast_or_null<RecordDecl>(PrevDecl));
16067 }
16068
16069 // C++11 [dcl.type]p3:
16070 // A type-specifier-seq shall not define a class or enumeration [...].
16071 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16072 TUK == TUK_Definition) {
16073 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16074 << Context.getTagDeclType(New);
16075 Invalid = true;
16076 }
16077
16078 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16079 DC->getDeclKind() == Decl::Enum) {
16080 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16081 << Context.getTagDeclType(New);
16082 Invalid = true;
16083 }
16084
16085 // Maybe add qualifier info.
16086 if (SS.isNotEmpty()) {
16087 if (SS.isSet()) {
16088 // If this is either a declaration or a definition, check the
16089 // nested-name-specifier against the current context.
16090 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16091 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16092 isMemberSpecialization))
16093 Invalid = true;
16094
16095 New->setQualifierInfo(SS.getWithLocInContext(Context));
16096 if (TemplateParameterLists.size() > 0) {
16097 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16098 }
16099 }
16100 else
16101 Invalid = true;
16102 }
16103
16104 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16105 // Add alignment attributes if necessary; these attributes are checked when
16106 // the ASTContext lays out the structure.
16107 //
16108 // It is important for implementing the correct semantics that this
16109 // happen here (in ActOnTag). The #pragma pack stack is
16110 // maintained as a result of parser callbacks which can occur at
16111 // many points during the parsing of a struct declaration (because
16112 // the #pragma tokens are effectively skipped over during the
16113 // parsing of the struct).
16114 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16115 AddAlignmentAttributesForRecord(RD);
16116 AddMsStructLayoutForRecord(RD);
16117 }
16118 }
16119
16120 if (ModulePrivateLoc.isValid()) {
16121 if (isMemberSpecialization)
16122 Diag(New->getLocation(), diag::err_module_private_specialization)
16123 << 2
16124 << FixItHint::CreateRemoval(ModulePrivateLoc);
16125 // __module_private__ does not apply to local classes. However, we only
16126 // diagnose this as an error when the declaration specifiers are
16127 // freestanding. Here, we just ignore the __module_private__.
16128 else if (!SearchDC->isFunctionOrMethod())
16129 New->setModulePrivate();
16130 }
16131
16132 // If this is a specialization of a member class (of a class template),
16133 // check the specialization.
16134 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16135 Invalid = true;
16136
16137 // If we're declaring or defining a tag in function prototype scope in C,
16138 // note that this type can only be used within the function and add it to
16139 // the list of decls to inject into the function definition scope.
16140 if ((Name || Kind == TTK_Enum) &&
16141 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16142 if (getLangOpts().CPlusPlus) {
16143 // C++ [dcl.fct]p6:
16144 // Types shall not be defined in return or parameter types.
16145 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16146 Diag(Loc, diag::err_type_defined_in_param_type)
16147 << Name;
16148 Invalid = true;
16149 }
16150 } else if (!PrevDecl) {
16151 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16152 }
16153 }
16154
16155 if (Invalid)
16156 New->setInvalidDecl();
16157
16158 // Set the lexical context. If the tag has a C++ scope specifier, the
16159 // lexical context will be different from the semantic context.
16160 New->setLexicalDeclContext(CurContext);
16161
16162 // Mark this as a friend decl if applicable.
16163 // In Microsoft mode, a friend declaration also acts as a forward
16164 // declaration so we always pass true to setObjectOfFriendDecl to make
16165 // the tag name visible.
16166 if (TUK == TUK_Friend)
16167 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16168
16169 // Set the access specifier.
16170 if (!Invalid && SearchDC->isRecord())
16171 SetMemberAccessSpecifier(New, PrevDecl, AS);
16172
16173 if (PrevDecl)
16174 CheckRedeclarationModuleOwnership(New, PrevDecl);
16175
16176 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16177 New->startDefinition();
16178
16179 ProcessDeclAttributeList(S, New, Attrs);
16180 AddPragmaAttributes(S, New);
16181
16182 // If this has an identifier, add it to the scope stack.
16183 if (TUK == TUK_Friend) {
16184 // We might be replacing an existing declaration in the lookup tables;
16185 // if so, borrow its access specifier.
16186 if (PrevDecl)
16187 New->setAccess(PrevDecl->getAccess());
16188
16189 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16190 DC->makeDeclVisibleInContext(New);
16191 if (Name) // can be null along some error paths
16192 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16193 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16194 } else if (Name) {
16195 S = getNonFieldDeclScope(S);
16196 PushOnScopeChains(New, S, true);
16197 } else {
16198 CurContext->addDecl(New);
16199 }
16200
16201 // If this is the C FILE type, notify the AST context.
16202 if (IdentifierInfo *II = New->getIdentifier())
16203 if (!New->isInvalidDecl() &&
16204 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16205 II->isStr("FILE"))
16206 Context.setFILEDecl(New);
16207
16208 if (PrevDecl)
16209 mergeDeclAttributes(New, PrevDecl);
16210
16211 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16212 inferGslOwnerPointerAttribute(CXXRD);
16213
16214 // If there's a #pragma GCC visibility in scope, set the visibility of this
16215 // record.
16216 AddPushedVisibilityAttribute(New);
16217
16218 if (isMemberSpecialization && !New->isInvalidDecl())
16219 CompleteMemberSpecialization(New, Previous);
16220
16221 OwnedDecl = true;
16222 // In C++, don't return an invalid declaration. We can't recover well from
16223 // the cases where we make the type anonymous.
16224 if (Invalid && getLangOpts().CPlusPlus) {
16225 if (New->isBeingDefined())
16226 if (auto RD = dyn_cast<RecordDecl>(New))
16227 RD->completeDefinition();
16228 return nullptr;
16229 } else if (SkipBody && SkipBody->ShouldSkip) {
16230 return SkipBody->Previous;
16231 } else {
16232 return New;
16233 }
16234}
16235
16236void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16237 AdjustDeclIfTemplate(TagD);
16238 TagDecl *Tag = cast<TagDecl>(TagD);
16239
16240 // Enter the tag context.
16241 PushDeclContext(S, Tag);
16242
16243 ActOnDocumentableDecl(TagD);
16244
16245 // If there's a #pragma GCC visibility in scope, set the visibility of this
16246 // record.
16247 AddPushedVisibilityAttribute(Tag);
16248}
16249
16250bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16251 SkipBodyInfo &SkipBody) {
16252 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16253 return false;
16254
16255 // Make the previous decl visible.
16256 makeMergedDefinitionVisible(SkipBody.Previous);
16257 return true;
16258}
16259
16260Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16261 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16262, __PRETTY_FUNCTION__))
16262 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16262, __PRETTY_FUNCTION__))
;
16263 DeclContext *OCD = cast<DeclContext>(IDecl);
16264 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16265, __PRETTY_FUNCTION__))
16265 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16265, __PRETTY_FUNCTION__))
;
16266 CurContext = OCD;
16267 return IDecl;
16268}
16269
16270void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16271 SourceLocation FinalLoc,
16272 bool IsFinalSpelledSealed,
16273 SourceLocation LBraceLoc) {
16274 AdjustDeclIfTemplate(TagD);
16275 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16276
16277 FieldCollector->StartClass();
16278
16279 if (!Record->getIdentifier())
16280 return;
16281
16282 if (FinalLoc.isValid())
16283 Record->addAttr(FinalAttr::Create(
16284 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16285 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16286
16287 // C++ [class]p2:
16288 // [...] The class-name is also inserted into the scope of the
16289 // class itself; this is known as the injected-class-name. For
16290 // purposes of access checking, the injected-class-name is treated
16291 // as if it were a public member name.
16292 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16293 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16294 Record->getLocation(), Record->getIdentifier(),
16295 /*PrevDecl=*/nullptr,
16296 /*DelayTypeCreation=*/true);
16297 Context.getTypeDeclType(InjectedClassName, Record);
16298 InjectedClassName->setImplicit();
16299 InjectedClassName->setAccess(AS_public);
16300 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16301 InjectedClassName->setDescribedClassTemplate(Template);
16302 PushOnScopeChains(InjectedClassName, S);
16303 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16304, __PRETTY_FUNCTION__))
16304 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16304, __PRETTY_FUNCTION__))
;
16305}
16306
16307void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16308 SourceRange BraceRange) {
16309 AdjustDeclIfTemplate(TagD);
16310 TagDecl *Tag = cast<TagDecl>(TagD);
16311 Tag->setBraceRange(BraceRange);
16312
16313 // Make sure we "complete" the definition even it is invalid.
16314 if (Tag->isBeingDefined()) {
16315 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16315, __PRETTY_FUNCTION__))
;
16316 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16317 RD->completeDefinition();
16318 }
16319
16320 if (isa<CXXRecordDecl>(Tag)) {
16321 FieldCollector->FinishClass();
16322 }
16323
16324 // Exit this scope of this tag's definition.
16325 PopDeclContext();
16326
16327 if (getCurLexicalContext()->isObjCContainer() &&
16328 Tag->getDeclContext()->isFileContext())
16329 Tag->setTopLevelDeclInObjCContainer();
16330
16331 // Notify the consumer that we've defined a tag.
16332 if (!Tag->isInvalidDecl())
16333 Consumer.HandleTagDeclDefinition(Tag);
16334}
16335
16336void Sema::ActOnObjCContainerFinishDefinition() {
16337 // Exit this scope of this interface definition.
16338 PopDeclContext();
16339}
16340
16341void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16342 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16342, __PRETTY_FUNCTION__))
;
16343 OriginalLexicalContext = DC;
16344 ActOnObjCContainerFinishDefinition();
16345}
16346
16347void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16348 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16349 OriginalLexicalContext = nullptr;
16350}
16351
16352void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16353 AdjustDeclIfTemplate(TagD);
16354 TagDecl *Tag = cast<TagDecl>(TagD);
16355 Tag->setInvalidDecl();
16356
16357 // Make sure we "complete" the definition even it is invalid.
16358 if (Tag->isBeingDefined()) {
16359 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16360 RD->completeDefinition();
16361 }
16362
16363 // We're undoing ActOnTagStartDefinition here, not
16364 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16365 // the FieldCollector.
16366
16367 PopDeclContext();
16368}
16369
16370// Note that FieldName may be null for anonymous bitfields.
16371ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16372 IdentifierInfo *FieldName,
16373 QualType FieldTy, bool IsMsStruct,
16374 Expr *BitWidth, bool *ZeroWidth) {
16375 assert(BitWidth)((BitWidth) ? static_cast<void> (0) : __assert_fail ("BitWidth"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16375, __PRETTY_FUNCTION__))
;
16376 if (BitWidth->containsErrors())
16377 return ExprError();
16378
16379 // Default to true; that shouldn't confuse checks for emptiness
16380 if (ZeroWidth)
16381 *ZeroWidth = true;
16382
16383 // C99 6.7.2.1p4 - verify the field type.
16384 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16385 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16386 // Handle incomplete and sizeless types with a specific error.
16387 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16388 diag::err_field_incomplete_or_sizeless))
16389 return ExprError();
16390 if (FieldName)
16391 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16392 << FieldName << FieldTy << BitWidth->getSourceRange();
16393 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16394 << FieldTy << BitWidth->getSourceRange();
16395 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16396 UPPC_BitFieldWidth))
16397 return ExprError();
16398
16399 // If the bit-width is type- or value-dependent, don't try to check
16400 // it now.
16401 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16402 return BitWidth;
16403
16404 llvm::APSInt Value;
16405 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16406 if (ICE.isInvalid())
16407 return ICE;
16408 BitWidth = ICE.get();
16409
16410 if (Value != 0 && ZeroWidth)
16411 *ZeroWidth = false;
16412
16413 // Zero-width bitfield is ok for anonymous field.
16414 if (Value == 0 && FieldName)
16415 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16416
16417 if (Value.isSigned() && Value.isNegative()) {
16418 if (FieldName)
16419 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16420 << FieldName << Value.toString(10);
16421 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16422 << Value.toString(10);
16423 }
16424
16425 if (!FieldTy->isDependentType()) {
16426 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16427 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16428 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16429
16430 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16431 // ABI.
16432 bool CStdConstraintViolation =
16433 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16434 bool MSBitfieldViolation =
16435 Value.ugt(TypeStorageSize) &&
16436 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16437 if (CStdConstraintViolation || MSBitfieldViolation) {
16438 unsigned DiagWidth =
16439 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16440 if (FieldName)
16441 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16442 << FieldName << (unsigned)Value.getZExtValue()
16443 << !CStdConstraintViolation << DiagWidth;
16444
16445 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16446 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16447 << DiagWidth;
16448 }
16449
16450 // Warn on types where the user might conceivably expect to get all
16451 // specified bits as value bits: that's all integral types other than
16452 // 'bool'.
16453 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16454 if (FieldName)
16455 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16456 << FieldName << (unsigned)Value.getZExtValue()
16457 << (unsigned)TypeWidth;
16458 else
16459 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16460 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16461 }
16462 }
16463
16464 return BitWidth;
16465}
16466
16467/// ActOnField - Each field of a C struct/union is passed into this in order
16468/// to create a FieldDecl object for it.
16469Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16470 Declarator &D, Expr *BitfieldWidth) {
16471 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'
16472 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16473 /*InitStyle=*/ICIS_NoInit, AS_public);
16474 return Res;
16475}
16476
16477/// HandleField - Analyze a field of a C struct or a C++ data member.
16478///
16479FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16480 SourceLocation DeclStart,
16481 Declarator &D, Expr *BitWidth,
16482 InClassInitStyle InitStyle,
16483 AccessSpecifier AS) {
16484 if (D.isDecompositionDeclarator()) {
4
Calling 'Declarator::isDecompositionDeclarator'
13
Returning from 'Declarator::isDecompositionDeclarator'
14
Taking false branch
16485 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16486 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16487 << Decomp.getSourceRange();
16488 return nullptr;
16489 }
16490
16491 IdentifierInfo *II = D.getIdentifier();
16492 SourceLocation Loc = DeclStart;
16493 if (II
14.1
'II' is null
14.1
'II' is null
14.1
'II' is null
) Loc = D.getIdentifierLoc();
15
Taking false branch
16494
16495 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16496 QualType T = TInfo->getType();
16497 if (getLangOpts().CPlusPlus) {
16
Assuming field 'CPlusPlus' is 0
17
Taking false branch
16498 CheckExtraCXXDefaultArguments(D);
16499
16500 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16501 UPPC_DataMemberType)) {
16502 D.setInvalidType();
16503 T = Context.IntTy;
16504 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16505 }
16506 }
16507
16508 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16509
16510 if (D.getDeclSpec().isInlineSpecified())
18
Assuming the condition is false
19
Taking false branch
16511 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16512 << getLangOpts().CPlusPlus17;
16513 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
20
Assuming 'TSCS' is 0
21
Taking false branch
16514 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16515 diag::err_invalid_thread)
16516 << DeclSpec::getSpecifierName(TSCS);
16517
16518 // Check to see if this name was declared as a member previously
16519 NamedDecl *PrevDecl = nullptr;
16520 LookupResult Previous(*this, II, Loc, LookupMemberName,
16521 ForVisibleRedeclaration);
16522 LookupName(Previous, S);
16523 switch (Previous.getResultKind()) {
22
Control jumps to 'case Ambiguous:' at line 16535
16524 case LookupResult::Found:
16525 case LookupResult::FoundUnresolvedValue:
16526 PrevDecl = Previous.getAsSingle<NamedDecl>();
16527 break;
16528
16529 case LookupResult::FoundOverloaded:
16530 PrevDecl = Previous.getRepresentativeDecl();
16531 break;
16532
16533 case LookupResult::NotFound:
16534 case LookupResult::NotFoundInCurrentInstantiation:
16535 case LookupResult::Ambiguous:
16536 break;
23
Execution continues on line 16538
16537 }
16538 Previous.suppressDiagnostics();
16539
16540 if (PrevDecl
23.1
'PrevDecl' is null
23.1
'PrevDecl' is null
23.1
'PrevDecl' is null
&& PrevDecl->isTemplateParameter()) {
16541 // Maybe we will complain about the shadowed template parameter.
16542 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16543 // Just pretend that we didn't see the previous declaration.
16544 PrevDecl = nullptr;
16545 }
16546
16547 if (PrevDecl
23.2
'PrevDecl' is null
23.2
'PrevDecl' is null
23.2
'PrevDecl' is null
&& !isDeclInScope(PrevDecl, Record, S))
16548 PrevDecl = nullptr;
16549
16550 bool Mutable
16551 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
24
Assuming the condition is false
16552 SourceLocation TSSL = D.getBeginLoc();
16553 FieldDecl *NewFD
16554 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
25
Passing null pointer value via 4th parameter 'Record'
26
Calling 'Sema::CheckFieldDecl'
16555 TSSL, AS, PrevDecl, &D);
16556
16557 if (NewFD->isInvalidDecl())
16558 Record->setInvalidDecl();
16559
16560 if (D.getDeclSpec().isModulePrivateSpecified())
16561 NewFD->setModulePrivate();
16562
16563 if (NewFD->isInvalidDecl() && PrevDecl) {
16564 // Don't introduce NewFD into scope; there's already something
16565 // with the same name in the same scope.
16566 } else if (II) {
16567 PushOnScopeChains(NewFD, S);
16568 } else
16569 Record->addDecl(NewFD);
16570
16571 return NewFD;
16572}
16573
16574/// Build a new FieldDecl and check its well-formedness.
16575///
16576/// This routine builds a new FieldDecl given the fields name, type,
16577/// record, etc. \p PrevDecl should refer to any previous declaration
16578/// with the same name and in the same scope as the field to be
16579/// created.
16580///
16581/// \returns a new FieldDecl.
16582///
16583/// \todo The Declarator argument is a hack. It will be removed once
16584FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16585 TypeSourceInfo *TInfo,
16586 RecordDecl *Record, SourceLocation Loc,
16587 bool Mutable, Expr *BitWidth,
16588 InClassInitStyle InitStyle,
16589 SourceLocation TSSL,
16590 AccessSpecifier AS, NamedDecl *PrevDecl,
16591 Declarator *D) {
16592 IdentifierInfo *II = Name.getAsIdentifierInfo();
16593 bool InvalidDecl = false;
16594 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
16595
16596 // If we receive a broken type, recover by assuming 'int' and
16597 // marking this declaration as invalid.
16598 if (T.isNull() || T->containsErrors()) {
28
Assuming the condition is false
29
Taking false branch
16599 InvalidDecl = true;
16600 T = Context.IntTy;
16601 }
16602
16603 QualType EltTy = Context.getBaseElementType(T);
16604 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
30
Assuming the condition is false
16605 if (RequireCompleteSizedType(Loc, EltTy,
16606 diag::err_field_incomplete_or_sizeless)) {
16607 // Fields of incomplete type force their record to be invalid.
16608 Record->setInvalidDecl();
16609 InvalidDecl = true;
16610 } else {
16611 NamedDecl *Def;
16612 EltTy->isIncompleteType(&Def);
16613 if (Def && Def->isInvalidDecl()) {
16614 Record->setInvalidDecl();
16615 InvalidDecl = true;
16616 }
16617 }
16618 }
16619
16620 // TR 18037 does not allow fields to be declared with address space
16621 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
31
Assuming the condition is false
32
Taking false branch
16622 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16623 Diag(Loc, diag::err_field_with_address_space);
16624 Record->setInvalidDecl();
16625 InvalidDecl = true;
16626 }
16627
16628 if (LangOpts.OpenCL) {
33
Assuming field 'OpenCL' is 0
34
Taking false branch
16629 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16630 // used as structure or union field: image, sampler, event or block types.
16631 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16632 T->isBlockPointerType()) {
16633 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16634 Record->setInvalidDecl();
16635 InvalidDecl = true;
16636 }
16637 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16638 if (BitWidth) {
16639 Diag(Loc, diag::err_opencl_bitfields);
16640 InvalidDecl = true;
16641 }
16642 }
16643
16644 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16645 if (!InvalidDecl
34.1
'InvalidDecl' is false
34.1
'InvalidDecl' is false
34.1
'InvalidDecl' is false
&& getLangOpts().CPlusPlus && !II && BitWidth &&
35
Assuming field 'CPlusPlus' is 0
16646 T.hasQualifiers()) {
16647 InvalidDecl = true;
16648 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16649 }
16650
16651 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16652 // than a variably modified type.
16653 if (!InvalidDecl
35.1
'InvalidDecl' is false
35.1
'InvalidDecl' is false
35.1
'InvalidDecl' is false
&& T->isVariablyModifiedType()) {
36
Assuming the condition is false
37
Taking false branch
16654 bool SizeIsNegative;
16655 llvm::APSInt Oversized;
16656
16657 TypeSourceInfo *FixedTInfo =
16658 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16659 SizeIsNegative,
16660 Oversized);
16661 if (FixedTInfo) {
16662 Diag(Loc, diag::ext_vla_folded_to_constant);
16663 TInfo = FixedTInfo;
16664 T = FixedTInfo->getType();
16665 } else {
16666 if (SizeIsNegative)
16667 Diag(Loc, diag::err_typecheck_negative_array_size);
16668 else if (Oversized.getBoolValue())
16669 Diag(Loc, diag::err_array_too_large)
16670 << Oversized.toString(10);
16671 else
16672 Diag(Loc, diag::err_typecheck_field_variable_size);
16673 InvalidDecl = true;
16674 }
16675 }
16676
16677 // Fields can not have abstract class types
16678 if (!InvalidDecl
37.1
'InvalidDecl' is false
37.1
'InvalidDecl' is false
37.1
'InvalidDecl' is false
&& RequireNonAbstractType(Loc, T,
38
Assuming the condition is false
39
Taking false branch
16679 diag::err_abstract_type_in_decl,
16680 AbstractFieldType))
16681 InvalidDecl = true;
16682
16683 bool ZeroWidth = false;
16684 if (InvalidDecl
39.1
'InvalidDecl' is false
39.1
'InvalidDecl' is false
39.1
'InvalidDecl' is false
)
40
Taking false branch
16685 BitWidth = nullptr;
16686 // If this is declared as a bit-field, check the bit-field.
16687 if (BitWidth) {
41
Assuming 'BitWidth' is non-null
42
Taking true branch
16688 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
43
Called C++ object pointer is null
16689 &ZeroWidth).get();
16690 if (!BitWidth) {
16691 InvalidDecl = true;
16692 BitWidth = nullptr;
16693 ZeroWidth = false;
16694 }
16695 }
16696
16697 // Check that 'mutable' is consistent with the type of the declaration.
16698 if (!InvalidDecl && Mutable) {
16699 unsigned DiagID = 0;
16700 if (T->isReferenceType())
16701 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16702 : diag::err_mutable_reference;
16703 else if (T.isConstQualified())
16704 DiagID = diag::err_mutable_const;
16705
16706 if (DiagID) {
16707 SourceLocation ErrLoc = Loc;
16708 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16709 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16710 Diag(ErrLoc, DiagID);
16711 if (DiagID != diag::ext_mutable_reference) {
16712 Mutable = false;
16713 InvalidDecl = true;
16714 }
16715 }
16716 }
16717
16718 // C++11 [class.union]p8 (DR1460):
16719 // At most one variant member of a union may have a
16720 // brace-or-equal-initializer.
16721 if (InitStyle != ICIS_NoInit)
16722 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16723
16724 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16725 BitWidth, Mutable, InitStyle);
16726 if (InvalidDecl)
16727 NewFD->setInvalidDecl();
16728
16729 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16730 Diag(Loc, diag::err_duplicate_member) << II;
16731 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16732 NewFD->setInvalidDecl();
16733 }
16734
16735 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16736 if (Record->isUnion()) {
16737 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16738 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16739 if (RDecl->getDefinition()) {
16740 // C++ [class.union]p1: An object of a class with a non-trivial
16741 // constructor, a non-trivial copy constructor, a non-trivial
16742 // destructor, or a non-trivial copy assignment operator
16743 // cannot be a member of a union, nor can an array of such
16744 // objects.
16745 if (CheckNontrivialField(NewFD))
16746 NewFD->setInvalidDecl();
16747 }
16748 }
16749
16750 // C++ [class.union]p1: If a union contains a member of reference type,
16751 // the program is ill-formed, except when compiling with MSVC extensions
16752 // enabled.
16753 if (EltTy->isReferenceType()) {
16754 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16755 diag::ext_union_member_of_reference_type :
16756 diag::err_union_member_of_reference_type)
16757 << NewFD->getDeclName() << EltTy;
16758 if (!getLangOpts().MicrosoftExt)
16759 NewFD->setInvalidDecl();
16760 }
16761 }
16762 }
16763
16764 // FIXME: We need to pass in the attributes given an AST
16765 // representation, not a parser representation.
16766 if (D) {
16767 // FIXME: The current scope is almost... but not entirely... correct here.
16768 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16769
16770 if (NewFD->hasAttrs())
16771 CheckAlignasUnderalignment(NewFD);
16772 }
16773
16774 // In auto-retain/release, infer strong retension for fields of
16775 // retainable type.
16776 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16777 NewFD->setInvalidDecl();
16778
16779 if (T.isObjCGCWeak())
16780 Diag(Loc, diag::warn_attribute_weak_on_field);
16781
16782 NewFD->setAccess(AS);
16783 return NewFD;
16784}
16785
16786bool Sema::CheckNontrivialField(FieldDecl *FD) {
16787 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16787, __PRETTY_FUNCTION__))
;
16788 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16788, __PRETTY_FUNCTION__))
;
16789
16790 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16791 return false;
16792
16793 QualType EltTy = Context.getBaseElementType(FD->getType());
16794 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16795 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16796 if (RDecl->getDefinition()) {
16797 // We check for copy constructors before constructors
16798 // because otherwise we'll never get complaints about
16799 // copy constructors.
16800
16801 CXXSpecialMember member = CXXInvalid;
16802 // We're required to check for any non-trivial constructors. Since the
16803 // implicit default constructor is suppressed if there are any
16804 // user-declared constructors, we just need to check that there is a
16805 // trivial default constructor and a trivial copy constructor. (We don't
16806 // worry about move constructors here, since this is a C++98 check.)
16807 if (RDecl->hasNonTrivialCopyConstructor())
16808 member = CXXCopyConstructor;
16809 else if (!RDecl->hasTrivialDefaultConstructor())
16810 member = CXXDefaultConstructor;
16811 else if (RDecl->hasNonTrivialCopyAssignment())
16812 member = CXXCopyAssignment;
16813 else if (RDecl->hasNonTrivialDestructor())
16814 member = CXXDestructor;
16815
16816 if (member != CXXInvalid) {
16817 if (!getLangOpts().CPlusPlus11 &&
16818 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16819 // Objective-C++ ARC: it is an error to have a non-trivial field of
16820 // a union. However, system headers in Objective-C programs
16821 // occasionally have Objective-C lifetime objects within unions,
16822 // and rather than cause the program to fail, we make those
16823 // members unavailable.
16824 SourceLocation Loc = FD->getLocation();
16825 if (getSourceManager().isInSystemHeader(Loc)) {
16826 if (!FD->hasAttr<UnavailableAttr>())
16827 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16828 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16829 return false;
16830 }
16831 }
16832
16833 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16834 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16835 diag::err_illegal_union_or_anon_struct_member)
16836 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16837 DiagnoseNontrivial(RDecl, member);
16838 return !getLangOpts().CPlusPlus11;
16839 }
16840 }
16841 }
16842
16843 return false;
16844}
16845
16846/// TranslateIvarVisibility - Translate visibility from a token ID to an
16847/// AST enum value.
16848static ObjCIvarDecl::AccessControl
16849TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16850 switch (ivarVisibility) {
16851 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16851)
;
16852 case tok::objc_private: return ObjCIvarDecl::Private;
16853 case tok::objc_public: return ObjCIvarDecl::Public;
16854 case tok::objc_protected: return ObjCIvarDecl::Protected;
16855 case tok::objc_package: return ObjCIvarDecl::Package;
16856 }
16857}
16858
16859/// ActOnIvar - Each ivar field of an objective-c class is passed into this
16860/// in order to create an IvarDecl object for it.
16861Decl *Sema::ActOnIvar(Scope *S,
16862 SourceLocation DeclStart,
16863 Declarator &D, Expr *BitfieldWidth,
16864 tok::ObjCKeywordKind Visibility) {
16865
16866 IdentifierInfo *II = D.getIdentifier();
16867 Expr *BitWidth = (Expr*)BitfieldWidth;
16868 SourceLocation Loc = DeclStart;
16869 if (II) Loc = D.getIdentifierLoc();
16870
16871 // FIXME: Unnamed fields can be handled in various different ways, for
16872 // example, unnamed unions inject all members into the struct namespace!
16873
16874 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16875 QualType T = TInfo->getType();
16876
16877 if (BitWidth) {
16878 // 6.7.2.1p3, 6.7.2.1p4
16879 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16880 if (!BitWidth)
16881 D.setInvalidType();
16882 } else {
16883 // Not a bitfield.
16884
16885 // validate II.
16886
16887 }
16888 if (T->isReferenceType()) {
16889 Diag(Loc, diag::err_ivar_reference_type);
16890 D.setInvalidType();
16891 }
16892 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16893 // than a variably modified type.
16894 else if (T->isVariablyModifiedType()) {
16895 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16896 D.setInvalidType();
16897 }
16898
16899 // Get the visibility (access control) for this ivar.
16900 ObjCIvarDecl::AccessControl ac =
16901 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16902 : ObjCIvarDecl::None;
16903 // Must set ivar's DeclContext to its enclosing interface.
16904 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16905 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16906 return nullptr;
16907 ObjCContainerDecl *EnclosingContext;
16908 if (ObjCImplementationDecl *IMPDecl =
16909 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16910 if (LangOpts.ObjCRuntime.isFragile()) {
16911 // Case of ivar declared in an implementation. Context is that of its class.
16912 EnclosingContext = IMPDecl->getClassInterface();
16913 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 16913, __PRETTY_FUNCTION__))
;
16914 }
16915 else
16916 EnclosingContext = EnclosingDecl;
16917 } else {
16918 if (ObjCCategoryDecl *CDecl =
16919 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16920 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16921 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16922 return nullptr;
16923 }
16924 }
16925 EnclosingContext = EnclosingDecl;
16926 }
16927
16928 // Construct the decl.
16929 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16930 DeclStart, Loc, II, T,
16931 TInfo, ac, (Expr *)BitfieldWidth);
16932
16933 if (II) {
16934 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16935 ForVisibleRedeclaration);
16936 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16937 && !isa<TagDecl>(PrevDecl)) {
16938 Diag(Loc, diag::err_duplicate_member) << II;
16939 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16940 NewID->setInvalidDecl();
16941 }
16942 }
16943
16944 // Process attributes attached to the ivar.
16945 ProcessDeclAttributes(S, NewID, D);
16946
16947 if (D.isInvalidType())
16948 NewID->setInvalidDecl();
16949
16950 // In ARC, infer 'retaining' for ivars of retainable type.
16951 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16952 NewID->setInvalidDecl();
16953
16954 if (D.getDeclSpec().isModulePrivateSpecified())
16955 NewID->setModulePrivate();
16956
16957 if (II) {
16958 // FIXME: When interfaces are DeclContexts, we'll need to add
16959 // these to the interface.
16960 S->AddDecl(NewID);
16961 IdResolver.AddDecl(NewID);
16962 }
16963
16964 if (LangOpts.ObjCRuntime.isNonFragile() &&
16965 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16966 Diag(Loc, diag::warn_ivars_in_interface);
16967
16968 return NewID;
16969}
16970
16971/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16972/// class and class extensions. For every class \@interface and class
16973/// extension \@interface, if the last ivar is a bitfield of any type,
16974/// then add an implicit `char :0` ivar to the end of that interface.
16975void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16976 SmallVectorImpl<Decl *> &AllIvarDecls) {
16977 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
16978 return;
16979
16980 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
16981 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
16982
16983 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
16984 return;
16985 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
16986 if (!ID) {
16987 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
16988 if (!CD->IsClassExtension())
16989 return;
16990 }
16991 // No need to add this to end of @implementation.
16992 else
16993 return;
16994 }
16995 // All conditions are met. Add a new bitfield to the tail end of ivars.
16996 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
16997 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
16998
16999 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17000 DeclLoc, DeclLoc, nullptr,
17001 Context.CharTy,
17002 Context.getTrivialTypeSourceInfo(Context.CharTy,
17003 DeclLoc),
17004 ObjCIvarDecl::Private, BW,
17005 true);
17006 AllIvarDecls.push_back(Ivar);
17007}
17008
17009void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17010 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17011 SourceLocation RBrac,
17012 const ParsedAttributesView &Attrs) {
17013 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17013, __PRETTY_FUNCTION__))
;
17014
17015 // If this is an Objective-C @implementation or category and we have
17016 // new fields here we should reset the layout of the interface since
17017 // it will now change.
17018 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17019 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17020 switch (DC->getKind()) {
17021 default: break;
17022 case Decl::ObjCCategory:
17023 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17024 break;
17025 case Decl::ObjCImplementation:
17026 Context.
17027 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17028 break;
17029 }
17030 }
17031
17032 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17033 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17034
17035 // Start counting up the number of named members; make sure to include
17036 // members of anonymous structs and unions in the total.
17037 unsigned NumNamedMembers = 0;
17038 if (Record) {
17039 for (const auto *I : Record->decls()) {
17040 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17041 if (IFD->getDeclName())
17042 ++NumNamedMembers;
17043 }
17044 }
17045
17046 // Verify that all the fields are okay.
17047 SmallVector<FieldDecl*, 32> RecFields;
17048
17049 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17050 i != end; ++i) {
17051 FieldDecl *FD = cast<FieldDecl>(*i);
17052
17053 // Get the type for the field.
17054 const Type *FDTy = FD->getType().getTypePtr();
17055
17056 if (!FD->isAnonymousStructOrUnion()) {
17057 // Remember all fields written by the user.
17058 RecFields.push_back(FD);
17059 }
17060
17061 // If the field is already invalid for some reason, don't emit more
17062 // diagnostics about it.
17063 if (FD->isInvalidDecl()) {
17064 EnclosingDecl->setInvalidDecl();
17065 continue;
17066 }
17067
17068 // C99 6.7.2.1p2:
17069 // A structure or union shall not contain a member with
17070 // incomplete or function type (hence, a structure shall not
17071 // contain an instance of itself, but may contain a pointer to
17072 // an instance of itself), except that the last member of a
17073 // structure with more than one named member may have incomplete
17074 // array type; such a structure (and any union containing,
17075 // possibly recursively, a member that is such a structure)
17076 // shall not be a member of a structure or an element of an
17077 // array.
17078 bool IsLastField = (i + 1 == Fields.end());
17079 if (FDTy->isFunctionType()) {
17080 // Field declared as a function.
17081 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17082 << FD->getDeclName();
17083 FD->setInvalidDecl();
17084 EnclosingDecl->setInvalidDecl();
17085 continue;
17086 } else if (FDTy->isIncompleteArrayType() &&
17087 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17088 if (Record) {
17089 // Flexible array member.
17090 // Microsoft and g++ is more permissive regarding flexible array.
17091 // It will accept flexible array in union and also
17092 // as the sole element of a struct/class.
17093 unsigned DiagID = 0;
17094 if (!Record->isUnion() && !IsLastField) {
17095 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17096 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17097 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17098 FD->setInvalidDecl();
17099 EnclosingDecl->setInvalidDecl();
17100 continue;
17101 } else if (Record->isUnion())
17102 DiagID = getLangOpts().MicrosoftExt
17103 ? diag::ext_flexible_array_union_ms
17104 : getLangOpts().CPlusPlus
17105 ? diag::ext_flexible_array_union_gnu
17106 : diag::err_flexible_array_union;
17107 else if (NumNamedMembers < 1)
17108 DiagID = getLangOpts().MicrosoftExt
17109 ? diag::ext_flexible_array_empty_aggregate_ms
17110 : getLangOpts().CPlusPlus
17111 ? diag::ext_flexible_array_empty_aggregate_gnu
17112 : diag::err_flexible_array_empty_aggregate;
17113
17114 if (DiagID)
17115 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17116 << Record->getTagKind();
17117 // While the layout of types that contain virtual bases is not specified
17118 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17119 // virtual bases after the derived members. This would make a flexible
17120 // array member declared at the end of an object not adjacent to the end
17121 // of the type.
17122 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17123 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17124 << FD->getDeclName() << Record->getTagKind();
17125 if (!getLangOpts().C99)
17126 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17127 << FD->getDeclName() << Record->getTagKind();
17128
17129 // If the element type has a non-trivial destructor, we would not
17130 // implicitly destroy the elements, so disallow it for now.
17131 //
17132 // FIXME: GCC allows this. We should probably either implicitly delete
17133 // the destructor of the containing class, or just allow this.
17134 QualType BaseElem = Context.getBaseElementType(FD->getType());
17135 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17136 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17137 << FD->getDeclName() << FD->getType();
17138 FD->setInvalidDecl();
17139 EnclosingDecl->setInvalidDecl();
17140 continue;
17141 }
17142 // Okay, we have a legal flexible array member at the end of the struct.
17143 Record->setHasFlexibleArrayMember(true);
17144 } else {
17145 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17146 // unless they are followed by another ivar. That check is done
17147 // elsewhere, after synthesized ivars are known.
17148 }
17149 } else if (!FDTy->isDependentType() &&
17150 RequireCompleteSizedType(
17151 FD->getLocation(), FD->getType(),
17152 diag::err_field_incomplete_or_sizeless)) {
17153 // Incomplete type
17154 FD->setInvalidDecl();
17155 EnclosingDecl->setInvalidDecl();
17156 continue;
17157 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17158 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17159 // A type which contains a flexible array member is considered to be a
17160 // flexible array member.
17161 Record->setHasFlexibleArrayMember(true);
17162 if (!Record->isUnion()) {
17163 // If this is a struct/class and this is not the last element, reject
17164 // it. Note that GCC supports variable sized arrays in the middle of
17165 // structures.
17166 if (!IsLastField)
17167 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17168 << FD->getDeclName() << FD->getType();
17169 else {
17170 // We support flexible arrays at the end of structs in
17171 // other structs as an extension.
17172 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17173 << FD->getDeclName();
17174 }
17175 }
17176 }
17177 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17178 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17179 diag::err_abstract_type_in_decl,
17180 AbstractIvarType)) {
17181 // Ivars can not have abstract class types
17182 FD->setInvalidDecl();
17183 }
17184 if (Record && FDTTy->getDecl()->hasObjectMember())
17185 Record->setHasObjectMember(true);
17186 if (Record && FDTTy->getDecl()->hasVolatileMember())
17187 Record->setHasVolatileMember(true);
17188 } else if (FDTy->isObjCObjectType()) {
17189 /// A field cannot be an Objective-c object
17190 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17191 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17192 QualType T = Context.getObjCObjectPointerType(FD->getType());
17193 FD->setType(T);
17194 } else if (Record && Record->isUnion() &&
17195 FD->getType().hasNonTrivialObjCLifetime() &&
17196 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17197 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17198 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17199 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17200 // For backward compatibility, fields of C unions declared in system
17201 // headers that have non-trivial ObjC ownership qualifications are marked
17202 // as unavailable unless the qualifier is explicit and __strong. This can
17203 // break ABI compatibility between programs compiled with ARC and MRR, but
17204 // is a better option than rejecting programs using those unions under
17205 // ARC.
17206 FD->addAttr(UnavailableAttr::CreateImplicit(
17207 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17208 FD->getLocation()));
17209 } else if (getLangOpts().ObjC &&
17210 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17211 !Record->hasObjectMember()) {
17212 if (FD->getType()->isObjCObjectPointerType() ||
17213 FD->getType().isObjCGCStrong())
17214 Record->setHasObjectMember(true);
17215 else if (Context.getAsArrayType(FD->getType())) {
17216 QualType BaseType = Context.getBaseElementType(FD->getType());
17217 if (BaseType->isRecordType() &&
17218 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17219 Record->setHasObjectMember(true);
17220 else if (BaseType->isObjCObjectPointerType() ||
17221 BaseType.isObjCGCStrong())
17222 Record->setHasObjectMember(true);
17223 }
17224 }
17225
17226 if (Record && !getLangOpts().CPlusPlus &&
17227 !shouldIgnoreForRecordTriviality(FD)) {
17228 QualType FT = FD->getType();
17229 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17230 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17231 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17232 Record->isUnion())
17233 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17234 }
17235 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17236 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17237 Record->setNonTrivialToPrimitiveCopy(true);
17238 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17239 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17240 }
17241 if (FT.isDestructedType()) {
17242 Record->setNonTrivialToPrimitiveDestroy(true);
17243 Record->setParamDestroyedInCallee(true);
17244 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17245 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17246 }
17247
17248 if (const auto *RT = FT->getAs<RecordType>()) {
17249 if (RT->getDecl()->getArgPassingRestrictions() ==
17250 RecordDecl::APK_CanNeverPassInRegs)
17251 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17252 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17253 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17254 }
17255
17256 if (Record && FD->getType().isVolatileQualified())
17257 Record->setHasVolatileMember(true);
17258 // Keep track of the number of named members.
17259 if (FD->getIdentifier())
17260 ++NumNamedMembers;
17261 }
17262
17263 // Okay, we successfully defined 'Record'.
17264 if (Record) {
17265 bool Completed = false;
17266 if (CXXRecord) {
17267 if (!CXXRecord->isInvalidDecl()) {
17268 // Set access bits correctly on the directly-declared conversions.
17269 for (CXXRecordDecl::conversion_iterator
17270 I = CXXRecord->conversion_begin(),
17271 E = CXXRecord->conversion_end(); I != E; ++I)
17272 I.setAccess((*I)->getAccess());
17273 }
17274
17275 // Add any implicitly-declared members to this class.
17276 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17277
17278 if (!CXXRecord->isDependentType()) {
17279 if (!CXXRecord->isInvalidDecl()) {
17280 // If we have virtual base classes, we may end up finding multiple
17281 // final overriders for a given virtual function. Check for this
17282 // problem now.
17283 if (CXXRecord->getNumVBases()) {
17284 CXXFinalOverriderMap FinalOverriders;
17285 CXXRecord->getFinalOverriders(FinalOverriders);
17286
17287 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17288 MEnd = FinalOverriders.end();
17289 M != MEnd; ++M) {
17290 for (OverridingMethods::iterator SO = M->second.begin(),
17291 SOEnd = M->second.end();
17292 SO != SOEnd; ++SO) {
17293 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17294, __PRETTY_FUNCTION__))
17294 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17294, __PRETTY_FUNCTION__))
;
17295 if (SO->second.size() == 1)
17296 continue;
17297
17298 // C++ [class.virtual]p2:
17299 // In a derived class, if a virtual member function of a base
17300 // class subobject has more than one final overrider the
17301 // program is ill-formed.
17302 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17303 << (const NamedDecl *)M->first << Record;
17304 Diag(M->first->getLocation(),
17305 diag::note_overridden_virtual_function);
17306 for (OverridingMethods::overriding_iterator
17307 OM = SO->second.begin(),
17308 OMEnd = SO->second.end();
17309 OM != OMEnd; ++OM)
17310 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17311 << (const NamedDecl *)M->first << OM->Method->getParent();
17312
17313 Record->setInvalidDecl();
17314 }
17315 }
17316 CXXRecord->completeDefinition(&FinalOverriders);
17317 Completed = true;
17318 }
17319 }
17320 }
17321 }
17322
17323 if (!Completed)
17324 Record->completeDefinition();
17325
17326 // Handle attributes before checking the layout.
17327 ProcessDeclAttributeList(S, Record, Attrs);
17328
17329 // We may have deferred checking for a deleted destructor. Check now.
17330 if (CXXRecord) {
17331 auto *Dtor = CXXRecord->getDestructor();
17332 if (Dtor && Dtor->isImplicit() &&
17333 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17334 CXXRecord->setImplicitDestructorIsDeleted();
17335 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17336 }
17337 }
17338
17339 if (Record->hasAttrs()) {
17340 CheckAlignasUnderalignment(Record);
17341
17342 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17343 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17344 IA->getRange(), IA->getBestCase(),
17345 IA->getInheritanceModel());
17346 }
17347
17348 // Check if the structure/union declaration is a type that can have zero
17349 // size in C. For C this is a language extension, for C++ it may cause
17350 // compatibility problems.
17351 bool CheckForZeroSize;
17352 if (!getLangOpts().CPlusPlus) {
17353 CheckForZeroSize = true;
17354 } else {
17355 // For C++ filter out types that cannot be referenced in C code.
17356 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17357 CheckForZeroSize =
17358 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17359 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17360 CXXRecord->isCLike();
17361 }
17362 if (CheckForZeroSize) {
17363 bool ZeroSize = true;
17364 bool IsEmpty = true;
17365 unsigned NonBitFields = 0;
17366 for (RecordDecl::field_iterator I = Record->field_begin(),
17367 E = Record->field_end();
17368 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17369 IsEmpty = false;
17370 if (I->isUnnamedBitfield()) {
17371 if (!I->isZeroLengthBitField(Context))
17372 ZeroSize = false;
17373 } else {
17374 ++NonBitFields;
17375 QualType FieldType = I->getType();
17376 if (FieldType->isIncompleteType() ||
17377 !Context.getTypeSizeInChars(FieldType).isZero())
17378 ZeroSize = false;
17379 }
17380 }
17381
17382 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17383 // allowed in C++, but warn if its declaration is inside
17384 // extern "C" block.
17385 if (ZeroSize) {
17386 Diag(RecLoc, getLangOpts().CPlusPlus ?
17387 diag::warn_zero_size_struct_union_in_extern_c :
17388 diag::warn_zero_size_struct_union_compat)
17389 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17390 }
17391
17392 // Structs without named members are extension in C (C99 6.7.2.1p7),
17393 // but are accepted by GCC.
17394 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17395 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17396 diag::ext_no_named_members_in_struct_union)
17397 << Record->isUnion();
17398 }
17399 }
17400 } else {
17401 ObjCIvarDecl **ClsFields =
17402 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17403 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17404 ID->setEndOfDefinitionLoc(RBrac);
17405 // Add ivar's to class's DeclContext.
17406 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17407 ClsFields[i]->setLexicalDeclContext(ID);
17408 ID->addDecl(ClsFields[i]);
17409 }
17410 // Must enforce the rule that ivars in the base classes may not be
17411 // duplicates.
17412 if (ID->getSuperClass())
17413 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17414 } else if (ObjCImplementationDecl *IMPDecl =
17415 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17416 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17416, __PRETTY_FUNCTION__))
;
17417 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17418 // Ivar declared in @implementation never belongs to the implementation.
17419 // Only it is in implementation's lexical context.
17420 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17421 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17422 IMPDecl->setIvarLBraceLoc(LBrac);
17423 IMPDecl->setIvarRBraceLoc(RBrac);
17424 } else if (ObjCCategoryDecl *CDecl =
17425 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17426 // case of ivars in class extension; all other cases have been
17427 // reported as errors elsewhere.
17428 // FIXME. Class extension does not have a LocEnd field.
17429 // CDecl->setLocEnd(RBrac);
17430 // Add ivar's to class extension's DeclContext.
17431 // Diagnose redeclaration of private ivars.
17432 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17433 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17434 if (IDecl) {
17435 if (const ObjCIvarDecl *ClsIvar =
17436 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17437 Diag(ClsFields[i]->getLocation(),
17438 diag::err_duplicate_ivar_declaration);
17439 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17440 continue;
17441 }
17442 for (const auto *Ext : IDecl->known_extensions()) {
17443 if (const ObjCIvarDecl *ClsExtIvar
17444 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17445 Diag(ClsFields[i]->getLocation(),
17446 diag::err_duplicate_ivar_declaration);
17447 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17448 continue;
17449 }
17450 }
17451 }
17452 ClsFields[i]->setLexicalDeclContext(CDecl);
17453 CDecl->addDecl(ClsFields[i]);
17454 }
17455 CDecl->setIvarLBraceLoc(LBrac);
17456 CDecl->setIvarRBraceLoc(RBrac);
17457 }
17458 }
17459}
17460
17461/// Determine whether the given integral value is representable within
17462/// the given type T.
17463static bool isRepresentableIntegerValue(ASTContext &Context,
17464 llvm::APSInt &Value,
17465 QualType T) {
17466 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17467, __PRETTY_FUNCTION__))
17467 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17467, __PRETTY_FUNCTION__))
;
17468 unsigned BitWidth = Context.getIntWidth(T);
17469
17470 if (Value.isUnsigned() || Value.isNonNegative()) {
17471 if (T->isSignedIntegerOrEnumerationType())
17472 --BitWidth;
17473 return Value.getActiveBits() <= BitWidth;
17474 }
17475 return Value.getMinSignedBits() <= BitWidth;
17476}
17477
17478// Given an integral type, return the next larger integral type
17479// (or a NULL type of no such type exists).
17480static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17481 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17482 // enum checking below.
17483 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17484, __PRETTY_FUNCTION__))
17484 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17484, __PRETTY_FUNCTION__))
;
17485 const unsigned NumTypes = 4;
17486 QualType SignedIntegralTypes[NumTypes] = {
17487 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17488 };
17489 QualType UnsignedIntegralTypes[NumTypes] = {
17490 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17491 Context.UnsignedLongLongTy
17492 };
17493
17494 unsigned BitWidth = Context.getTypeSize(T);
17495 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17496 : UnsignedIntegralTypes;
17497 for (unsigned I = 0; I != NumTypes; ++I)
17498 if (Context.getTypeSize(Types[I]) > BitWidth)
17499 return Types[I];
17500
17501 return QualType();
17502}
17503
17504EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17505 EnumConstantDecl *LastEnumConst,
17506 SourceLocation IdLoc,
17507 IdentifierInfo *Id,
17508 Expr *Val) {
17509 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17510 llvm::APSInt EnumVal(IntWidth);
17511 QualType EltTy;
17512
17513 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17514 Val = nullptr;
17515
17516 if (Val)
17517 Val = DefaultLvalueConversion(Val).get();
17518
17519 if (Val) {
17520 if (Enum->isDependentType() || Val->isTypeDependent())
17521 EltTy = Context.DependentTy;
17522 else {
17523 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17524 // underlying type, but do allow it in all other contexts.
17525 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17526 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17527 // constant-expression in the enumerator-definition shall be a converted
17528 // constant expression of the underlying type.
17529 EltTy = Enum->getIntegerType();
17530 ExprResult Converted =
17531 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17532 CCEK_Enumerator);
17533 if (Converted.isInvalid())
17534 Val = nullptr;
17535 else
17536 Val = Converted.get();
17537 } else if (!Val->isValueDependent() &&
17538 !(Val =
17539 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17540 .get())) {
17541 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17542 } else {
17543 if (Enum->isComplete()) {
17544 EltTy = Enum->getIntegerType();
17545
17546 // In Obj-C and Microsoft mode, require the enumeration value to be
17547 // representable in the underlying type of the enumeration. In C++11,
17548 // we perform a non-narrowing conversion as part of converted constant
17549 // expression checking.
17550 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17551 if (Context.getTargetInfo()
17552 .getTriple()
17553 .isWindowsMSVCEnvironment()) {
17554 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17555 } else {
17556 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17557 }
17558 }
17559
17560 // Cast to the underlying type.
17561 Val = ImpCastExprToType(Val, EltTy,
17562 EltTy->isBooleanType() ? CK_IntegralToBoolean
17563 : CK_IntegralCast)
17564 .get();
17565 } else if (getLangOpts().CPlusPlus) {
17566 // C++11 [dcl.enum]p5:
17567 // If the underlying type is not fixed, the type of each enumerator
17568 // is the type of its initializing value:
17569 // - If an initializer is specified for an enumerator, the
17570 // initializing value has the same type as the expression.
17571 EltTy = Val->getType();
17572 } else {
17573 // C99 6.7.2.2p2:
17574 // The expression that defines the value of an enumeration constant
17575 // shall be an integer constant expression that has a value
17576 // representable as an int.
17577
17578 // Complain if the value is not representable in an int.
17579 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17580 Diag(IdLoc, diag::ext_enum_value_not_int)
17581 << EnumVal.toString(10) << Val->getSourceRange()
17582 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17583 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17584 // Force the type of the expression to 'int'.
17585 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17586 }
17587 EltTy = Val->getType();
17588 }
17589 }
17590 }
17591 }
17592
17593 if (!Val) {
17594 if (Enum->isDependentType())
17595 EltTy = Context.DependentTy;
17596 else if (!LastEnumConst) {
17597 // C++0x [dcl.enum]p5:
17598 // If the underlying type is not fixed, the type of each enumerator
17599 // is the type of its initializing value:
17600 // - If no initializer is specified for the first enumerator, the
17601 // initializing value has an unspecified integral type.
17602 //
17603 // GCC uses 'int' for its unspecified integral type, as does
17604 // C99 6.7.2.2p3.
17605 if (Enum->isFixed()) {
17606 EltTy = Enum->getIntegerType();
17607 }
17608 else {
17609 EltTy = Context.IntTy;
17610 }
17611 } else {
17612 // Assign the last value + 1.
17613 EnumVal = LastEnumConst->getInitVal();
17614 ++EnumVal;
17615 EltTy = LastEnumConst->getType();
17616
17617 // Check for overflow on increment.
17618 if (EnumVal < LastEnumConst->getInitVal()) {
17619 // C++0x [dcl.enum]p5:
17620 // If the underlying type is not fixed, the type of each enumerator
17621 // is the type of its initializing value:
17622 //
17623 // - Otherwise the type of the initializing value is the same as
17624 // the type of the initializing value of the preceding enumerator
17625 // unless the incremented value is not representable in that type,
17626 // in which case the type is an unspecified integral type
17627 // sufficient to contain the incremented value. If no such type
17628 // exists, the program is ill-formed.
17629 QualType T = getNextLargerIntegralType(Context, EltTy);
17630 if (T.isNull() || Enum->isFixed()) {
17631 // There is no integral type larger enough to represent this
17632 // value. Complain, then allow the value to wrap around.
17633 EnumVal = LastEnumConst->getInitVal();
17634 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17635 ++EnumVal;
17636 if (Enum->isFixed())
17637 // When the underlying type is fixed, this is ill-formed.
17638 Diag(IdLoc, diag::err_enumerator_wrapped)
17639 << EnumVal.toString(10)
17640 << EltTy;
17641 else
17642 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17643 << EnumVal.toString(10);
17644 } else {
17645 EltTy = T;
17646 }
17647
17648 // Retrieve the last enumerator's value, extent that type to the
17649 // type that is supposed to be large enough to represent the incremented
17650 // value, then increment.
17651 EnumVal = LastEnumConst->getInitVal();
17652 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17653 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17654 ++EnumVal;
17655
17656 // If we're not in C++, diagnose the overflow of enumerator values,
17657 // which in C99 means that the enumerator value is not representable in
17658 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17659 // permits enumerator values that are representable in some larger
17660 // integral type.
17661 if (!getLangOpts().CPlusPlus && !T.isNull())
17662 Diag(IdLoc, diag::warn_enum_value_overflow);
17663 } else if (!getLangOpts().CPlusPlus &&
17664 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17665 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17666 Diag(IdLoc, diag::ext_enum_value_not_int)
17667 << EnumVal.toString(10) << 1;
17668 }
17669 }
17670 }
17671
17672 if (!EltTy->isDependentType()) {
17673 // Make the enumerator value match the signedness and size of the
17674 // enumerator's type.
17675 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17676 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17677 }
17678
17679 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17680 Val, EnumVal);
17681}
17682
17683Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17684 SourceLocation IILoc) {
17685 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17686 !getLangOpts().CPlusPlus)
17687 return SkipBodyInfo();
17688
17689 // We have an anonymous enum definition. Look up the first enumerator to
17690 // determine if we should merge the definition with an existing one and
17691 // skip the body.
17692 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17693 forRedeclarationInCurContext());
17694 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17695 if (!PrevECD)
17696 return SkipBodyInfo();
17697
17698 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17699 NamedDecl *Hidden;
17700 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17701 SkipBodyInfo Skip;
17702 Skip.Previous = Hidden;
17703 return Skip;
17704 }
17705
17706 return SkipBodyInfo();
17707}
17708
17709Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17710 SourceLocation IdLoc, IdentifierInfo *Id,
17711 const ParsedAttributesView &Attrs,
17712 SourceLocation EqualLoc, Expr *Val) {
17713 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17714 EnumConstantDecl *LastEnumConst =
17715 cast_or_null<EnumConstantDecl>(lastEnumConst);
17716
17717 // The scope passed in may not be a decl scope. Zip up the scope tree until
17718 // we find one that is.
17719 S = getNonFieldDeclScope(S);
17720
17721 // Verify that there isn't already something declared with this name in this
17722 // scope.
17723 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17724 LookupName(R, S);
17725 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17726
17727 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17728 // Maybe we will complain about the shadowed template parameter.
17729 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17730 // Just pretend that we didn't see the previous declaration.
17731 PrevDecl = nullptr;
17732 }
17733
17734 // C++ [class.mem]p15:
17735 // If T is the name of a class, then each of the following shall have a name
17736 // different from T:
17737 // - every enumerator of every member of class T that is an unscoped
17738 // enumerated type
17739 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17740 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17741 DeclarationNameInfo(Id, IdLoc));
17742
17743 EnumConstantDecl *New =
17744 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17745 if (!New)
17746 return nullptr;
17747
17748 if (PrevDecl) {
17749 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17750 // Check for other kinds of shadowing not already handled.
17751 CheckShadow(New, PrevDecl, R);
17752 }
17753
17754 // When in C++, we may get a TagDecl with the same name; in this case the
17755 // enum constant will 'hide' the tag.
17756 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17757, __PRETTY_FUNCTION__))
17757 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17757, __PRETTY_FUNCTION__))
;
17758 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17759 if (isa<EnumConstantDecl>(PrevDecl))
17760 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17761 else
17762 Diag(IdLoc, diag::err_redefinition) << Id;
17763 notePreviousDefinition(PrevDecl, IdLoc);
17764 return nullptr;
17765 }
17766 }
17767
17768 // Process attributes.
17769 ProcessDeclAttributeList(S, New, Attrs);
17770 AddPragmaAttributes(S, New);
17771
17772 // Register this decl in the current scope stack.
17773 New->setAccess(TheEnumDecl->getAccess());
17774 PushOnScopeChains(New, S);
17775
17776 ActOnDocumentableDecl(New);
17777
17778 return New;
17779}
17780
17781// Returns true when the enum initial expression does not trigger the
17782// duplicate enum warning. A few common cases are exempted as follows:
17783// Element2 = Element1
17784// Element2 = Element1 + 1
17785// Element2 = Element1 - 1
17786// Where Element2 and Element1 are from the same enum.
17787static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17788 Expr *InitExpr = ECD->getInitExpr();
17789 if (!InitExpr)
17790 return true;
17791 InitExpr = InitExpr->IgnoreImpCasts();
17792
17793 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17794 if (!BO->isAdditiveOp())
17795 return true;
17796 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17797 if (!IL)
17798 return true;
17799 if (IL->getValue() != 1)
17800 return true;
17801
17802 InitExpr = BO->getLHS();
17803 }
17804
17805 // This checks if the elements are from the same enum.
17806 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17807 if (!DRE)
17808 return true;
17809
17810 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17811 if (!EnumConstant)
17812 return true;
17813
17814 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17815 Enum)
17816 return true;
17817
17818 return false;
17819}
17820
17821// Emits a warning when an element is implicitly set a value that
17822// a previous element has already been set to.
17823static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17824 EnumDecl *Enum, QualType EnumType) {
17825 // Avoid anonymous enums
17826 if (!Enum->getIdentifier())
17827 return;
17828
17829 // Only check for small enums.
17830 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17831 return;
17832
17833 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17834 return;
17835
17836 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17837 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17838
17839 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17840
17841 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17842 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17843
17844 // Use int64_t as a key to avoid needing special handling for map keys.
17845 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17846 llvm::APSInt Val = D->getInitVal();
17847 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17848 };
17849
17850 DuplicatesVector DupVector;
17851 ValueToVectorMap EnumMap;
17852
17853 // Populate the EnumMap with all values represented by enum constants without
17854 // an initializer.
17855 for (auto *Element : Elements) {
17856 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17857
17858 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17859 // this constant. Skip this enum since it may be ill-formed.
17860 if (!ECD) {
17861 return;
17862 }
17863
17864 // Constants with initalizers are handled in the next loop.
17865 if (ECD->getInitExpr())
17866 continue;
17867
17868 // Duplicate values are handled in the next loop.
17869 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17870 }
17871
17872 if (EnumMap.size() == 0)
17873 return;
17874
17875 // Create vectors for any values that has duplicates.
17876 for (auto *Element : Elements) {
17877 // The last loop returned if any constant was null.
17878 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17879 if (!ValidDuplicateEnum(ECD, Enum))
17880 continue;
17881
17882 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17883 if (Iter == EnumMap.end())
17884 continue;
17885
17886 DeclOrVector& Entry = Iter->second;
17887 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17888 // Ensure constants are different.
17889 if (D == ECD)
17890 continue;
17891
17892 // Create new vector and push values onto it.
17893 auto Vec = std::make_unique<ECDVector>();
17894 Vec->push_back(D);
17895 Vec->push_back(ECD);
17896
17897 // Update entry to point to the duplicates vector.
17898 Entry = Vec.get();
17899
17900 // Store the vector somewhere we can consult later for quick emission of
17901 // diagnostics.
17902 DupVector.emplace_back(std::move(Vec));
17903 continue;
17904 }
17905
17906 ECDVector *Vec = Entry.get<ECDVector*>();
17907 // Make sure constants are not added more than once.
17908 if (*Vec->begin() == ECD)
17909 continue;
17910
17911 Vec->push_back(ECD);
17912 }
17913
17914 // Emit diagnostics.
17915 for (const auto &Vec : DupVector) {
17916 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17916, __PRETTY_FUNCTION__))
;
17917
17918 // Emit warning for one enum constant.
17919 auto *FirstECD = Vec->front();
17920 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17921 << FirstECD << FirstECD->getInitVal().toString(10)
17922 << FirstECD->getSourceRange();
17923
17924 // Emit one note for each of the remaining enum constants with
17925 // the same value.
17926 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17927 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17928 << ECD << ECD->getInitVal().toString(10)
17929 << ECD->getSourceRange();
17930 }
17931}
17932
17933bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17934 bool AllowMask) const {
17935 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17935, __PRETTY_FUNCTION__))
;
17936 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 17936, __PRETTY_FUNCTION__))
;
17937
17938 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17939 llvm::APInt &FlagBits = R.first->second;
17940
17941 if (R.second) {
17942 for (auto *E : ED->enumerators()) {
17943 const auto &EVal = E->getInitVal();
17944 // Only single-bit enumerators introduce new flag values.
17945 if (EVal.isPowerOf2())
17946 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17947 }
17948 }
17949
17950 // A value is in a flag enum if either its bits are a subset of the enum's
17951 // flag bits (the first condition) or we are allowing masks and the same is
17952 // true of its complement (the second condition). When masks are allowed, we
17953 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17954 //
17955 // While it's true that any value could be used as a mask, the assumption is
17956 // that a mask will have all of the insignificant bits set. Anything else is
17957 // likely a logic error.
17958 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17959 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17960}
17961
17962void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17963 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17964 const ParsedAttributesView &Attrs) {
17965 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17966 QualType EnumType = Context.getTypeDeclType(Enum);
17967
17968 ProcessDeclAttributeList(S, Enum, Attrs);
17969
17970 if (Enum->isDependentType()) {
17971 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17972 EnumConstantDecl *ECD =
17973 cast_or_null<EnumConstantDecl>(Elements[i]);
17974 if (!ECD) continue;
17975
17976 ECD->setType(EnumType);
17977 }
17978
17979 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
17980 return;
17981 }
17982
17983 // TODO: If the result value doesn't fit in an int, it must be a long or long
17984 // long value. ISO C does not support this, but GCC does as an extension,
17985 // emit a warning.
17986 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17987 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
17988 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
17989
17990 // Verify that all the values are okay, compute the size of the values, and
17991 // reverse the list.
17992 unsigned NumNegativeBits = 0;
17993 unsigned NumPositiveBits = 0;
17994
17995 // Keep track of whether all elements have type int.
17996 bool AllElementsInt = true;
17997
17998 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17999 EnumConstantDecl *ECD =
18000 cast_or_null<EnumConstantDecl>(Elements[i]);
18001 if (!ECD) continue; // Already issued a diagnostic.
18002
18003 const llvm::APSInt &InitVal = ECD->getInitVal();
18004
18005 // Keep track of the size of positive and negative values.
18006 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18007 NumPositiveBits = std::max(NumPositiveBits,
18008 (unsigned)InitVal.getActiveBits());
18009 else
18010 NumNegativeBits = std::max(NumNegativeBits,
18011 (unsigned)InitVal.getMinSignedBits());
18012
18013 // Keep track of whether every enum element has type int (very common).
18014 if (AllElementsInt)
18015 AllElementsInt = ECD->getType() == Context.IntTy;
18016 }
18017
18018 // Figure out the type that should be used for this enum.
18019 QualType BestType;
18020 unsigned BestWidth;
18021
18022 // C++0x N3000 [conv.prom]p3:
18023 // An rvalue of an unscoped enumeration type whose underlying
18024 // type is not fixed can be converted to an rvalue of the first
18025 // of the following types that can represent all the values of
18026 // the enumeration: int, unsigned int, long int, unsigned long
18027 // int, long long int, or unsigned long long int.
18028 // C99 6.4.4.3p2:
18029 // An identifier declared as an enumeration constant has type int.
18030 // The C99 rule is modified by a gcc extension
18031 QualType BestPromotionType;
18032
18033 bool Packed = Enum->hasAttr<PackedAttr>();
18034 // -fshort-enums is the equivalent to specifying the packed attribute on all
18035 // enum definitions.
18036 if (LangOpts.ShortEnums)
18037 Packed = true;
18038
18039 // If the enum already has a type because it is fixed or dictated by the
18040 // target, promote that type instead of analyzing the enumerators.
18041 if (Enum->isComplete()) {
18042 BestType = Enum->getIntegerType();
18043 if (BestType->isPromotableIntegerType())
18044 BestPromotionType = Context.getPromotedIntegerType(BestType);
18045 else
18046 BestPromotionType = BestType;
18047
18048 BestWidth = Context.getIntWidth(BestType);
18049 }
18050 else if (NumNegativeBits) {
18051 // If there is a negative value, figure out the smallest integer type (of
18052 // int/long/longlong) that fits.
18053 // If it's packed, check also if it fits a char or a short.
18054 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18055 BestType = Context.SignedCharTy;
18056 BestWidth = CharWidth;
18057 } else if (Packed && NumNegativeBits <= ShortWidth &&
18058 NumPositiveBits < ShortWidth) {
18059 BestType = Context.ShortTy;
18060 BestWidth = ShortWidth;
18061 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18062 BestType = Context.IntTy;
18063 BestWidth = IntWidth;
18064 } else {
18065 BestWidth = Context.getTargetInfo().getLongWidth();
18066
18067 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18068 BestType = Context.LongTy;
18069 } else {
18070 BestWidth = Context.getTargetInfo().getLongLongWidth();
18071
18072 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18073 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18074 BestType = Context.LongLongTy;
18075 }
18076 }
18077 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18078 } else {
18079 // If there is no negative value, figure out the smallest type that fits
18080 // all of the enumerator values.
18081 // If it's packed, check also if it fits a char or a short.
18082 if (Packed && NumPositiveBits <= CharWidth) {
18083 BestType = Context.UnsignedCharTy;
18084 BestPromotionType = Context.IntTy;
18085 BestWidth = CharWidth;
18086 } else if (Packed && NumPositiveBits <= ShortWidth) {
18087 BestType = Context.UnsignedShortTy;
18088 BestPromotionType = Context.IntTy;
18089 BestWidth = ShortWidth;
18090 } else if (NumPositiveBits <= IntWidth) {
18091 BestType = Context.UnsignedIntTy;
18092 BestWidth = IntWidth;
18093 BestPromotionType
18094 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18095 ? Context.UnsignedIntTy : Context.IntTy;
18096 } else if (NumPositiveBits <=
18097 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18098 BestType = Context.UnsignedLongTy;
18099 BestPromotionType
18100 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18101 ? Context.UnsignedLongTy : Context.LongTy;
18102 } else {
18103 BestWidth = Context.getTargetInfo().getLongLongWidth();
18104 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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 18105, __PRETTY_FUNCTION__))
18105 "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-12.0.0~++20201102111116+1ed2ca68191/clang/lib/Sema/SemaDecl.cpp"
, 18105, __PRETTY_FUNCTION__))
;
18106 BestType = Context.UnsignedLongLongTy;
18107 BestPromotionType
18108 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18109 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18110 }
18111 }
18112
18113 // Loop over all of the enumerator constants, changing their types to match
18114 // the type of the enum if needed.
18115 for (auto *D : Elements) {
18116 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18117 if (!ECD) continue; // Already issued a diagnostic.
18118
18119 // Standard C says the enumerators have int type, but we allow, as an
18120 // extension, the enumerators to be larger than int size. If each
18121 // enumerator value fits in an int, type it as an int, otherwise type it the
18122 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18123 // that X has type 'int', not 'unsigned'.
18124
18125 // Determine whether the value fits into an int.
18126 llvm::APSInt InitVal = ECD->getInitVal();
18127
18128 // If it fits into an integer type, force it. Otherwise force it to match
18129 // the enum decl type.
18130 QualType NewTy;
18131 unsigned NewWidth;
18132 bool NewSign;
18133 if (!getLangOpts().CPlusPlus &&
18134 !Enum->isFixed() &&
18135 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18136 NewTy = Context.IntTy;
18137 NewWidth = IntWidth;
18138 NewSign = true;
18139 } else if (ECD->getType() == BestType) {
18140 // Already the right type!
18141 if (getLangOpts().CPlusPlus)
18142 // C++ [dcl.enum]p4: Following the closing brace of an
18143 // enum-specifier, each enumerator has the type of its
18144 // enumeration.
18145 ECD->setType(EnumType);
18146 continue;
18147 } else {
18148 NewTy = BestType;
18149 NewWidth = BestWidth;
18150 NewSign = BestType->isSignedIntegerOrEnumerationType();
18151 }
18152
18153 // Adjust the APSInt value.
18154 InitVal = InitVal.extOrTrunc(NewWidth);
18155 InitVal.setIsSigned(NewSign);
18156 ECD->setInitVal(InitVal);
18157
18158 // Adjust the Expr initializer and type.
18159 if (ECD->getInitExpr() &&
18160 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18161 ECD->setInitExpr(ImplicitCastExpr::Create(
18162 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18163 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18164 if (getLangOpts().CPlusPlus)
18165 // C++ [dcl.enum]p4: Following the closing brace of an
18166 // enum-specifier, each enumerator has the type of its
18167 // enumeration.
18168 ECD->setType(EnumType);
18169 else
18170 ECD->setType(NewTy);
18171 }
18172
18173 Enum->completeDefinition(BestType, BestPromotionType,
18174 NumPositiveBits, NumNegativeBits);
18175
18176 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18177
18178 if (Enum->isClosedFlag()) {
18179 for (Decl *D : Elements) {
18180 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18181 if (!ECD) continue; // Already issued a diagnostic.
18182
18183 llvm::APSInt InitVal = ECD->getInitVal();
18184 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18185 !IsValueInFlagEnum(Enum, InitVal, true))
18186 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18187 << ECD << Enum;
18188 }
18189 }
18190
18191 // Now that the enum type is defined, ensure it's not been underaligned.
18192 if (Enum->hasAttrs())
18193 CheckAlignasUnderalignment(Enum);
18194}
18195
18196Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18197 SourceLocation StartLoc,
18198 SourceLocation EndLoc) {
18199 StringLiteral *AsmString = cast<StringLiteral>(expr);
18200
18201 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18202 AsmString, StartLoc,
18203 EndLoc);
18204 CurContext->addDecl(New);
18205 return New;
18206}
18207
18208void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18209 IdentifierInfo* AliasName,
18210 SourceLocation PragmaLoc,
18211 SourceLocation NameLoc,
18212 SourceLocation AliasNameLoc) {
18213 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18214 LookupOrdinaryName);
18215 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18216 AttributeCommonInfo::AS_Pragma);
18217 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18218 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18219
18220 // If a declaration that:
18221 // 1) declares a function or a variable
18222 // 2) has external linkage
18223 // already exists, add a label attribute to it.
18224 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18225 if (isDeclExternC(PrevDecl))
18226 PrevDecl->addAttr(Attr);
18227 else
18228 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18229 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18230 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18231 } else
18232 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18233}
18234
18235void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18236 SourceLocation PragmaLoc,
18237 SourceLocation NameLoc) {
18238 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18239
18240 if (PrevDecl) {
18241 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18242 } else {
18243 (void)WeakUndeclaredIdentifiers.insert(
18244 std::pair<IdentifierInfo*,WeakInfo>
18245 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18246 }
18247}
18248
18249void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18250 IdentifierInfo* AliasName,
18251 SourceLocation PragmaLoc,
18252 SourceLocation NameLoc,
18253 SourceLocation AliasNameLoc) {
18254 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18255 LookupOrdinaryName);
18256 WeakInfo W = WeakInfo(Name, NameLoc);
18257
18258 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18259 if (!PrevDecl->hasAttr<AliasAttr>())
18260 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18261 DeclApplyPragmaWeak(TUScope, ND, W);
18262 } else {
18263 (void)WeakUndeclaredIdentifiers.insert(
18264 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18265 }
18266}
18267
18268Decl *Sema::getObjCDeclContext() const {
18269 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18270}
18271
18272Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18273 bool Final) {
18274 // SYCL functions can be template, so we check if they have appropriate
18275 // attribute prior to checking if it is a template.
18276 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18277 return FunctionEmissionStatus::Emitted;
18278
18279 // Templates are emitted when they're instantiated.
18280 if (FD->isDependentContext())
18281 return FunctionEmissionStatus::TemplateDiscarded;
18282
18283 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18284 if (LangOpts.OpenMPIsDevice) {
18285 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18286 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18287 if (DevTy.hasValue()) {
18288 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18289 OMPES = FunctionEmissionStatus::OMPDiscarded;
18290 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18291 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18292 OMPES = FunctionEmissionStatus::Emitted;
18293 }
18294 }
18295 } else if (LangOpts.OpenMP) {
18296 // In OpenMP 4.5 all the functions are host functions.
18297 if (LangOpts.OpenMP <= 45) {
18298 OMPES = FunctionEmissionStatus::Emitted;
18299 } else {
18300 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18301 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18302 // In OpenMP 5.0 or above, DevTy may be changed later by
18303 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18304 // having no value does not imply host. The emission status will be
18305 // checked again at the end of compilation unit.
18306 if (DevTy.hasValue()) {
18307 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18308 OMPES = FunctionEmissionStatus::OMPDiscarded;
18309 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18310 *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18311 OMPES = FunctionEmissionStatus::Emitted;
18312 } else if (Final)
18313 OMPES = FunctionEmissionStatus::Emitted;
18314 }
18315 }
18316 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18317 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18318 return OMPES;
18319
18320 if (LangOpts.CUDA) {
18321 // When compiling for device, host functions are never emitted. Similarly,
18322 // when compiling for host, device and global functions are never emitted.
18323 // (Technically, we do emit a host-side stub for global functions, but this
18324 // doesn't count for our purposes here.)
18325 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18326 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18327 return FunctionEmissionStatus::CUDADiscarded;
18328 if (!LangOpts.CUDAIsDevice &&
18329 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18330 return FunctionEmissionStatus::CUDADiscarded;
18331
18332 // Check whether this function is externally visible -- if so, it's
18333 // known-emitted.
18334 //
18335 // We have to check the GVA linkage of the function's *definition* -- if we
18336 // only have a declaration, we don't know whether or not the function will
18337 // be emitted, because (say) the definition could include "inline".
18338 FunctionDecl *Def = FD->getDefinition();
18339
18340 if (Def &&
18341 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18342 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18343 return FunctionEmissionStatus::Emitted;
18344 }
18345
18346 // Otherwise, the function is known-emitted if it's in our set of
18347 // known-emitted functions.
18348 return FunctionEmissionStatus::Unknown;
18349}
18350
18351bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18352 // Host-side references to a __global__ function refer to the stub, so the
18353 // function itself is never emitted and therefore should not be marked.
18354 // If we have host fn calls kernel fn calls host+device, the HD function
18355 // does not get instantiated on the host. We model this by omitting at the
18356 // call to the kernel from the callgraph. This ensures that, when compiling
18357 // for host, only HD functions actually called from the host get marked as
18358 // known-emitted.
18359 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18360 IdentifyCUDATarget(Callee) == CFT_Global;
18361}

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

/build/llvm-toolchain-snapshot-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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-12.0.0~++20201102111116+1ed2ca68191/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