Bug Summary

File:clang/lib/Sema/SemaDecl.cpp
Warning:line 11534, column 10
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~++20200927111121+5811d723998/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/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~++20200927111121+5811d723998/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998=. -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-09-28-092409-31635-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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~++20200927111121+5811d723998/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() &&
1482 !D->getDeclContext()->getRedeclContext()->Equals(
1483 D->getLexicalDeclContext()->getRedeclContext()) &&
1484 !D->getLexicalDeclContext()->isFunctionOrMethod())
1485 return;
1486
1487 // Template instantiations should also not be pushed into scope.
1488 if (isa<FunctionDecl>(D) &&
1489 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1490 return;
1491
1492 // If this replaces anything in the current scope,
1493 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1494 IEnd = IdResolver.end();
1495 for (; I != IEnd; ++I) {
1496 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1497 S->RemoveDecl(*I);
1498 IdResolver.RemoveDecl(*I);
1499
1500 // Should only need to replace one decl.
1501 break;
1502 }
1503 }
1504
1505 S->AddDecl(D);
1506
1507 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1508 // Implicitly-generated labels may end up getting generated in an order that
1509 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1510 // the label at the appropriate place in the identifier chain.
1511 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1512 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1513 if (IDC == CurContext) {
1514 if (!S->isDeclScope(*I))
1515 continue;
1516 } else if (IDC->Encloses(CurContext))
1517 break;
1518 }
1519
1520 IdResolver.InsertDeclAfter(I, D);
1521 } else {
1522 IdResolver.AddDecl(D);
1523 }
1524}
1525
1526bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1527 bool AllowInlineNamespace) {
1528 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1529}
1530
1531Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1532 DeclContext *TargetDC = DC->getPrimaryContext();
1533 do {
1534 if (DeclContext *ScopeDC = S->getEntity())
1535 if (ScopeDC->getPrimaryContext() == TargetDC)
1536 return S;
1537 } while ((S = S->getParent()));
1538
1539 return nullptr;
1540}
1541
1542static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1543 DeclContext*,
1544 ASTContext&);
1545
1546/// Filters out lookup results that don't fall within the given scope
1547/// as determined by isDeclInScope.
1548void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1549 bool ConsiderLinkage,
1550 bool AllowInlineNamespace) {
1551 LookupResult::Filter F = R.makeFilter();
1552 while (F.hasNext()) {
1553 NamedDecl *D = F.next();
1554
1555 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1556 continue;
1557
1558 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1559 continue;
1560
1561 F.erase();
1562 }
1563
1564 F.done();
1565}
1566
1567/// We've determined that \p New is a redeclaration of \p Old. Check that they
1568/// have compatible owning modules.
1569bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1570 // FIXME: The Modules TS is not clear about how friend declarations are
1571 // to be treated. It's not meaningful to have different owning modules for
1572 // linkage in redeclarations of the same entity, so for now allow the
1573 // redeclaration and change the owning modules to match.
1574 if (New->getFriendObjectKind() &&
1575 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1576 New->setLocalOwningModule(Old->getOwningModule());
1577 makeMergedDefinitionVisible(New);
1578 return false;
1579 }
1580
1581 Module *NewM = New->getOwningModule();
1582 Module *OldM = Old->getOwningModule();
1583
1584 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1585 NewM = NewM->Parent;
1586 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1587 OldM = OldM->Parent;
1588
1589 if (NewM == OldM)
1590 return false;
1591
1592 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1593 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1594 if (NewIsModuleInterface || OldIsModuleInterface) {
1595 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1596 // if a declaration of D [...] appears in the purview of a module, all
1597 // other such declarations shall appear in the purview of the same module
1598 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1599 << New
1600 << NewIsModuleInterface
1601 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1602 << OldIsModuleInterface
1603 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1604 Diag(Old->getLocation(), diag::note_previous_declaration);
1605 New->setInvalidDecl();
1606 return true;
1607 }
1608
1609 return false;
1610}
1611
1612static bool isUsingDecl(NamedDecl *D) {
1613 return isa<UsingShadowDecl>(D) ||
1614 isa<UnresolvedUsingTypenameDecl>(D) ||
1615 isa<UnresolvedUsingValueDecl>(D);
1616}
1617
1618/// Removes using shadow declarations from the lookup results.
1619static void RemoveUsingDecls(LookupResult &R) {
1620 LookupResult::Filter F = R.makeFilter();
1621 while (F.hasNext())
1622 if (isUsingDecl(F.next()))
1623 F.erase();
1624
1625 F.done();
1626}
1627
1628/// Check for this common pattern:
1629/// @code
1630/// class S {
1631/// S(const S&); // DO NOT IMPLEMENT
1632/// void operator=(const S&); // DO NOT IMPLEMENT
1633/// };
1634/// @endcode
1635static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1636 // FIXME: Should check for private access too but access is set after we get
1637 // the decl here.
1638 if (D->doesThisDeclarationHaveABody())
1639 return false;
1640
1641 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1642 return CD->isCopyConstructor();
1643 return D->isCopyAssignmentOperator();
1644}
1645
1646// We need this to handle
1647//
1648// typedef struct {
1649// void *foo() { return 0; }
1650// } A;
1651//
1652// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1653// for example. If 'A', foo will have external linkage. If we have '*A',
1654// foo will have no linkage. Since we can't know until we get to the end
1655// of the typedef, this function finds out if D might have non-external linkage.
1656// Callers should verify at the end of the TU if it D has external linkage or
1657// not.
1658bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1659 const DeclContext *DC = D->getDeclContext();
1660 while (!DC->isTranslationUnit()) {
1661 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1662 if (!RD->hasNameForLinkage())
1663 return true;
1664 }
1665 DC = DC->getParent();
1666 }
1667
1668 return !D->isExternallyVisible();
1669}
1670
1671// FIXME: This needs to be refactored; some other isInMainFile users want
1672// these semantics.
1673static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1674 if (S.TUKind != TU_Complete)
1675 return false;
1676 return S.SourceMgr.isInMainFile(Loc);
1677}
1678
1679bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1680 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 1680, __PRETTY_FUNCTION__))
;
1681
1682 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1683 return false;
1684
1685 // Ignore all entities declared within templates, and out-of-line definitions
1686 // of members of class templates.
1687 if (D->getDeclContext()->isDependentContext() ||
1688 D->getLexicalDeclContext()->isDependentContext())
1689 return false;
1690
1691 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1692 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1693 return false;
1694 // A non-out-of-line declaration of a member specialization was implicitly
1695 // instantiated; it's the out-of-line declaration that we're interested in.
1696 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1697 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1698 return false;
1699
1700 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1701 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1702 return false;
1703 } else {
1704 // 'static inline' functions are defined in headers; don't warn.
1705 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1706 return false;
1707 }
1708
1709 if (FD->doesThisDeclarationHaveABody() &&
1710 Context.DeclMustBeEmitted(FD))
1711 return false;
1712 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1713 // Constants and utility variables are defined in headers with internal
1714 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1715 // like "inline".)
1716 if (!isMainFileLoc(*this, VD->getLocation()))
1717 return false;
1718
1719 if (Context.DeclMustBeEmitted(VD))
1720 return false;
1721
1722 if (VD->isStaticDataMember() &&
1723 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1724 return false;
1725 if (VD->isStaticDataMember() &&
1726 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1727 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1728 return false;
1729
1730 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1731 return false;
1732 } else {
1733 return false;
1734 }
1735
1736 // Only warn for unused decls internal to the translation unit.
1737 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1738 // for inline functions defined in the main source file, for instance.
1739 return mightHaveNonExternalLinkage(D);
1740}
1741
1742void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1743 if (!D)
1744 return;
1745
1746 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1747 const FunctionDecl *First = FD->getFirstDecl();
1748 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1749 return; // First should already be in the vector.
1750 }
1751
1752 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1753 const VarDecl *First = VD->getFirstDecl();
1754 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1755 return; // First should already be in the vector.
1756 }
1757
1758 if (ShouldWarnIfUnusedFileScopedDecl(D))
1759 UnusedFileScopedDecls.push_back(D);
1760}
1761
1762static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1763 if (D->isInvalidDecl())
1764 return false;
1765
1766 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1767 // For a decomposition declaration, warn if none of the bindings are
1768 // referenced, instead of if the variable itself is referenced (which
1769 // it is, by the bindings' expressions).
1770 for (auto *BD : DD->bindings())
1771 if (BD->isReferenced())
1772 return false;
1773 } else if (!D->getDeclName()) {
1774 return false;
1775 } else if (D->isReferenced() || D->isUsed()) {
1776 return false;
1777 }
1778
1779 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1780 return false;
1781
1782 if (isa<LabelDecl>(D))
1783 return true;
1784
1785 // Except for labels, we only care about unused decls that are local to
1786 // functions.
1787 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1788 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1789 // For dependent types, the diagnostic is deferred.
1790 WithinFunction =
1791 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1792 if (!WithinFunction)
1793 return false;
1794
1795 if (isa<TypedefNameDecl>(D))
1796 return true;
1797
1798 // White-list anything that isn't a local variable.
1799 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1800 return false;
1801
1802 // Types of valid local variables should be complete, so this should succeed.
1803 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1804
1805 // White-list anything with an __attribute__((unused)) type.
1806 const auto *Ty = VD->getType().getTypePtr();
1807
1808 // Only look at the outermost level of typedef.
1809 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1810 if (TT->getDecl()->hasAttr<UnusedAttr>())
1811 return false;
1812 }
1813
1814 // If we failed to complete the type for some reason, or if the type is
1815 // dependent, don't diagnose the variable.
1816 if (Ty->isIncompleteType() || Ty->isDependentType())
1817 return false;
1818
1819 // Look at the element type to ensure that the warning behaviour is
1820 // consistent for both scalars and arrays.
1821 Ty = Ty->getBaseElementTypeUnsafe();
1822
1823 if (const TagType *TT = Ty->getAs<TagType>()) {
1824 const TagDecl *Tag = TT->getDecl();
1825 if (Tag->hasAttr<UnusedAttr>())
1826 return false;
1827
1828 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1829 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1830 return false;
1831
1832 if (const Expr *Init = VD->getInit()) {
1833 if (const ExprWithCleanups *Cleanups =
1834 dyn_cast<ExprWithCleanups>(Init))
1835 Init = Cleanups->getSubExpr();
1836 const CXXConstructExpr *Construct =
1837 dyn_cast<CXXConstructExpr>(Init);
1838 if (Construct && !Construct->isElidable()) {
1839 CXXConstructorDecl *CD = Construct->getConstructor();
1840 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1841 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1842 return false;
1843 }
1844
1845 // Suppress the warning if we don't know how this is constructed, and
1846 // it could possibly be non-trivial constructor.
1847 if (Init->isTypeDependent())
1848 for (const CXXConstructorDecl *Ctor : RD->ctors())
1849 if (!Ctor->isTrivial())
1850 return false;
1851 }
1852 }
1853 }
1854
1855 // TODO: __attribute__((unused)) templates?
1856 }
1857
1858 return true;
1859}
1860
1861static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1862 FixItHint &Hint) {
1863 if (isa<LabelDecl>(D)) {
1864 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1865 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1866 true);
1867 if (AfterColon.isInvalid())
1868 return;
1869 Hint = FixItHint::CreateRemoval(
1870 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1871 }
1872}
1873
1874void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1875 if (D->getTypeForDecl()->isDependentType())
1876 return;
1877
1878 for (auto *TmpD : D->decls()) {
1879 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1880 DiagnoseUnusedDecl(T);
1881 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1882 DiagnoseUnusedNestedTypedefs(R);
1883 }
1884}
1885
1886/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1887/// unless they are marked attr(unused).
1888void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1889 if (!ShouldDiagnoseUnusedDecl(D))
1890 return;
1891
1892 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1893 // typedefs can be referenced later on, so the diagnostics are emitted
1894 // at end-of-translation-unit.
1895 UnusedLocalTypedefNameCandidates.insert(TD);
1896 return;
1897 }
1898
1899 FixItHint Hint;
1900 GenerateFixForUnusedDecl(D, Context, Hint);
1901
1902 unsigned DiagID;
1903 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1904 DiagID = diag::warn_unused_exception_param;
1905 else if (isa<LabelDecl>(D))
1906 DiagID = diag::warn_unused_label;
1907 else
1908 DiagID = diag::warn_unused_variable;
1909
1910 Diag(D->getLocation(), DiagID) << D << Hint;
1911}
1912
1913static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1914 // Verify that we have no forward references left. If so, there was a goto
1915 // or address of a label taken, but no definition of it. Label fwd
1916 // definitions are indicated with a null substmt which is also not a resolved
1917 // MS inline assembly label name.
1918 bool Diagnose = false;
1919 if (L->isMSAsmLabel())
1920 Diagnose = !L->isResolvedMSAsmLabel();
1921 else
1922 Diagnose = L->getStmt() == nullptr;
1923 if (Diagnose)
1924 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1925}
1926
1927void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1928 S->mergeNRVOIntoParent();
1929
1930 if (S->decl_empty()) return;
1931 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
1932 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 1932, __PRETTY_FUNCTION__))
;
1933
1934 for (auto *TmpD : S->decls()) {
1935 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 1935, __PRETTY_FUNCTION__))
;
1936
1937 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 1937, __PRETTY_FUNCTION__))
;
1938 NamedDecl *D = cast<NamedDecl>(TmpD);
1939
1940 // Diagnose unused variables in this scope.
1941 if (!S->hasUnrecoverableErrorOccurred()) {
1942 DiagnoseUnusedDecl(D);
1943 if (const auto *RD = dyn_cast<RecordDecl>(D))
1944 DiagnoseUnusedNestedTypedefs(RD);
1945 }
1946
1947 if (!D->getDeclName()) continue;
1948
1949 // If this was a forward reference to a label, verify it was defined.
1950 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1951 CheckPoppedLabel(LD, *this);
1952
1953 // Remove this name from our lexical scope, and warn on it if we haven't
1954 // already.
1955 IdResolver.RemoveDecl(D);
1956 auto ShadowI = ShadowingDecls.find(D);
1957 if (ShadowI != ShadowingDecls.end()) {
1958 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1959 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1960 << D << FD << FD->getParent();
1961 Diag(FD->getLocation(), diag::note_previous_declaration);
1962 }
1963 ShadowingDecls.erase(ShadowI);
1964 }
1965 }
1966}
1967
1968/// Look for an Objective-C class in the translation unit.
1969///
1970/// \param Id The name of the Objective-C class we're looking for. If
1971/// typo-correction fixes this name, the Id will be updated
1972/// to the fixed name.
1973///
1974/// \param IdLoc The location of the name in the translation unit.
1975///
1976/// \param DoTypoCorrection If true, this routine will attempt typo correction
1977/// if there is no class with the given name.
1978///
1979/// \returns The declaration of the named Objective-C class, or NULL if the
1980/// class could not be found.
1981ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1982 SourceLocation IdLoc,
1983 bool DoTypoCorrection) {
1984 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1985 // creation from this context.
1986 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1987
1988 if (!IDecl && DoTypoCorrection) {
1989 // Perform typo correction at the given location, but only if we
1990 // find an Objective-C class name.
1991 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
1992 if (TypoCorrection C =
1993 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
1994 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
1995 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1996 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1997 Id = IDecl->getIdentifier();
1998 }
1999 }
2000 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2001 // This routine must always return a class definition, if any.
2002 if (Def && Def->getDefinition())
2003 Def = Def->getDefinition();
2004 return Def;
2005}
2006
2007/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2008/// from S, where a non-field would be declared. This routine copes
2009/// with the difference between C and C++ scoping rules in structs and
2010/// unions. For example, the following code is well-formed in C but
2011/// ill-formed in C++:
2012/// @code
2013/// struct S6 {
2014/// enum { BAR } e;
2015/// };
2016///
2017/// void test_S6() {
2018/// struct S6 a;
2019/// a.e = BAR;
2020/// }
2021/// @endcode
2022/// For the declaration of BAR, this routine will return a different
2023/// scope. The scope S will be the scope of the unnamed enumeration
2024/// within S6. In C++, this routine will return the scope associated
2025/// with S6, because the enumeration's scope is a transparent
2026/// context but structures can contain non-field names. In C, this
2027/// routine will return the translation unit scope, since the
2028/// enumeration's scope is a transparent context and structures cannot
2029/// contain non-field names.
2030Scope *Sema::getNonFieldDeclScope(Scope *S) {
2031 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2032 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2033 (S->isClassScope() && !getLangOpts().CPlusPlus))
2034 S = S->getParent();
2035 return S;
2036}
2037
2038static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2039 ASTContext::GetBuiltinTypeError Error) {
2040 switch (Error) {
2041 case ASTContext::GE_None:
2042 return "";
2043 case ASTContext::GE_Missing_type:
2044 return BuiltinInfo.getHeaderName(ID);
2045 case ASTContext::GE_Missing_stdio:
2046 return "stdio.h";
2047 case ASTContext::GE_Missing_setjmp:
2048 return "setjmp.h";
2049 case ASTContext::GE_Missing_ucontext:
2050 return "ucontext.h";
2051 }
2052 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 2052)
;
2053}
2054
2055FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2056 unsigned ID, SourceLocation Loc) {
2057 DeclContext *Parent = Context.getTranslationUnitDecl();
2058
2059 if (getLangOpts().CPlusPlus) {
2060 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2061 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2062 CLinkageDecl->setImplicit();
2063 Parent->addDecl(CLinkageDecl);
2064 Parent = CLinkageDecl;
2065 }
2066
2067 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2068 /*TInfo=*/nullptr, SC_Extern, false,
2069 Type->isFunctionProtoType());
2070 New->setImplicit();
2071 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2072
2073 // Create Decl objects for each parameter, adding them to the
2074 // FunctionDecl.
2075 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2076 SmallVector<ParmVarDecl *, 16> Params;
2077 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2078 ParmVarDecl *parm = ParmVarDecl::Create(
2079 Context, New, SourceLocation(), SourceLocation(), nullptr,
2080 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2081 parm->setScopeInfo(0, i);
2082 Params.push_back(parm);
2083 }
2084 New->setParams(Params);
2085 }
2086
2087 AddKnownFunctionAttributes(New);
2088 return New;
2089}
2090
2091/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2092/// file scope. lazily create a decl for it. ForRedeclaration is true
2093/// if we're creating this built-in in anticipation of redeclaring the
2094/// built-in.
2095NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2096 Scope *S, bool ForRedeclaration,
2097 SourceLocation Loc) {
2098 LookupNecessaryTypesForBuiltin(S, ID);
2099
2100 ASTContext::GetBuiltinTypeError Error;
2101 QualType R = Context.GetBuiltinType(ID, Error);
2102 if (Error) {
2103 if (!ForRedeclaration)
2104 return nullptr;
2105
2106 // If we have a builtin without an associated type we should not emit a
2107 // warning when we were not able to find a type for it.
2108 if (Error == ASTContext::GE_Missing_type)
2109 return nullptr;
2110
2111 // If we could not find a type for setjmp it is because the jmp_buf type was
2112 // not defined prior to the setjmp declaration.
2113 if (Error == ASTContext::GE_Missing_setjmp) {
2114 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2115 << Context.BuiltinInfo.getName(ID);
2116 return nullptr;
2117 }
2118
2119 // Generally, we emit a warning that the declaration requires the
2120 // appropriate header.
2121 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2122 << getHeaderName(Context.BuiltinInfo, ID, Error)
2123 << Context.BuiltinInfo.getName(ID);
2124 return nullptr;
2125 }
2126
2127 if (!ForRedeclaration &&
2128 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2129 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2130 Diag(Loc, diag::ext_implicit_lib_function_decl)
2131 << Context.BuiltinInfo.getName(ID) << R;
2132 if (Context.BuiltinInfo.getHeaderName(ID) &&
2133 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
2134 Diag(Loc, diag::note_include_header_or_declare)
2135 << Context.BuiltinInfo.getHeaderName(ID)
2136 << Context.BuiltinInfo.getName(ID);
2137 }
2138
2139 if (R.isNull())
2140 return nullptr;
2141
2142 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2143 RegisterLocallyScopedExternCDecl(New, S);
2144
2145 // TUScope is the translation-unit scope to insert this function into.
2146 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2147 // relate Scopes to DeclContexts, and probably eliminate CurContext
2148 // entirely, but we're not there yet.
2149 DeclContext *SavedContext = CurContext;
2150 CurContext = New->getDeclContext();
2151 PushOnScopeChains(New, TUScope);
2152 CurContext = SavedContext;
2153 return New;
2154}
2155
2156/// Typedef declarations don't have linkage, but they still denote the same
2157/// entity if their types are the same.
2158/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2159/// isSameEntity.
2160static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2161 TypedefNameDecl *Decl,
2162 LookupResult &Previous) {
2163 // This is only interesting when modules are enabled.
2164 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2165 return;
2166
2167 // Empty sets are uninteresting.
2168 if (Previous.empty())
2169 return;
2170
2171 LookupResult::Filter Filter = Previous.makeFilter();
2172 while (Filter.hasNext()) {
2173 NamedDecl *Old = Filter.next();
2174
2175 // Non-hidden declarations are never ignored.
2176 if (S.isVisible(Old))
2177 continue;
2178
2179 // Declarations of the same entity are not ignored, even if they have
2180 // different linkages.
2181 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2182 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2183 Decl->getUnderlyingType()))
2184 continue;
2185
2186 // If both declarations give a tag declaration a typedef name for linkage
2187 // purposes, then they declare the same entity.
2188 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2189 Decl->getAnonDeclWithTypedefName())
2190 continue;
2191 }
2192
2193 Filter.erase();
2194 }
2195
2196 Filter.done();
2197}
2198
2199bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2200 QualType OldType;
2201 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2202 OldType = OldTypedef->getUnderlyingType();
2203 else
2204 OldType = Context.getTypeDeclType(Old);
2205 QualType NewType = New->getUnderlyingType();
2206
2207 if (NewType->isVariablyModifiedType()) {
2208 // Must not redefine a typedef with a variably-modified type.
2209 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2210 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2211 << Kind << NewType;
2212 if (Old->getLocation().isValid())
2213 notePreviousDefinition(Old, New->getLocation());
2214 New->setInvalidDecl();
2215 return true;
2216 }
2217
2218 if (OldType != NewType &&
2219 !OldType->isDependentType() &&
2220 !NewType->isDependentType() &&
2221 !Context.hasSameType(OldType, NewType)) {
2222 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2223 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2224 << Kind << NewType << OldType;
2225 if (Old->getLocation().isValid())
2226 notePreviousDefinition(Old, New->getLocation());
2227 New->setInvalidDecl();
2228 return true;
2229 }
2230 return false;
2231}
2232
2233/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2234/// same name and scope as a previous declaration 'Old'. Figure out
2235/// how to resolve this situation, merging decls or emitting
2236/// diagnostics as appropriate. If there was an error, set New to be invalid.
2237///
2238void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2239 LookupResult &OldDecls) {
2240 // If the new decl is known invalid already, don't bother doing any
2241 // merging checks.
2242 if (New->isInvalidDecl()) return;
2243
2244 // Allow multiple definitions for ObjC built-in typedefs.
2245 // FIXME: Verify the underlying types are equivalent!
2246 if (getLangOpts().ObjC) {
2247 const IdentifierInfo *TypeID = New->getIdentifier();
2248 switch (TypeID->getLength()) {
2249 default: break;
2250 case 2:
2251 {
2252 if (!TypeID->isStr("id"))
2253 break;
2254 QualType T = New->getUnderlyingType();
2255 if (!T->isPointerType())
2256 break;
2257 if (!T->isVoidPointerType()) {
2258 QualType PT = T->castAs<PointerType>()->getPointeeType();
2259 if (!PT->isStructureType())
2260 break;
2261 }
2262 Context.setObjCIdRedefinitionType(T);
2263 // Install the built-in type for 'id', ignoring the current definition.
2264 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2265 return;
2266 }
2267 case 5:
2268 if (!TypeID->isStr("Class"))
2269 break;
2270 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2271 // Install the built-in type for 'Class', ignoring the current definition.
2272 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2273 return;
2274 case 3:
2275 if (!TypeID->isStr("SEL"))
2276 break;
2277 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2278 // Install the built-in type for 'SEL', ignoring the current definition.
2279 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2280 return;
2281 }
2282 // Fall through - the typedef name was not a builtin type.
2283 }
2284
2285 // Verify the old decl was also a type.
2286 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2287 if (!Old) {
2288 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2289 << New->getDeclName();
2290
2291 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2292 if (OldD->getLocation().isValid())
2293 notePreviousDefinition(OldD, New->getLocation());
2294
2295 return New->setInvalidDecl();
2296 }
2297
2298 // If the old declaration is invalid, just give up here.
2299 if (Old->isInvalidDecl())
2300 return New->setInvalidDecl();
2301
2302 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2303 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2304 auto *NewTag = New->getAnonDeclWithTypedefName();
2305 NamedDecl *Hidden = nullptr;
2306 if (OldTag && NewTag &&
2307 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2308 !hasVisibleDefinition(OldTag, &Hidden)) {
2309 // There is a definition of this tag, but it is not visible. Use it
2310 // instead of our tag.
2311 New->setTypeForDecl(OldTD->getTypeForDecl());
2312 if (OldTD->isModed())
2313 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2314 OldTD->getUnderlyingType());
2315 else
2316 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2317
2318 // Make the old tag definition visible.
2319 makeMergedDefinitionVisible(Hidden);
2320
2321 // If this was an unscoped enumeration, yank all of its enumerators
2322 // out of the scope.
2323 if (isa<EnumDecl>(NewTag)) {
2324 Scope *EnumScope = getNonFieldDeclScope(S);
2325 for (auto *D : NewTag->decls()) {
2326 auto *ED = cast<EnumConstantDecl>(D);
2327 assert(EnumScope->isDeclScope(ED))((EnumScope->isDeclScope(ED)) ? static_cast<void> (0
) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 2327, __PRETTY_FUNCTION__))
;
2328 EnumScope->RemoveDecl(ED);
2329 IdResolver.RemoveDecl(ED);
2330 ED->getLexicalDeclContext()->removeDecl(ED);
2331 }
2332 }
2333 }
2334 }
2335
2336 // If the typedef types are not identical, reject them in all languages and
2337 // with any extensions enabled.
2338 if (isIncompatibleTypedef(Old, New))
2339 return;
2340
2341 // The types match. Link up the redeclaration chain and merge attributes if
2342 // the old declaration was a typedef.
2343 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2344 New->setPreviousDecl(Typedef);
2345 mergeDeclAttributes(New, Old);
2346 }
2347
2348 if (getLangOpts().MicrosoftExt)
2349 return;
2350
2351 if (getLangOpts().CPlusPlus) {
2352 // C++ [dcl.typedef]p2:
2353 // In a given non-class scope, a typedef specifier can be used to
2354 // redefine the name of any type declared in that scope to refer
2355 // to the type to which it already refers.
2356 if (!isa<CXXRecordDecl>(CurContext))
2357 return;
2358
2359 // C++0x [dcl.typedef]p4:
2360 // In a given class scope, a typedef specifier can be used to redefine
2361 // any class-name declared in that scope that is not also a typedef-name
2362 // to refer to the type to which it already refers.
2363 //
2364 // This wording came in via DR424, which was a correction to the
2365 // wording in DR56, which accidentally banned code like:
2366 //
2367 // struct S {
2368 // typedef struct A { } A;
2369 // };
2370 //
2371 // in the C++03 standard. We implement the C++0x semantics, which
2372 // allow the above but disallow
2373 //
2374 // struct S {
2375 // typedef int I;
2376 // typedef int I;
2377 // };
2378 //
2379 // since that was the intent of DR56.
2380 if (!isa<TypedefNameDecl>(Old))
2381 return;
2382
2383 Diag(New->getLocation(), diag::err_redefinition)
2384 << New->getDeclName();
2385 notePreviousDefinition(Old, New->getLocation());
2386 return New->setInvalidDecl();
2387 }
2388
2389 // Modules always permit redefinition of typedefs, as does C11.
2390 if (getLangOpts().Modules || getLangOpts().C11)
2391 return;
2392
2393 // If we have a redefinition of a typedef in C, emit a warning. This warning
2394 // is normally mapped to an error, but can be controlled with
2395 // -Wtypedef-redefinition. If either the original or the redefinition is
2396 // in a system header, don't emit this for compatibility with GCC.
2397 if (getDiagnostics().getSuppressSystemWarnings() &&
2398 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2399 (Old->isImplicit() ||
2400 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2401 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2402 return;
2403
2404 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2405 << New->getDeclName();
2406 notePreviousDefinition(Old, New->getLocation());
2407}
2408
2409/// DeclhasAttr - returns true if decl Declaration already has the target
2410/// attribute.
2411static bool DeclHasAttr(const Decl *D, const Attr *A) {
2412 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2413 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2414 for (const auto *i : D->attrs())
2415 if (i->getKind() == A->getKind()) {
2416 if (Ann) {
2417 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2418 return true;
2419 continue;
2420 }
2421 // FIXME: Don't hardcode this check
2422 if (OA && isa<OwnershipAttr>(i))
2423 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2424 return true;
2425 }
2426
2427 return false;
2428}
2429
2430static bool isAttributeTargetADefinition(Decl *D) {
2431 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2432 return VD->isThisDeclarationADefinition();
2433 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2434 return TD->isCompleteDefinition() || TD->isBeingDefined();
2435 return true;
2436}
2437
2438/// Merge alignment attributes from \p Old to \p New, taking into account the
2439/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2440///
2441/// \return \c true if any attributes were added to \p New.
2442static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2443 // Look for alignas attributes on Old, and pick out whichever attribute
2444 // specifies the strictest alignment requirement.
2445 AlignedAttr *OldAlignasAttr = nullptr;
2446 AlignedAttr *OldStrictestAlignAttr = nullptr;
2447 unsigned OldAlign = 0;
2448 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2449 // FIXME: We have no way of representing inherited dependent alignments
2450 // in a case like:
2451 // template<int A, int B> struct alignas(A) X;
2452 // template<int A, int B> struct alignas(B) X {};
2453 // For now, we just ignore any alignas attributes which are not on the
2454 // definition in such a case.
2455 if (I->isAlignmentDependent())
2456 return false;
2457
2458 if (I->isAlignas())
2459 OldAlignasAttr = I;
2460
2461 unsigned Align = I->getAlignment(S.Context);
2462 if (Align > OldAlign) {
2463 OldAlign = Align;
2464 OldStrictestAlignAttr = I;
2465 }
2466 }
2467
2468 // Look for alignas attributes on New.
2469 AlignedAttr *NewAlignasAttr = nullptr;
2470 unsigned NewAlign = 0;
2471 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2472 if (I->isAlignmentDependent())
2473 return false;
2474
2475 if (I->isAlignas())
2476 NewAlignasAttr = I;
2477
2478 unsigned Align = I->getAlignment(S.Context);
2479 if (Align > NewAlign)
2480 NewAlign = Align;
2481 }
2482
2483 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2484 // Both declarations have 'alignas' attributes. We require them to match.
2485 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2486 // fall short. (If two declarations both have alignas, they must both match
2487 // every definition, and so must match each other if there is a definition.)
2488
2489 // If either declaration only contains 'alignas(0)' specifiers, then it
2490 // specifies the natural alignment for the type.
2491 if (OldAlign == 0 || NewAlign == 0) {
2492 QualType Ty;
2493 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2494 Ty = VD->getType();
2495 else
2496 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2497
2498 if (OldAlign == 0)
2499 OldAlign = S.Context.getTypeAlign(Ty);
2500 if (NewAlign == 0)
2501 NewAlign = S.Context.getTypeAlign(Ty);
2502 }
2503
2504 if (OldAlign != NewAlign) {
2505 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2506 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2507 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2508 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2509 }
2510 }
2511
2512 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2513 // C++11 [dcl.align]p6:
2514 // if any declaration of an entity has an alignment-specifier,
2515 // every defining declaration of that entity shall specify an
2516 // equivalent alignment.
2517 // C11 6.7.5/7:
2518 // If the definition of an object does not have an alignment
2519 // specifier, any other declaration of that object shall also
2520 // have no alignment specifier.
2521 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2522 << OldAlignasAttr;
2523 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2524 << OldAlignasAttr;
2525 }
2526
2527 bool AnyAdded = false;
2528
2529 // Ensure we have an attribute representing the strictest alignment.
2530 if (OldAlign > NewAlign) {
2531 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2532 Clone->setInherited(true);
2533 New->addAttr(Clone);
2534 AnyAdded = true;
2535 }
2536
2537 // Ensure we have an alignas attribute if the old declaration had one.
2538 if (OldAlignasAttr && !NewAlignasAttr &&
2539 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2540 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2541 Clone->setInherited(true);
2542 New->addAttr(Clone);
2543 AnyAdded = true;
2544 }
2545
2546 return AnyAdded;
2547}
2548
2549static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2550 const InheritableAttr *Attr,
2551 Sema::AvailabilityMergeKind AMK) {
2552 // This function copies an attribute Attr from a previous declaration to the
2553 // new declaration D if the new declaration doesn't itself have that attribute
2554 // yet or if that attribute allows duplicates.
2555 // If you're adding a new attribute that requires logic different from
2556 // "use explicit attribute on decl if present, else use attribute from
2557 // previous decl", for example if the attribute needs to be consistent
2558 // between redeclarations, you need to call a custom merge function here.
2559 InheritableAttr *NewAttr = nullptr;
2560 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2561 NewAttr = S.mergeAvailabilityAttr(
2562 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2563 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2564 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2565 AA->getPriority());
2566 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2567 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2568 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2569 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2570 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2571 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2572 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2573 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2574 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2575 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2576 FA->getFirstArg());
2577 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2578 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2579 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2580 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2581 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2582 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2583 IA->getInheritanceModel());
2584 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2585 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2586 &S.Context.Idents.get(AA->getSpelling()));
2587 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2588 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2589 isa<CUDAGlobalAttr>(Attr))) {
2590 // CUDA target attributes are part of function signature for
2591 // overloading purposes and must not be merged.
2592 return false;
2593 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2594 NewAttr = S.mergeMinSizeAttr(D, *MA);
2595 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2596 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2597 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2598 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2599 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2600 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2601 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2602 NewAttr = S.mergeCommonAttr(D, *CommonA);
2603 else if (isa<AlignedAttr>(Attr))
2604 // AlignedAttrs are handled separately, because we need to handle all
2605 // such attributes on a declaration at the same time.
2606 NewAttr = nullptr;
2607 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2608 (AMK == Sema::AMK_Override ||
2609 AMK == Sema::AMK_ProtocolImplementation))
2610 NewAttr = nullptr;
2611 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2612 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2613 else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2614 NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2615 else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2616 NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2617 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2618 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2619 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2620 NewAttr = S.mergeImportNameAttr(D, *INA);
2621 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2622 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2623
2624 if (NewAttr) {
2625 NewAttr->setInherited(true);
2626 D->addAttr(NewAttr);
2627 if (isa<MSInheritanceAttr>(NewAttr))
2628 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2629 return true;
2630 }
2631
2632 return false;
2633}
2634
2635static const NamedDecl *getDefinition(const Decl *D) {
2636 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2637 return TD->getDefinition();
2638 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2639 const VarDecl *Def = VD->getDefinition();
2640 if (Def)
2641 return Def;
2642 return VD->getActingDefinition();
2643 }
2644 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2645 return FD->getDefinition();
2646 return nullptr;
2647}
2648
2649static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2650 for (const auto *Attribute : D->attrs())
2651 if (Attribute->getKind() == Kind)
2652 return true;
2653 return false;
2654}
2655
2656/// checkNewAttributesAfterDef - If we already have a definition, check that
2657/// there are no new attributes in this declaration.
2658static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2659 if (!New->hasAttrs())
2660 return;
2661
2662 const NamedDecl *Def = getDefinition(Old);
2663 if (!Def || Def == New)
2664 return;
2665
2666 AttrVec &NewAttributes = New->getAttrs();
2667 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2668 const Attr *NewAttribute = NewAttributes[I];
2669
2670 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2671 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2672 Sema::SkipBodyInfo SkipBody;
2673 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2674
2675 // If we're skipping this definition, drop the "alias" attribute.
2676 if (SkipBody.ShouldSkip) {
2677 NewAttributes.erase(NewAttributes.begin() + I);
2678 --E;
2679 continue;
2680 }
2681 } else {
2682 VarDecl *VD = cast<VarDecl>(New);
2683 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2684 VarDecl::TentativeDefinition
2685 ? diag::err_alias_after_tentative
2686 : diag::err_redefinition;
2687 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2688 if (Diag == diag::err_redefinition)
2689 S.notePreviousDefinition(Def, VD->getLocation());
2690 else
2691 S.Diag(Def->getLocation(), diag::note_previous_definition);
2692 VD->setInvalidDecl();
2693 }
2694 ++I;
2695 continue;
2696 }
2697
2698 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2699 // Tentative definitions are only interesting for the alias check above.
2700 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2701 ++I;
2702 continue;
2703 }
2704 }
2705
2706 if (hasAttribute(Def, NewAttribute->getKind())) {
2707 ++I;
2708 continue; // regular attr merging will take care of validating this.
2709 }
2710
2711 if (isa<C11NoReturnAttr>(NewAttribute)) {
2712 // C's _Noreturn is allowed to be added to a function after it is defined.
2713 ++I;
2714 continue;
2715 } else if (isa<UuidAttr>(NewAttribute)) {
2716 // msvc will allow a subsequent definition to add an uuid to a class
2717 ++I;
2718 continue;
2719 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2720 if (AA->isAlignas()) {
2721 // C++11 [dcl.align]p6:
2722 // if any declaration of an entity has an alignment-specifier,
2723 // every defining declaration of that entity shall specify an
2724 // equivalent alignment.
2725 // C11 6.7.5/7:
2726 // If the definition of an object does not have an alignment
2727 // specifier, any other declaration of that object shall also
2728 // have no alignment specifier.
2729 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2730 << AA;
2731 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2732 << AA;
2733 NewAttributes.erase(NewAttributes.begin() + I);
2734 --E;
2735 continue;
2736 }
2737 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2738 // If there is a C definition followed by a redeclaration with this
2739 // attribute then there are two different definitions. In C++, prefer the
2740 // standard diagnostics.
2741 if (!S.getLangOpts().CPlusPlus) {
2742 S.Diag(NewAttribute->getLocation(),
2743 diag::err_loader_uninitialized_redeclaration);
2744 S.Diag(Def->getLocation(), diag::note_previous_definition);
2745 NewAttributes.erase(NewAttributes.begin() + I);
2746 --E;
2747 continue;
2748 }
2749 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2750 cast<VarDecl>(New)->isInline() &&
2751 !cast<VarDecl>(New)->isInlineSpecified()) {
2752 // Don't warn about applying selectany to implicitly inline variables.
2753 // Older compilers and language modes would require the use of selectany
2754 // to make such variables inline, and it would have no effect if we
2755 // honored it.
2756 ++I;
2757 continue;
2758 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2759 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2760 // declarations after defintions.
2761 ++I;
2762 continue;
2763 }
2764
2765 S.Diag(NewAttribute->getLocation(),
2766 diag::warn_attribute_precede_definition);
2767 S.Diag(Def->getLocation(), diag::note_previous_definition);
2768 NewAttributes.erase(NewAttributes.begin() + I);
2769 --E;
2770 }
2771}
2772
2773static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2774 const ConstInitAttr *CIAttr,
2775 bool AttrBeforeInit) {
2776 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2777
2778 // Figure out a good way to write this specifier on the old declaration.
2779 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2780 // enough of the attribute list spelling information to extract that without
2781 // heroics.
2782 std::string SuitableSpelling;
2783 if (S.getLangOpts().CPlusPlus20)
2784 SuitableSpelling = std::string(
2785 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2786 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2787 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2788 InsertLoc, {tok::l_square, tok::l_square,
2789 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2790 S.PP.getIdentifierInfo("require_constant_initialization"),
2791 tok::r_square, tok::r_square}));
2792 if (SuitableSpelling.empty())
2793 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2794 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2795 S.PP.getIdentifierInfo("require_constant_initialization"),
2796 tok::r_paren, tok::r_paren}));
2797 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2798 SuitableSpelling = "constinit";
2799 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2800 SuitableSpelling = "[[clang::require_constant_initialization]]";
2801 if (SuitableSpelling.empty())
2802 SuitableSpelling = "__attribute__((require_constant_initialization))";
2803 SuitableSpelling += " ";
2804
2805 if (AttrBeforeInit) {
2806 // extern constinit int a;
2807 // int a = 0; // error (missing 'constinit'), accepted as extension
2808 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 2808, __PRETTY_FUNCTION__))
;
2809 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2810 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2811 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2812 } else {
2813 // int a = 0;
2814 // constinit extern int a; // error (missing 'constinit')
2815 S.Diag(CIAttr->getLocation(),
2816 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2817 : diag::warn_require_const_init_added_too_late)
2818 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2819 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2820 << CIAttr->isConstinit()
2821 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2822 }
2823}
2824
2825/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2826void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2827 AvailabilityMergeKind AMK) {
2828 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2829 UsedAttr *NewAttr = OldAttr->clone(Context);
2830 NewAttr->setInherited(true);
2831 New->addAttr(NewAttr);
2832 }
2833
2834 if (!Old->hasAttrs() && !New->hasAttrs())
2835 return;
2836
2837 // [dcl.constinit]p1:
2838 // If the [constinit] specifier is applied to any declaration of a
2839 // variable, it shall be applied to the initializing declaration.
2840 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2841 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2842 if (bool(OldConstInit) != bool(NewConstInit)) {
2843 const auto *OldVD = cast<VarDecl>(Old);
2844 auto *NewVD = cast<VarDecl>(New);
2845
2846 // Find the initializing declaration. Note that we might not have linked
2847 // the new declaration into the redeclaration chain yet.
2848 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2849 if (!InitDecl &&
2850 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2851 InitDecl = NewVD;
2852
2853 if (InitDecl == NewVD) {
2854 // This is the initializing declaration. If it would inherit 'constinit',
2855 // that's ill-formed. (Note that we do not apply this to the attribute
2856 // form).
2857 if (OldConstInit && OldConstInit->isConstinit())
2858 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2859 /*AttrBeforeInit=*/true);
2860 } else if (NewConstInit) {
2861 // This is the first time we've been told that this declaration should
2862 // have a constant initializer. If we already saw the initializing
2863 // declaration, this is too late.
2864 if (InitDecl && InitDecl != NewVD) {
2865 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2866 /*AttrBeforeInit=*/false);
2867 NewVD->dropAttr<ConstInitAttr>();
2868 }
2869 }
2870 }
2871
2872 // Attributes declared post-definition are currently ignored.
2873 checkNewAttributesAfterDef(*this, New, Old);
2874
2875 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2876 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2877 if (!OldA->isEquivalent(NewA)) {
2878 // This redeclaration changes __asm__ label.
2879 Diag(New->getLocation(), diag::err_different_asm_label);
2880 Diag(OldA->getLocation(), diag::note_previous_declaration);
2881 }
2882 } else if (Old->isUsed()) {
2883 // This redeclaration adds an __asm__ label to a declaration that has
2884 // already been ODR-used.
2885 Diag(New->getLocation(), diag::err_late_asm_label_name)
2886 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2887 }
2888 }
2889
2890 // Re-declaration cannot add abi_tag's.
2891 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2892 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2893 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2894 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2895 NewTag) == OldAbiTagAttr->tags_end()) {
2896 Diag(NewAbiTagAttr->getLocation(),
2897 diag::err_new_abi_tag_on_redeclaration)
2898 << NewTag;
2899 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2900 }
2901 }
2902 } else {
2903 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2904 Diag(Old->getLocation(), diag::note_previous_declaration);
2905 }
2906 }
2907
2908 // This redeclaration adds a section attribute.
2909 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2910 if (auto *VD = dyn_cast<VarDecl>(New)) {
2911 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2912 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2913 Diag(Old->getLocation(), diag::note_previous_declaration);
2914 }
2915 }
2916 }
2917
2918 // Redeclaration adds code-seg attribute.
2919 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2920 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2921 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2922 Diag(New->getLocation(), diag::warn_mismatched_section)
2923 << 0 /*codeseg*/;
2924 Diag(Old->getLocation(), diag::note_previous_declaration);
2925 }
2926
2927 if (!Old->hasAttrs())
2928 return;
2929
2930 bool foundAny = New->hasAttrs();
2931
2932 // Ensure that any moving of objects within the allocated map is done before
2933 // we process them.
2934 if (!foundAny) New->setAttrs(AttrVec());
2935
2936 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2937 // Ignore deprecated/unavailable/availability attributes if requested.
2938 AvailabilityMergeKind LocalAMK = AMK_None;
2939 if (isa<DeprecatedAttr>(I) ||
2940 isa<UnavailableAttr>(I) ||
2941 isa<AvailabilityAttr>(I)) {
2942 switch (AMK) {
2943 case AMK_None:
2944 continue;
2945
2946 case AMK_Redeclaration:
2947 case AMK_Override:
2948 case AMK_ProtocolImplementation:
2949 LocalAMK = AMK;
2950 break;
2951 }
2952 }
2953
2954 // Already handled.
2955 if (isa<UsedAttr>(I))
2956 continue;
2957
2958 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2959 foundAny = true;
2960 }
2961
2962 if (mergeAlignedAttrs(*this, New, Old))
2963 foundAny = true;
2964
2965 if (!foundAny) New->dropAttrs();
2966}
2967
2968/// mergeParamDeclAttributes - Copy attributes from the old parameter
2969/// to the new one.
2970static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2971 const ParmVarDecl *oldDecl,
2972 Sema &S) {
2973 // C++11 [dcl.attr.depend]p2:
2974 // The first declaration of a function shall specify the
2975 // carries_dependency attribute for its declarator-id if any declaration
2976 // of the function specifies the carries_dependency attribute.
2977 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2978 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2979 S.Diag(CDA->getLocation(),
2980 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2981 // Find the first declaration of the parameter.
2982 // FIXME: Should we build redeclaration chains for function parameters?
2983 const FunctionDecl *FirstFD =
2984 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2985 const ParmVarDecl *FirstVD =
2986 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2987 S.Diag(FirstVD->getLocation(),
2988 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2989 }
2990
2991 if (!oldDecl->hasAttrs())
2992 return;
2993
2994 bool foundAny = newDecl->hasAttrs();
2995
2996 // Ensure that any moving of objects within the allocated map is
2997 // done before we process them.
2998 if (!foundAny) newDecl->setAttrs(AttrVec());
2999
3000 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3001 if (!DeclHasAttr(newDecl, I)) {
3002 InheritableAttr *newAttr =
3003 cast<InheritableParamAttr>(I->clone(S.Context));
3004 newAttr->setInherited(true);
3005 newDecl->addAttr(newAttr);
3006 foundAny = true;
3007 }
3008 }
3009
3010 if (!foundAny) newDecl->dropAttrs();
3011}
3012
3013static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3014 const ParmVarDecl *OldParam,
3015 Sema &S) {
3016 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3017 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3018 if (*Oldnullability != *Newnullability) {
3019 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3020 << DiagNullabilityKind(
3021 *Newnullability,
3022 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3023 != 0))
3024 << DiagNullabilityKind(
3025 *Oldnullability,
3026 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3027 != 0));
3028 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3029 }
3030 } else {
3031 QualType NewT = NewParam->getType();
3032 NewT = S.Context.getAttributedType(
3033 AttributedType::getNullabilityAttrKind(*Oldnullability),
3034 NewT, NewT);
3035 NewParam->setType(NewT);
3036 }
3037 }
3038}
3039
3040namespace {
3041
3042/// Used in MergeFunctionDecl to keep track of function parameters in
3043/// C.
3044struct GNUCompatibleParamWarning {
3045 ParmVarDecl *OldParm;
3046 ParmVarDecl *NewParm;
3047 QualType PromotedType;
3048};
3049
3050} // end anonymous namespace
3051
3052// Determine whether the previous declaration was a definition, implicit
3053// declaration, or a declaration.
3054template <typename T>
3055static std::pair<diag::kind, SourceLocation>
3056getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3057 diag::kind PrevDiag;
3058 SourceLocation OldLocation = Old->getLocation();
3059 if (Old->isThisDeclarationADefinition())
3060 PrevDiag = diag::note_previous_definition;
3061 else if (Old->isImplicit()) {
3062 PrevDiag = diag::note_previous_implicit_declaration;
3063 if (OldLocation.isInvalid())
3064 OldLocation = New->getLocation();
3065 } else
3066 PrevDiag = diag::note_previous_declaration;
3067 return std::make_pair(PrevDiag, OldLocation);
3068}
3069
3070/// canRedefineFunction - checks if a function can be redefined. Currently,
3071/// only extern inline functions can be redefined, and even then only in
3072/// GNU89 mode.
3073static bool canRedefineFunction(const FunctionDecl *FD,
3074 const LangOptions& LangOpts) {
3075 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3076 !LangOpts.CPlusPlus &&
3077 FD->isInlineSpecified() &&
3078 FD->getStorageClass() == SC_Extern);
3079}
3080
3081const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3082 const AttributedType *AT = T->getAs<AttributedType>();
3083 while (AT && !AT->isCallingConv())
3084 AT = AT->getModifiedType()->getAs<AttributedType>();
3085 return AT;
3086}
3087
3088template <typename T>
3089static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3090 const DeclContext *DC = Old->getDeclContext();
3091 if (DC->isRecord())
3092 return false;
3093
3094 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3095 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3096 return true;
3097 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3098 return true;
3099 return false;
3100}
3101
3102template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3103static bool isExternC(VarTemplateDecl *) { return false; }
3104
3105/// Check whether a redeclaration of an entity introduced by a
3106/// using-declaration is valid, given that we know it's not an overload
3107/// (nor a hidden tag declaration).
3108template<typename ExpectedDecl>
3109static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3110 ExpectedDecl *New) {
3111 // C++11 [basic.scope.declarative]p4:
3112 // Given a set of declarations in a single declarative region, each of
3113 // which specifies the same unqualified name,
3114 // -- they shall all refer to the same entity, or all refer to functions
3115 // and function templates; or
3116 // -- exactly one declaration shall declare a class name or enumeration
3117 // name that is not a typedef name and the other declarations shall all
3118 // refer to the same variable or enumerator, or all refer to functions
3119 // and function templates; in this case the class name or enumeration
3120 // name is hidden (3.3.10).
3121
3122 // C++11 [namespace.udecl]p14:
3123 // If a function declaration in namespace scope or block scope has the
3124 // same name and the same parameter-type-list as a function introduced
3125 // by a using-declaration, and the declarations do not declare the same
3126 // function, the program is ill-formed.
3127
3128 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3129 if (Old &&
3130 !Old->getDeclContext()->getRedeclContext()->Equals(
3131 New->getDeclContext()->getRedeclContext()) &&
3132 !(isExternC(Old) && isExternC(New)))
3133 Old = nullptr;
3134
3135 if (!Old) {
3136 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3137 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3138 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
3139 return true;
3140 }
3141 return false;
3142}
3143
3144static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3145 const FunctionDecl *B) {
3146 assert(A->getNumParams() == B->getNumParams())((A->getNumParams() == B->getNumParams()) ? static_cast
<void> (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3146, __PRETTY_FUNCTION__))
;
3147
3148 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3149 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3150 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3151 if (AttrA == AttrB)
3152 return true;
3153 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3154 AttrA->isDynamic() == AttrB->isDynamic();
3155 };
3156
3157 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3158}
3159
3160/// If necessary, adjust the semantic declaration context for a qualified
3161/// declaration to name the correct inline namespace within the qualifier.
3162static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3163 DeclaratorDecl *OldD) {
3164 // The only case where we need to update the DeclContext is when
3165 // redeclaration lookup for a qualified name finds a declaration
3166 // in an inline namespace within the context named by the qualifier:
3167 //
3168 // inline namespace N { int f(); }
3169 // int ::f(); // Sema DC needs adjusting from :: to N::.
3170 //
3171 // For unqualified declarations, the semantic context *can* change
3172 // along the redeclaration chain (for local extern declarations,
3173 // extern "C" declarations, and friend declarations in particular).
3174 if (!NewD->getQualifier())
3175 return;
3176
3177 // NewD is probably already in the right context.
3178 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3179 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3180 if (NamedDC->Equals(SemaDC))
3181 return;
3182
3183 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3185, __PRETTY_FUNCTION__))
3184 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3185, __PRETTY_FUNCTION__))
3185 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3185, __PRETTY_FUNCTION__))
;
3186
3187 auto *LexDC = NewD->getLexicalDeclContext();
3188 auto FixSemaDC = [=](NamedDecl *D) {
3189 if (!D)
3190 return;
3191 D->setDeclContext(SemaDC);
3192 D->setLexicalDeclContext(LexDC);
3193 };
3194
3195 FixSemaDC(NewD);
3196 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3197 FixSemaDC(FD->getDescribedFunctionTemplate());
3198 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3199 FixSemaDC(VD->getDescribedVarTemplate());
3200}
3201
3202/// MergeFunctionDecl - We just parsed a function 'New' from
3203/// declarator D which has the same name and scope as a previous
3204/// declaration 'Old'. Figure out how to resolve this situation,
3205/// merging decls or emitting diagnostics as appropriate.
3206///
3207/// In C++, New and Old must be declarations that are not
3208/// overloaded. Use IsOverload to determine whether New and Old are
3209/// overloaded, and to select the Old declaration that New should be
3210/// merged with.
3211///
3212/// Returns true if there was an error, false otherwise.
3213bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3214 Scope *S, bool MergeTypeWithOld) {
3215 // Verify the old decl was also a function.
3216 FunctionDecl *Old = OldD->getAsFunction();
3217 if (!Old) {
3218 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3219 if (New->getFriendObjectKind()) {
3220 Diag(New->getLocation(), diag::err_using_decl_friend);
3221 Diag(Shadow->getTargetDecl()->getLocation(),
3222 diag::note_using_decl_target);
3223 Diag(Shadow->getUsingDecl()->getLocation(),
3224 diag::note_using_decl) << 0;
3225 return true;
3226 }
3227
3228 // Check whether the two declarations might declare the same function.
3229 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3230 return true;
3231 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3232 } else {
3233 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3234 << New->getDeclName();
3235 notePreviousDefinition(OldD, New->getLocation());
3236 return true;
3237 }
3238 }
3239
3240 // If the old declaration is invalid, just give up here.
3241 if (Old->isInvalidDecl())
3242 return true;
3243
3244 // Disallow redeclaration of some builtins.
3245 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3246 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3247 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3248 << Old << Old->getType();
3249 return true;
3250 }
3251
3252 diag::kind PrevDiag;
3253 SourceLocation OldLocation;
3254 std::tie(PrevDiag, OldLocation) =
3255 getNoteDiagForInvalidRedeclaration(Old, New);
3256
3257 // Don't complain about this if we're in GNU89 mode and the old function
3258 // is an extern inline function.
3259 // Don't complain about specializations. They are not supposed to have
3260 // storage classes.
3261 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3262 New->getStorageClass() == SC_Static &&
3263 Old->hasExternalFormalLinkage() &&
3264 !New->getTemplateSpecializationInfo() &&
3265 !canRedefineFunction(Old, getLangOpts())) {
3266 if (getLangOpts().MicrosoftExt) {
3267 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3268 Diag(OldLocation, PrevDiag);
3269 } else {
3270 Diag(New->getLocation(), diag::err_static_non_static) << New;
3271 Diag(OldLocation, PrevDiag);
3272 return true;
3273 }
3274 }
3275
3276 if (New->hasAttr<InternalLinkageAttr>() &&
3277 !Old->hasAttr<InternalLinkageAttr>()) {
3278 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3279 << New->getDeclName();
3280 notePreviousDefinition(Old, New->getLocation());
3281 New->dropAttr<InternalLinkageAttr>();
3282 }
3283
3284 if (CheckRedeclarationModuleOwnership(New, Old))
3285 return true;
3286
3287 if (!getLangOpts().CPlusPlus) {
3288 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3289 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3290 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3291 << New << OldOvl;
3292
3293 // Try our best to find a decl that actually has the overloadable
3294 // attribute for the note. In most cases (e.g. programs with only one
3295 // broken declaration/definition), this won't matter.
3296 //
3297 // FIXME: We could do this if we juggled some extra state in
3298 // OverloadableAttr, rather than just removing it.
3299 const Decl *DiagOld = Old;
3300 if (OldOvl) {
3301 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3302 const auto *A = D->getAttr<OverloadableAttr>();
3303 return A && !A->isImplicit();
3304 });
3305 // If we've implicitly added *all* of the overloadable attrs to this
3306 // chain, emitting a "previous redecl" note is pointless.
3307 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3308 }
3309
3310 if (DiagOld)
3311 Diag(DiagOld->getLocation(),
3312 diag::note_attribute_overloadable_prev_overload)
3313 << OldOvl;
3314
3315 if (OldOvl)
3316 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3317 else
3318 New->dropAttr<OverloadableAttr>();
3319 }
3320 }
3321
3322 // If a function is first declared with a calling convention, but is later
3323 // declared or defined without one, all following decls assume the calling
3324 // convention of the first.
3325 //
3326 // It's OK if a function is first declared without a calling convention,
3327 // but is later declared or defined with the default calling convention.
3328 //
3329 // To test if either decl has an explicit calling convention, we look for
3330 // AttributedType sugar nodes on the type as written. If they are missing or
3331 // were canonicalized away, we assume the calling convention was implicit.
3332 //
3333 // Note also that we DO NOT return at this point, because we still have
3334 // other tests to run.
3335 QualType OldQType = Context.getCanonicalType(Old->getType());
3336 QualType NewQType = Context.getCanonicalType(New->getType());
3337 const FunctionType *OldType = cast<FunctionType>(OldQType);
3338 const FunctionType *NewType = cast<FunctionType>(NewQType);
3339 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3340 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3341 bool RequiresAdjustment = false;
3342
3343 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3344 FunctionDecl *First = Old->getFirstDecl();
3345 const FunctionType *FT =
3346 First->getType().getCanonicalType()->castAs<FunctionType>();
3347 FunctionType::ExtInfo FI = FT->getExtInfo();
3348 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3349 if (!NewCCExplicit) {
3350 // Inherit the CC from the previous declaration if it was specified
3351 // there but not here.
3352 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3353 RequiresAdjustment = true;
3354 } else if (Old->getBuiltinID()) {
3355 // Builtin attribute isn't propagated to the new one yet at this point,
3356 // so we check if the old one is a builtin.
3357
3358 // Calling Conventions on a Builtin aren't really useful and setting a
3359 // default calling convention and cdecl'ing some builtin redeclarations is
3360 // common, so warn and ignore the calling convention on the redeclaration.
3361 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3362 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3363 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3364 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3365 RequiresAdjustment = true;
3366 } else {
3367 // Calling conventions aren't compatible, so complain.
3368 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3369 Diag(New->getLocation(), diag::err_cconv_change)
3370 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3371 << !FirstCCExplicit
3372 << (!FirstCCExplicit ? "" :
3373 FunctionType::getNameForCallConv(FI.getCC()));
3374
3375 // Put the note on the first decl, since it is the one that matters.
3376 Diag(First->getLocation(), diag::note_previous_declaration);
3377 return true;
3378 }
3379 }
3380
3381 // FIXME: diagnose the other way around?
3382 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3383 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3384 RequiresAdjustment = true;
3385 }
3386
3387 // Merge regparm attribute.
3388 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3389 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3390 if (NewTypeInfo.getHasRegParm()) {
3391 Diag(New->getLocation(), diag::err_regparm_mismatch)
3392 << NewType->getRegParmType()
3393 << OldType->getRegParmType();
3394 Diag(OldLocation, diag::note_previous_declaration);
3395 return true;
3396 }
3397
3398 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3399 RequiresAdjustment = true;
3400 }
3401
3402 // Merge ns_returns_retained attribute.
3403 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3404 if (NewTypeInfo.getProducesResult()) {
3405 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3406 << "'ns_returns_retained'";
3407 Diag(OldLocation, diag::note_previous_declaration);
3408 return true;
3409 }
3410
3411 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3412 RequiresAdjustment = true;
3413 }
3414
3415 if (OldTypeInfo.getNoCallerSavedRegs() !=
3416 NewTypeInfo.getNoCallerSavedRegs()) {
3417 if (NewTypeInfo.getNoCallerSavedRegs()) {
3418 AnyX86NoCallerSavedRegistersAttr *Attr =
3419 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3420 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3421 Diag(OldLocation, diag::note_previous_declaration);
3422 return true;
3423 }
3424
3425 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3426 RequiresAdjustment = true;
3427 }
3428
3429 if (RequiresAdjustment) {
3430 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3431 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3432 New->setType(QualType(AdjustedType, 0));
3433 NewQType = Context.getCanonicalType(New->getType());
3434 }
3435
3436 // If this redeclaration makes the function inline, we may need to add it to
3437 // UndefinedButUsed.
3438 if (!Old->isInlined() && New->isInlined() &&
3439 !New->hasAttr<GNUInlineAttr>() &&
3440 !getLangOpts().GNUInline &&
3441 Old->isUsed(false) &&
3442 !Old->isDefined() && !New->isThisDeclarationADefinition())
3443 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3444 SourceLocation()));
3445
3446 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3447 // about it.
3448 if (New->hasAttr<GNUInlineAttr>() &&
3449 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3450 UndefinedButUsed.erase(Old->getCanonicalDecl());
3451 }
3452
3453 // If pass_object_size params don't match up perfectly, this isn't a valid
3454 // redeclaration.
3455 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3456 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3457 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3458 << New->getDeclName();
3459 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3460 return true;
3461 }
3462
3463 if (getLangOpts().CPlusPlus) {
3464 // C++1z [over.load]p2
3465 // Certain function declarations cannot be overloaded:
3466 // -- Function declarations that differ only in the return type,
3467 // the exception specification, or both cannot be overloaded.
3468
3469 // Check the exception specifications match. This may recompute the type of
3470 // both Old and New if it resolved exception specifications, so grab the
3471 // types again after this. Because this updates the type, we do this before
3472 // any of the other checks below, which may update the "de facto" NewQType
3473 // but do not necessarily update the type of New.
3474 if (CheckEquivalentExceptionSpec(Old, New))
3475 return true;
3476 OldQType = Context.getCanonicalType(Old->getType());
3477 NewQType = Context.getCanonicalType(New->getType());
3478
3479 // Go back to the type source info to compare the declared return types,
3480 // per C++1y [dcl.type.auto]p13:
3481 // Redeclarations or specializations of a function or function template
3482 // with a declared return type that uses a placeholder type shall also
3483 // use that placeholder, not a deduced type.
3484 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3485 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3486 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3487 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3488 OldDeclaredReturnType)) {
3489 QualType ResQT;
3490 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3491 OldDeclaredReturnType->isObjCObjectPointerType())
3492 // FIXME: This does the wrong thing for a deduced return type.
3493 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3494 if (ResQT.isNull()) {
3495 if (New->isCXXClassMember() && New->isOutOfLine())
3496 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3497 << New << New->getReturnTypeSourceRange();
3498 else
3499 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3500 << New->getReturnTypeSourceRange();
3501 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3502 << Old->getReturnTypeSourceRange();
3503 return true;
3504 }
3505 else
3506 NewQType = ResQT;
3507 }
3508
3509 QualType OldReturnType = OldType->getReturnType();
3510 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3511 if (OldReturnType != NewReturnType) {
3512 // If this function has a deduced return type and has already been
3513 // defined, copy the deduced value from the old declaration.
3514 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3515 if (OldAT && OldAT->isDeduced()) {
3516 New->setType(
3517 SubstAutoType(New->getType(),
3518 OldAT->isDependentType() ? Context.DependentTy
3519 : OldAT->getDeducedType()));
3520 NewQType = Context.getCanonicalType(
3521 SubstAutoType(NewQType,
3522 OldAT->isDependentType() ? Context.DependentTy
3523 : OldAT->getDeducedType()));
3524 }
3525 }
3526
3527 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3528 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3529 if (OldMethod && NewMethod) {
3530 // Preserve triviality.
3531 NewMethod->setTrivial(OldMethod->isTrivial());
3532
3533 // MSVC allows explicit template specialization at class scope:
3534 // 2 CXXMethodDecls referring to the same function will be injected.
3535 // We don't want a redeclaration error.
3536 bool IsClassScopeExplicitSpecialization =
3537 OldMethod->isFunctionTemplateSpecialization() &&
3538 NewMethod->isFunctionTemplateSpecialization();
3539 bool isFriend = NewMethod->getFriendObjectKind();
3540
3541 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3542 !IsClassScopeExplicitSpecialization) {
3543 // -- Member function declarations with the same name and the
3544 // same parameter types cannot be overloaded if any of them
3545 // is a static member function declaration.
3546 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3547 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3548 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3549 return true;
3550 }
3551
3552 // C++ [class.mem]p1:
3553 // [...] A member shall not be declared twice in the
3554 // member-specification, except that a nested class or member
3555 // class template can be declared and then later defined.
3556 if (!inTemplateInstantiation()) {
3557 unsigned NewDiag;
3558 if (isa<CXXConstructorDecl>(OldMethod))
3559 NewDiag = diag::err_constructor_redeclared;
3560 else if (isa<CXXDestructorDecl>(NewMethod))
3561 NewDiag = diag::err_destructor_redeclared;
3562 else if (isa<CXXConversionDecl>(NewMethod))
3563 NewDiag = diag::err_conv_function_redeclared;
3564 else
3565 NewDiag = diag::err_member_redeclared;
3566
3567 Diag(New->getLocation(), NewDiag);
3568 } else {
3569 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3570 << New << New->getType();
3571 }
3572 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3573 return true;
3574
3575 // Complain if this is an explicit declaration of a special
3576 // member that was initially declared implicitly.
3577 //
3578 // As an exception, it's okay to befriend such methods in order
3579 // to permit the implicit constructor/destructor/operator calls.
3580 } else if (OldMethod->isImplicit()) {
3581 if (isFriend) {
3582 NewMethod->setImplicit();
3583 } else {
3584 Diag(NewMethod->getLocation(),
3585 diag::err_definition_of_implicitly_declared_member)
3586 << New << getSpecialMember(OldMethod);
3587 return true;
3588 }
3589 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3590 Diag(NewMethod->getLocation(),
3591 diag::err_definition_of_explicitly_defaulted_member)
3592 << getSpecialMember(OldMethod);
3593 return true;
3594 }
3595 }
3596
3597 // C++11 [dcl.attr.noreturn]p1:
3598 // The first declaration of a function shall specify the noreturn
3599 // attribute if any declaration of that function specifies the noreturn
3600 // attribute.
3601 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3602 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3603 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3604 Diag(Old->getFirstDecl()->getLocation(),
3605 diag::note_noreturn_missing_first_decl);
3606 }
3607
3608 // C++11 [dcl.attr.depend]p2:
3609 // The first declaration of a function shall specify the
3610 // carries_dependency attribute for its declarator-id if any declaration
3611 // of the function specifies the carries_dependency attribute.
3612 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3613 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3614 Diag(CDA->getLocation(),
3615 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3616 Diag(Old->getFirstDecl()->getLocation(),
3617 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3618 }
3619
3620 // (C++98 8.3.5p3):
3621 // All declarations for a function shall agree exactly in both the
3622 // return type and the parameter-type-list.
3623 // We also want to respect all the extended bits except noreturn.
3624
3625 // noreturn should now match unless the old type info didn't have it.
3626 QualType OldQTypeForComparison = OldQType;
3627 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3628 auto *OldType = OldQType->castAs<FunctionProtoType>();
3629 const FunctionType *OldTypeForComparison
3630 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3631 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3632 assert(OldQTypeForComparison.isCanonical())((OldQTypeForComparison.isCanonical()) ? static_cast<void>
(0) : __assert_fail ("OldQTypeForComparison.isCanonical()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3632, __PRETTY_FUNCTION__))
;
3633 }
3634
3635 if (haveIncompatibleLanguageLinkages(Old, New)) {
3636 // As a special case, retain the language linkage from previous
3637 // declarations of a friend function as an extension.
3638 //
3639 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3640 // and is useful because there's otherwise no way to specify language
3641 // linkage within class scope.
3642 //
3643 // Check cautiously as the friend object kind isn't yet complete.
3644 if (New->getFriendObjectKind() != Decl::FOK_None) {
3645 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3646 Diag(OldLocation, PrevDiag);
3647 } else {
3648 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3649 Diag(OldLocation, PrevDiag);
3650 return true;
3651 }
3652 }
3653
3654 // If the function types are compatible, merge the declarations. Ignore the
3655 // exception specifier because it was already checked above in
3656 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3657 // about incompatible types under -fms-compatibility.
3658 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3659 NewQType))
3660 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3661
3662 // If the types are imprecise (due to dependent constructs in friends or
3663 // local extern declarations), it's OK if they differ. We'll check again
3664 // during instantiation.
3665 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3666 return false;
3667
3668 // Fall through for conflicting redeclarations and redefinitions.
3669 }
3670
3671 // C: Function types need to be compatible, not identical. This handles
3672 // duplicate function decls like "void f(int); void f(enum X);" properly.
3673 if (!getLangOpts().CPlusPlus &&
3674 Context.typesAreCompatible(OldQType, NewQType)) {
3675 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3676 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3677 const FunctionProtoType *OldProto = nullptr;
3678 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3679 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3680 // The old declaration provided a function prototype, but the
3681 // new declaration does not. Merge in the prototype.
3682 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3682, __PRETTY_FUNCTION__))
;
3683 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3684 NewQType =
3685 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3686 OldProto->getExtProtoInfo());
3687 New->setType(NewQType);
3688 New->setHasInheritedPrototype();
3689
3690 // Synthesize parameters with the same types.
3691 SmallVector<ParmVarDecl*, 16> Params;
3692 for (const auto &ParamType : OldProto->param_types()) {
3693 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3694 SourceLocation(), nullptr,
3695 ParamType, /*TInfo=*/nullptr,
3696 SC_None, nullptr);
3697 Param->setScopeInfo(0, Params.size());
3698 Param->setImplicit();
3699 Params.push_back(Param);
3700 }
3701
3702 New->setParams(Params);
3703 }
3704
3705 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3706 }
3707
3708 // Check if the function types are compatible when pointer size address
3709 // spaces are ignored.
3710 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3711 return false;
3712
3713 // GNU C permits a K&R definition to follow a prototype declaration
3714 // if the declared types of the parameters in the K&R definition
3715 // match the types in the prototype declaration, even when the
3716 // promoted types of the parameters from the K&R definition differ
3717 // from the types in the prototype. GCC then keeps the types from
3718 // the prototype.
3719 //
3720 // If a variadic prototype is followed by a non-variadic K&R definition,
3721 // the K&R definition becomes variadic. This is sort of an edge case, but
3722 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3723 // C99 6.9.1p8.
3724 if (!getLangOpts().CPlusPlus &&
3725 Old->hasPrototype() && !New->hasPrototype() &&
3726 New->getType()->getAs<FunctionProtoType>() &&
3727 Old->getNumParams() == New->getNumParams()) {
3728 SmallVector<QualType, 16> ArgTypes;
3729 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3730 const FunctionProtoType *OldProto
3731 = Old->getType()->getAs<FunctionProtoType>();
3732 const FunctionProtoType *NewProto
3733 = New->getType()->getAs<FunctionProtoType>();
3734
3735 // Determine whether this is the GNU C extension.
3736 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3737 NewProto->getReturnType());
3738 bool LooseCompatible = !MergedReturn.isNull();
3739 for (unsigned Idx = 0, End = Old->getNumParams();
3740 LooseCompatible && Idx != End; ++Idx) {
3741 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3742 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3743 if (Context.typesAreCompatible(OldParm->getType(),
3744 NewProto->getParamType(Idx))) {
3745 ArgTypes.push_back(NewParm->getType());
3746 } else if (Context.typesAreCompatible(OldParm->getType(),
3747 NewParm->getType(),
3748 /*CompareUnqualified=*/true)) {
3749 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3750 NewProto->getParamType(Idx) };
3751 Warnings.push_back(Warn);
3752 ArgTypes.push_back(NewParm->getType());
3753 } else
3754 LooseCompatible = false;
3755 }
3756
3757 if (LooseCompatible) {
3758 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3759 Diag(Warnings[Warn].NewParm->getLocation(),
3760 diag::ext_param_promoted_not_compatible_with_prototype)
3761 << Warnings[Warn].PromotedType
3762 << Warnings[Warn].OldParm->getType();
3763 if (Warnings[Warn].OldParm->getLocation().isValid())
3764 Diag(Warnings[Warn].OldParm->getLocation(),
3765 diag::note_previous_declaration);
3766 }
3767
3768 if (MergeTypeWithOld)
3769 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3770 OldProto->getExtProtoInfo()));
3771 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3772 }
3773
3774 // Fall through to diagnose conflicting types.
3775 }
3776
3777 // A function that has already been declared has been redeclared or
3778 // defined with a different type; show an appropriate diagnostic.
3779
3780 // If the previous declaration was an implicitly-generated builtin
3781 // declaration, then at the very least we should use a specialized note.
3782 unsigned BuiltinID;
3783 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3784 // If it's actually a library-defined builtin function like 'malloc'
3785 // or 'printf', just warn about the incompatible redeclaration.
3786 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3787 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3788 Diag(OldLocation, diag::note_previous_builtin_declaration)
3789 << Old << Old->getType();
3790 return false;
3791 }
3792
3793 PrevDiag = diag::note_previous_builtin_declaration;
3794 }
3795
3796 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3797 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3798 return true;
3799}
3800
3801/// Completes the merge of two function declarations that are
3802/// known to be compatible.
3803///
3804/// This routine handles the merging of attributes and other
3805/// properties of function declarations from the old declaration to
3806/// the new declaration, once we know that New is in fact a
3807/// redeclaration of Old.
3808///
3809/// \returns false
3810bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3811 Scope *S, bool MergeTypeWithOld) {
3812 // Merge the attributes
3813 mergeDeclAttributes(New, Old);
3814
3815 // Merge "pure" flag.
3816 if (Old->isPure())
3817 New->setPure();
3818
3819 // Merge "used" flag.
3820 if (Old->getMostRecentDecl()->isUsed(false))
3821 New->setIsUsed();
3822
3823 // Merge attributes from the parameters. These can mismatch with K&R
3824 // declarations.
3825 if (New->getNumParams() == Old->getNumParams())
3826 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3827 ParmVarDecl *NewParam = New->getParamDecl(i);
3828 ParmVarDecl *OldParam = Old->getParamDecl(i);
3829 mergeParamDeclAttributes(NewParam, OldParam, *this);
3830 mergeParamDeclTypes(NewParam, OldParam, *this);
3831 }
3832
3833 if (getLangOpts().CPlusPlus)
3834 return MergeCXXFunctionDecl(New, Old, S);
3835
3836 // Merge the function types so the we get the composite types for the return
3837 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3838 // was visible.
3839 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3840 if (!Merged.isNull() && MergeTypeWithOld)
3841 New->setType(Merged);
3842
3843 return false;
3844}
3845
3846void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3847 ObjCMethodDecl *oldMethod) {
3848 // Merge the attributes, including deprecated/unavailable
3849 AvailabilityMergeKind MergeKind =
3850 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3851 ? AMK_ProtocolImplementation
3852 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3853 : AMK_Override;
3854
3855 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3856
3857 // Merge attributes from the parameters.
3858 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3859 oe = oldMethod->param_end();
3860 for (ObjCMethodDecl::param_iterator
3861 ni = newMethod->param_begin(), ne = newMethod->param_end();
3862 ni != ne && oi != oe; ++ni, ++oi)
3863 mergeParamDeclAttributes(*ni, *oi, *this);
3864
3865 CheckObjCMethodOverride(newMethod, oldMethod);
3866}
3867
3868static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3869 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 3869, __PRETTY_FUNCTION__))
;
3870
3871 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3872 ? diag::err_redefinition_different_type
3873 : diag::err_redeclaration_different_type)
3874 << New->getDeclName() << New->getType() << Old->getType();
3875
3876 diag::kind PrevDiag;
3877 SourceLocation OldLocation;
3878 std::tie(PrevDiag, OldLocation)
3879 = getNoteDiagForInvalidRedeclaration(Old, New);
3880 S.Diag(OldLocation, PrevDiag);
3881 New->setInvalidDecl();
3882}
3883
3884/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3885/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3886/// emitting diagnostics as appropriate.
3887///
3888/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3889/// to here in AddInitializerToDecl. We can't check them before the initializer
3890/// is attached.
3891void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3892 bool MergeTypeWithOld) {
3893 if (New->isInvalidDecl() || Old->isInvalidDecl())
3894 return;
3895
3896 QualType MergedT;
3897 if (getLangOpts().CPlusPlus) {
3898 if (New->getType()->isUndeducedType()) {
3899 // We don't know what the new type is until the initializer is attached.
3900 return;
3901 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3902 // These could still be something that needs exception specs checked.
3903 return MergeVarDeclExceptionSpecs(New, Old);
3904 }
3905 // C++ [basic.link]p10:
3906 // [...] the types specified by all declarations referring to a given
3907 // object or function shall be identical, except that declarations for an
3908 // array object can specify array types that differ by the presence or
3909 // absence of a major array bound (8.3.4).
3910 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3911 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3912 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3913
3914 // We are merging a variable declaration New into Old. If it has an array
3915 // bound, and that bound differs from Old's bound, we should diagnose the
3916 // mismatch.
3917 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3918 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3919 PrevVD = PrevVD->getPreviousDecl()) {
3920 QualType PrevVDTy = PrevVD->getType();
3921 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3922 continue;
3923
3924 if (!Context.hasSameType(New->getType(), PrevVDTy))
3925 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3926 }
3927 }
3928
3929 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3930 if (Context.hasSameType(OldArray->getElementType(),
3931 NewArray->getElementType()))
3932 MergedT = New->getType();
3933 }
3934 // FIXME: Check visibility. New is hidden but has a complete type. If New
3935 // has no array bound, it should not inherit one from Old, if Old is not
3936 // visible.
3937 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3938 if (Context.hasSameType(OldArray->getElementType(),
3939 NewArray->getElementType()))
3940 MergedT = Old->getType();
3941 }
3942 }
3943 else if (New->getType()->isObjCObjectPointerType() &&
3944 Old->getType()->isObjCObjectPointerType()) {
3945 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3946 Old->getType());
3947 }
3948 } else {
3949 // C 6.2.7p2:
3950 // All declarations that refer to the same object or function shall have
3951 // compatible type.
3952 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3953 }
3954 if (MergedT.isNull()) {
3955 // It's OK if we couldn't merge types if either type is dependent, for a
3956 // block-scope variable. In other cases (static data members of class
3957 // templates, variable templates, ...), we require the types to be
3958 // equivalent.
3959 // FIXME: The C++ standard doesn't say anything about this.
3960 if ((New->getType()->isDependentType() ||
3961 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3962 // If the old type was dependent, we can't merge with it, so the new type
3963 // becomes dependent for now. We'll reproduce the original type when we
3964 // instantiate the TypeSourceInfo for the variable.
3965 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3966 New->setType(Context.DependentTy);
3967 return;
3968 }
3969 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3970 }
3971
3972 // Don't actually update the type on the new declaration if the old
3973 // declaration was an extern declaration in a different scope.
3974 if (MergeTypeWithOld)
3975 New->setType(MergedT);
3976}
3977
3978static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3979 LookupResult &Previous) {
3980 // C11 6.2.7p4:
3981 // For an identifier with internal or external linkage declared
3982 // in a scope in which a prior declaration of that identifier is
3983 // visible, if the prior declaration specifies internal or
3984 // external linkage, the type of the identifier at the later
3985 // declaration becomes the composite type.
3986 //
3987 // If the variable isn't visible, we do not merge with its type.
3988 if (Previous.isShadowed())
3989 return false;
3990
3991 if (S.getLangOpts().CPlusPlus) {
3992 // C++11 [dcl.array]p3:
3993 // If there is a preceding declaration of the entity in the same
3994 // scope in which the bound was specified, an omitted array bound
3995 // is taken to be the same as in that earlier declaration.
3996 return NewVD->isPreviousDeclInSameBlockScope() ||
3997 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3998 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3999 } else {
4000 // If the old declaration was function-local, don't merge with its
4001 // type unless we're in the same function.
4002 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4003 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4004 }
4005}
4006
4007/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4008/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4009/// situation, merging decls or emitting diagnostics as appropriate.
4010///
4011/// Tentative definition rules (C99 6.9.2p2) are checked by
4012/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4013/// definitions here, since the initializer hasn't been attached.
4014///
4015void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4016 // If the new decl is already invalid, don't do any other checking.
4017 if (New->isInvalidDecl())
4018 return;
4019
4020 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4021 return;
4022
4023 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4024
4025 // Verify the old decl was also a variable or variable template.
4026 VarDecl *Old = nullptr;
4027 VarTemplateDecl *OldTemplate = nullptr;
4028 if (Previous.isSingleResult()) {
4029 if (NewTemplate) {
4030 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4031 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4032
4033 if (auto *Shadow =
4034 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4035 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4036 return New->setInvalidDecl();
4037 } else {
4038 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4039
4040 if (auto *Shadow =
4041 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4042 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4043 return New->setInvalidDecl();
4044 }
4045 }
4046 if (!Old) {
4047 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4048 << New->getDeclName();
4049 notePreviousDefinition(Previous.getRepresentativeDecl(),
4050 New->getLocation());
4051 return New->setInvalidDecl();
4052 }
4053
4054 // Ensure the template parameters are compatible.
4055 if (NewTemplate &&
4056 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4057 OldTemplate->getTemplateParameters(),
4058 /*Complain=*/true, TPL_TemplateMatch))
4059 return New->setInvalidDecl();
4060
4061 // C++ [class.mem]p1:
4062 // A member shall not be declared twice in the member-specification [...]
4063 //
4064 // Here, we need only consider static data members.
4065 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4066 Diag(New->getLocation(), diag::err_duplicate_member)
4067 << New->getIdentifier();
4068 Diag(Old->getLocation(), diag::note_previous_declaration);
4069 New->setInvalidDecl();
4070 }
4071
4072 mergeDeclAttributes(New, Old);
4073 // Warn if an already-declared variable is made a weak_import in a subsequent
4074 // declaration
4075 if (New->hasAttr<WeakImportAttr>() &&
4076 Old->getStorageClass() == SC_None &&
4077 !Old->hasAttr<WeakImportAttr>()) {
4078 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4079 notePreviousDefinition(Old, New->getLocation());
4080 // Remove weak_import attribute on new declaration.
4081 New->dropAttr<WeakImportAttr>();
4082 }
4083
4084 if (New->hasAttr<InternalLinkageAttr>() &&
4085 !Old->hasAttr<InternalLinkageAttr>()) {
4086 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4087 << New->getDeclName();
4088 notePreviousDefinition(Old, New->getLocation());
4089 New->dropAttr<InternalLinkageAttr>();
4090 }
4091
4092 // Merge the types.
4093 VarDecl *MostRecent = Old->getMostRecentDecl();
4094 if (MostRecent != Old) {
4095 MergeVarDeclTypes(New, MostRecent,
4096 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4097 if (New->isInvalidDecl())
4098 return;
4099 }
4100
4101 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4102 if (New->isInvalidDecl())
4103 return;
4104
4105 diag::kind PrevDiag;
4106 SourceLocation OldLocation;
4107 std::tie(PrevDiag, OldLocation) =
4108 getNoteDiagForInvalidRedeclaration(Old, New);
4109
4110 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4111 if (New->getStorageClass() == SC_Static &&
4112 !New->isStaticDataMember() &&
4113 Old->hasExternalFormalLinkage()) {
4114 if (getLangOpts().MicrosoftExt) {
4115 Diag(New->getLocation(), diag::ext_static_non_static)
4116 << New->getDeclName();
4117 Diag(OldLocation, PrevDiag);
4118 } else {
4119 Diag(New->getLocation(), diag::err_static_non_static)
4120 << New->getDeclName();
4121 Diag(OldLocation, PrevDiag);
4122 return New->setInvalidDecl();
4123 }
4124 }
4125 // C99 6.2.2p4:
4126 // For an identifier declared with the storage-class specifier
4127 // extern in a scope in which a prior declaration of that
4128 // identifier is visible,23) if the prior declaration specifies
4129 // internal or external linkage, the linkage of the identifier at
4130 // the later declaration is the same as the linkage specified at
4131 // the prior declaration. If no prior declaration is visible, or
4132 // if the prior declaration specifies no linkage, then the
4133 // identifier has external linkage.
4134 if (New->hasExternalStorage() && Old->hasLinkage())
4135 /* Okay */;
4136 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4137 !New->isStaticDataMember() &&
4138 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4139 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4140 Diag(OldLocation, PrevDiag);
4141 return New->setInvalidDecl();
4142 }
4143
4144 // Check if extern is followed by non-extern and vice-versa.
4145 if (New->hasExternalStorage() &&
4146 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4147 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4148 Diag(OldLocation, PrevDiag);
4149 return New->setInvalidDecl();
4150 }
4151 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4152 !New->hasExternalStorage()) {
4153 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4154 Diag(OldLocation, PrevDiag);
4155 return New->setInvalidDecl();
4156 }
4157
4158 if (CheckRedeclarationModuleOwnership(New, Old))
4159 return;
4160
4161 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4162
4163 // FIXME: The test for external storage here seems wrong? We still
4164 // need to check for mismatches.
4165 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4166 // Don't complain about out-of-line definitions of static members.
4167 !(Old->getLexicalDeclContext()->isRecord() &&
4168 !New->getLexicalDeclContext()->isRecord())) {
4169 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4170 Diag(OldLocation, PrevDiag);
4171 return New->setInvalidDecl();
4172 }
4173
4174 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4175 if (VarDecl *Def = Old->getDefinition()) {
4176 // C++1z [dcl.fcn.spec]p4:
4177 // If the definition of a variable appears in a translation unit before
4178 // its first declaration as inline, the program is ill-formed.
4179 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4180 Diag(Def->getLocation(), diag::note_previous_definition);
4181 }
4182 }
4183
4184 // If this redeclaration makes the variable inline, we may need to add it to
4185 // UndefinedButUsed.
4186 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4187 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4188 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4189 SourceLocation()));
4190
4191 if (New->getTLSKind() != Old->getTLSKind()) {
4192 if (!Old->getTLSKind()) {
4193 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4194 Diag(OldLocation, PrevDiag);
4195 } else if (!New->getTLSKind()) {
4196 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4197 Diag(OldLocation, PrevDiag);
4198 } else {
4199 // Do not allow redeclaration to change the variable between requiring
4200 // static and dynamic initialization.
4201 // FIXME: GCC allows this, but uses the TLS keyword on the first
4202 // declaration to determine the kind. Do we need to be compatible here?
4203 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4204 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4205 Diag(OldLocation, PrevDiag);
4206 }
4207 }
4208
4209 // C++ doesn't have tentative definitions, so go right ahead and check here.
4210 if (getLangOpts().CPlusPlus &&
4211 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4212 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4213 Old->getCanonicalDecl()->isConstexpr()) {
4214 // This definition won't be a definition any more once it's been merged.
4215 Diag(New->getLocation(),
4216 diag::warn_deprecated_redundant_constexpr_static_def);
4217 } else if (VarDecl *Def = Old->getDefinition()) {
4218 if (checkVarDeclRedefinition(Def, New))
4219 return;
4220 }
4221 }
4222
4223 if (haveIncompatibleLanguageLinkages(Old, New)) {
4224 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4225 Diag(OldLocation, PrevDiag);
4226 New->setInvalidDecl();
4227 return;
4228 }
4229
4230 // Merge "used" flag.
4231 if (Old->getMostRecentDecl()->isUsed(false))
4232 New->setIsUsed();
4233
4234 // Keep a chain of previous declarations.
4235 New->setPreviousDecl(Old);
4236 if (NewTemplate)
4237 NewTemplate->setPreviousDecl(OldTemplate);
4238 adjustDeclContextForDeclaratorDecl(New, Old);
4239
4240 // Inherit access appropriately.
4241 New->setAccess(Old->getAccess());
4242 if (NewTemplate)
4243 NewTemplate->setAccess(New->getAccess());
4244
4245 if (Old->isInline())
4246 New->setImplicitlyInline();
4247}
4248
4249void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4250 SourceManager &SrcMgr = getSourceManager();
4251 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4252 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4253 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4254 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4255 auto &HSI = PP.getHeaderSearchInfo();
4256 StringRef HdrFilename =
4257 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4258
4259 auto noteFromModuleOrInclude = [&](Module *Mod,
4260 SourceLocation IncLoc) -> bool {
4261 // Redefinition errors with modules are common with non modular mapped
4262 // headers, example: a non-modular header H in module A that also gets
4263 // included directly in a TU. Pointing twice to the same header/definition
4264 // is confusing, try to get better diagnostics when modules is on.
4265 if (IncLoc.isValid()) {
4266 if (Mod) {
4267 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4268 << HdrFilename.str() << Mod->getFullModuleName();
4269 if (!Mod->DefinitionLoc.isInvalid())
4270 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4271 << Mod->getFullModuleName();
4272 } else {
4273 Diag(IncLoc, diag::note_redefinition_include_same_file)
4274 << HdrFilename.str();
4275 }
4276 return true;
4277 }
4278
4279 return false;
4280 };
4281
4282 // Is it the same file and same offset? Provide more information on why
4283 // this leads to a redefinition error.
4284 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4285 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4286 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4287 bool EmittedDiag =
4288 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4289 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4290
4291 // If the header has no guards, emit a note suggesting one.
4292 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4293 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4294
4295 if (EmittedDiag)
4296 return;
4297 }
4298
4299 // Redefinition coming from different files or couldn't do better above.
4300 if (Old->getLocation().isValid())
4301 Diag(Old->getLocation(), diag::note_previous_definition);
4302}
4303
4304/// We've just determined that \p Old and \p New both appear to be definitions
4305/// of the same variable. Either diagnose or fix the problem.
4306bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4307 if (!hasVisibleDefinition(Old) &&
4308 (New->getFormalLinkage() == InternalLinkage ||
4309 New->isInline() ||
4310 New->getDescribedVarTemplate() ||
4311 New->getNumTemplateParameterLists() ||
4312 New->getDeclContext()->isDependentContext())) {
4313 // The previous definition is hidden, and multiple definitions are
4314 // permitted (in separate TUs). Demote this to a declaration.
4315 New->demoteThisDefinitionToDeclaration();
4316
4317 // Make the canonical definition visible.
4318 if (auto *OldTD = Old->getDescribedVarTemplate())
4319 makeMergedDefinitionVisible(OldTD);
4320 makeMergedDefinitionVisible(Old);
4321 return false;
4322 } else {
4323 Diag(New->getLocation(), diag::err_redefinition) << New;
4324 notePreviousDefinition(Old, New->getLocation());
4325 New->setInvalidDecl();
4326 return true;
4327 }
4328}
4329
4330/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4331/// no declarator (e.g. "struct foo;") is parsed.
4332Decl *
4333Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4334 RecordDecl *&AnonRecord) {
4335 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4336 AnonRecord);
4337}
4338
4339// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4340// disambiguate entities defined in different scopes.
4341// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4342// compatibility.
4343// We will pick our mangling number depending on which version of MSVC is being
4344// targeted.
4345static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4346 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4347 ? S->getMSCurManglingNumber()
4348 : S->getMSLastManglingNumber();
4349}
4350
4351void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4352 if (!Context.getLangOpts().CPlusPlus)
4353 return;
4354
4355 if (isa<CXXRecordDecl>(Tag->getParent())) {
4356 // If this tag is the direct child of a class, number it if
4357 // it is anonymous.
4358 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4359 return;
4360 MangleNumberingContext &MCtx =
4361 Context.getManglingNumberContext(Tag->getParent());
4362 Context.setManglingNumber(
4363 Tag, MCtx.getManglingNumber(
4364 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4365 return;
4366 }
4367
4368 // If this tag isn't a direct child of a class, number it if it is local.
4369 MangleNumberingContext *MCtx;
4370 Decl *ManglingContextDecl;
4371 std::tie(MCtx, ManglingContextDecl) =
4372 getCurrentMangleNumberContext(Tag->getDeclContext());
4373 if (MCtx) {
4374 Context.setManglingNumber(
4375 Tag, MCtx->getManglingNumber(
4376 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4377 }
4378}
4379
4380namespace {
4381struct NonCLikeKind {
4382 enum {
4383 None,
4384 BaseClass,
4385 DefaultMemberInit,
4386 Lambda,
4387 Friend,
4388 OtherMember,
4389 Invalid,
4390 } Kind = None;
4391 SourceRange Range;
4392
4393 explicit operator bool() { return Kind != None; }
4394};
4395}
4396
4397/// Determine whether a class is C-like, according to the rules of C++
4398/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4399static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4400 if (RD->isInvalidDecl())
4401 return {NonCLikeKind::Invalid, {}};
4402
4403 // C++ [dcl.typedef]p9: [P1766R1]
4404 // An unnamed class with a typedef name for linkage purposes shall not
4405 //
4406 // -- have any base classes
4407 if (RD->getNumBases())
4408 return {NonCLikeKind::BaseClass,
4409 SourceRange(RD->bases_begin()->getBeginLoc(),
4410 RD->bases_end()[-1].getEndLoc())};
4411 bool Invalid = false;
4412 for (Decl *D : RD->decls()) {
4413 // Don't complain about things we already diagnosed.
4414 if (D->isInvalidDecl()) {
4415 Invalid = true;
4416 continue;
4417 }
4418
4419 // -- have any [...] default member initializers
4420 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4421 if (FD->hasInClassInitializer()) {
4422 auto *Init = FD->getInClassInitializer();
4423 return {NonCLikeKind::DefaultMemberInit,
4424 Init ? Init->getSourceRange() : D->getSourceRange()};
4425 }
4426 continue;
4427 }
4428
4429 // FIXME: We don't allow friend declarations. This violates the wording of
4430 // P1766, but not the intent.
4431 if (isa<FriendDecl>(D))
4432 return {NonCLikeKind::Friend, D->getSourceRange()};
4433
4434 // -- declare any members other than non-static data members, member
4435 // enumerations, or member classes,
4436 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4437 isa<EnumDecl>(D))
4438 continue;
4439 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4440 if (!MemberRD) {
4441 if (D->isImplicit())
4442 continue;
4443 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4444 }
4445
4446 // -- contain a lambda-expression,
4447 if (MemberRD->isLambda())
4448 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4449
4450 // and all member classes shall also satisfy these requirements
4451 // (recursively).
4452 if (MemberRD->isThisDeclarationADefinition()) {
4453 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4454 return Kind;
4455 }
4456 }
4457
4458 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4459}
4460
4461void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4462 TypedefNameDecl *NewTD) {
4463 if (TagFromDeclSpec->isInvalidDecl())
4464 return;
4465
4466 // Do nothing if the tag already has a name for linkage purposes.
4467 if (TagFromDeclSpec->hasNameForLinkage())
4468 return;
4469
4470 // A well-formed anonymous tag must always be a TUK_Definition.
4471 assert(TagFromDeclSpec->isThisDeclarationADefinition())((TagFromDeclSpec->isThisDeclarationADefinition()) ? static_cast
<void> (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4471, __PRETTY_FUNCTION__))
;
4472
4473 // The type must match the tag exactly; no qualifiers allowed.
4474 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4475 Context.getTagDeclType(TagFromDeclSpec))) {
4476 if (getLangOpts().CPlusPlus)
4477 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4478 return;
4479 }
4480
4481 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4482 // An unnamed class with a typedef name for linkage purposes shall [be
4483 // C-like].
4484 //
4485 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4486 // shouldn't happen, but there are constructs that the language rule doesn't
4487 // disallow for which we can't reasonably avoid computing linkage early.
4488 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4489 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4490 : NonCLikeKind();
4491 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4492 if (NonCLike || ChangesLinkage) {
4493 if (NonCLike.Kind == NonCLikeKind::Invalid)
4494 return;
4495
4496 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4497 if (ChangesLinkage) {
4498 // If the linkage changes, we can't accept this as an extension.
4499 if (NonCLike.Kind == NonCLikeKind::None)
4500 DiagID = diag::err_typedef_changes_linkage;
4501 else
4502 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4503 }
4504
4505 SourceLocation FixitLoc =
4506 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4507 llvm::SmallString<40> TextToInsert;
4508 TextToInsert += ' ';
4509 TextToInsert += NewTD->getIdentifier()->getName();
4510
4511 Diag(FixitLoc, DiagID)
4512 << isa<TypeAliasDecl>(NewTD)
4513 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4514 if (NonCLike.Kind != NonCLikeKind::None) {
4515 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4516 << NonCLike.Kind - 1 << NonCLike.Range;
4517 }
4518 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4519 << NewTD << isa<TypeAliasDecl>(NewTD);
4520
4521 if (ChangesLinkage)
4522 return;
4523 }
4524
4525 // Otherwise, set this as the anon-decl typedef for the tag.
4526 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4527}
4528
4529static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4530 switch (T) {
4531 case DeclSpec::TST_class:
4532 return 0;
4533 case DeclSpec::TST_struct:
4534 return 1;
4535 case DeclSpec::TST_interface:
4536 return 2;
4537 case DeclSpec::TST_union:
4538 return 3;
4539 case DeclSpec::TST_enum:
4540 return 4;
4541 default:
4542 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4542)
;
4543 }
4544}
4545
4546/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4547/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4548/// parameters to cope with template friend declarations.
4549Decl *
4550Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4551 MultiTemplateParamsArg TemplateParams,
4552 bool IsExplicitInstantiation,
4553 RecordDecl *&AnonRecord) {
4554 Decl *TagD = nullptr;
4555 TagDecl *Tag = nullptr;
4556 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4557 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4558 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4559 DS.getTypeSpecType() == DeclSpec::TST_union ||
4560 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4561 TagD = DS.getRepAsDecl();
4562
4563 if (!TagD) // We probably had an error
4564 return nullptr;
4565
4566 // Note that the above type specs guarantee that the
4567 // type rep is a Decl, whereas in many of the others
4568 // it's a Type.
4569 if (isa<TagDecl>(TagD))
4570 Tag = cast<TagDecl>(TagD);
4571 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4572 Tag = CTD->getTemplatedDecl();
4573 }
4574
4575 if (Tag) {
4576 handleTagNumbering(Tag, S);
4577 Tag->setFreeStanding();
4578 if (Tag->isInvalidDecl())
4579 return Tag;
4580 }
4581
4582 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4583 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4584 // or incomplete types shall not be restrict-qualified."
4585 if (TypeQuals & DeclSpec::TQ_restrict)
4586 Diag(DS.getRestrictSpecLoc(),
4587 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4588 << DS.getSourceRange();
4589 }
4590
4591 if (DS.isInlineSpecified())
4592 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4593 << getLangOpts().CPlusPlus17;
4594
4595 if (DS.hasConstexprSpecifier()) {
4596 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4597 // and definitions of functions and variables.
4598 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4599 // the declaration of a function or function template
4600 if (Tag)
4601 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4602 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4603 << DS.getConstexprSpecifier();
4604 else
4605 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4606 << DS.getConstexprSpecifier();
4607 // Don't emit warnings after this error.
4608 return TagD;
4609 }
4610
4611 DiagnoseFunctionSpecifiers(DS);
4612
4613 if (DS.isFriendSpecified()) {
4614 // If we're dealing with a decl but not a TagDecl, assume that
4615 // whatever routines created it handled the friendship aspect.
4616 if (TagD && !Tag)
4617 return nullptr;
4618 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4619 }
4620
4621 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4622 bool IsExplicitSpecialization =
4623 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4624 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4625 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4626 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4627 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4628 // nested-name-specifier unless it is an explicit instantiation
4629 // or an explicit specialization.
4630 //
4631 // FIXME: We allow class template partial specializations here too, per the
4632 // obvious intent of DR1819.
4633 //
4634 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4635 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4636 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4637 return nullptr;
4638 }
4639
4640 // Track whether this decl-specifier declares anything.
4641 bool DeclaresAnything = true;
4642
4643 // Handle anonymous struct definitions.
4644 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4645 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4646 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4647 if (getLangOpts().CPlusPlus ||
4648 Record->getDeclContext()->isRecord()) {
4649 // If CurContext is a DeclContext that can contain statements,
4650 // RecursiveASTVisitor won't visit the decls that
4651 // BuildAnonymousStructOrUnion() will put into CurContext.
4652 // Also store them here so that they can be part of the
4653 // DeclStmt that gets created in this case.
4654 // FIXME: Also return the IndirectFieldDecls created by
4655 // BuildAnonymousStructOr union, for the same reason?
4656 if (CurContext->isFunctionOrMethod())
4657 AnonRecord = Record;
4658 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4659 Context.getPrintingPolicy());
4660 }
4661
4662 DeclaresAnything = false;
4663 }
4664 }
4665
4666 // C11 6.7.2.1p2:
4667 // A struct-declaration that does not declare an anonymous structure or
4668 // anonymous union shall contain a struct-declarator-list.
4669 //
4670 // This rule also existed in C89 and C99; the grammar for struct-declaration
4671 // did not permit a struct-declaration without a struct-declarator-list.
4672 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4673 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4674 // Check for Microsoft C extension: anonymous struct/union member.
4675 // Handle 2 kinds of anonymous struct/union:
4676 // struct STRUCT;
4677 // union UNION;
4678 // and
4679 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4680 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4681 if ((Tag && Tag->getDeclName()) ||
4682 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4683 RecordDecl *Record = nullptr;
4684 if (Tag)
4685 Record = dyn_cast<RecordDecl>(Tag);
4686 else if (const RecordType *RT =
4687 DS.getRepAsType().get()->getAsStructureType())
4688 Record = RT->getDecl();
4689 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4690 Record = UT->getDecl();
4691
4692 if (Record && getLangOpts().MicrosoftExt) {
4693 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4694 << Record->isUnion() << DS.getSourceRange();
4695 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4696 }
4697
4698 DeclaresAnything = false;
4699 }
4700 }
4701
4702 // Skip all the checks below if we have a type error.
4703 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4704 (TagD && TagD->isInvalidDecl()))
4705 return TagD;
4706
4707 if (getLangOpts().CPlusPlus &&
4708 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4709 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4710 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4711 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4712 DeclaresAnything = false;
4713
4714 if (!DS.isMissingDeclaratorOk()) {
4715 // Customize diagnostic for a typedef missing a name.
4716 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4717 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4718 << DS.getSourceRange();
4719 else
4720 DeclaresAnything = false;
4721 }
4722
4723 if (DS.isModulePrivateSpecified() &&
4724 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4725 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4726 << Tag->getTagKind()
4727 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4728
4729 ActOnDocumentableDecl(TagD);
4730
4731 // C 6.7/2:
4732 // A declaration [...] shall declare at least a declarator [...], a tag,
4733 // or the members of an enumeration.
4734 // C++ [dcl.dcl]p3:
4735 // [If there are no declarators], and except for the declaration of an
4736 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4737 // names into the program, or shall redeclare a name introduced by a
4738 // previous declaration.
4739 if (!DeclaresAnything) {
4740 // In C, we allow this as a (popular) extension / bug. Don't bother
4741 // producing further diagnostics for redundant qualifiers after this.
4742 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4743 ? diag::err_no_declarators
4744 : diag::ext_no_declarators)
4745 << DS.getSourceRange();
4746 return TagD;
4747 }
4748
4749 // C++ [dcl.stc]p1:
4750 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4751 // init-declarator-list of the declaration shall not be empty.
4752 // C++ [dcl.fct.spec]p1:
4753 // If a cv-qualifier appears in a decl-specifier-seq, the
4754 // init-declarator-list of the declaration shall not be empty.
4755 //
4756 // Spurious qualifiers here appear to be valid in C.
4757 unsigned DiagID = diag::warn_standalone_specifier;
4758 if (getLangOpts().CPlusPlus)
4759 DiagID = diag::ext_standalone_specifier;
4760
4761 // Note that a linkage-specification sets a storage class, but
4762 // 'extern "C" struct foo;' is actually valid and not theoretically
4763 // useless.
4764 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4765 if (SCS == DeclSpec::SCS_mutable)
4766 // Since mutable is not a viable storage class specifier in C, there is
4767 // no reason to treat it as an extension. Instead, diagnose as an error.
4768 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4769 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4770 Diag(DS.getStorageClassSpecLoc(), DiagID)
4771 << DeclSpec::getSpecifierName(SCS);
4772 }
4773
4774 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4775 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4776 << DeclSpec::getSpecifierName(TSCS);
4777 if (DS.getTypeQualifiers()) {
4778 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4779 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4780 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4781 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4782 // Restrict is covered above.
4783 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4784 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4785 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4786 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4787 }
4788
4789 // Warn about ignored type attributes, for example:
4790 // __attribute__((aligned)) struct A;
4791 // Attributes should be placed after tag to apply to type declaration.
4792 if (!DS.getAttributes().empty()) {
4793 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4794 if (TypeSpecType == DeclSpec::TST_class ||
4795 TypeSpecType == DeclSpec::TST_struct ||
4796 TypeSpecType == DeclSpec::TST_interface ||
4797 TypeSpecType == DeclSpec::TST_union ||
4798 TypeSpecType == DeclSpec::TST_enum) {
4799 for (const ParsedAttr &AL : DS.getAttributes())
4800 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4801 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4802 }
4803 }
4804
4805 return TagD;
4806}
4807
4808/// We are trying to inject an anonymous member into the given scope;
4809/// check if there's an existing declaration that can't be overloaded.
4810///
4811/// \return true if this is a forbidden redeclaration
4812static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4813 Scope *S,
4814 DeclContext *Owner,
4815 DeclarationName Name,
4816 SourceLocation NameLoc,
4817 bool IsUnion) {
4818 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4819 Sema::ForVisibleRedeclaration);
4820 if (!SemaRef.LookupName(R, S)) return false;
4821
4822 // Pick a representative declaration.
4823 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4824 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4824, __PRETTY_FUNCTION__))
;
4825
4826 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4827 return false;
4828
4829 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4830 << IsUnion << Name;
4831 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4832
4833 return true;
4834}
4835
4836/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4837/// anonymous struct or union AnonRecord into the owning context Owner
4838/// and scope S. This routine will be invoked just after we realize
4839/// that an unnamed union or struct is actually an anonymous union or
4840/// struct, e.g.,
4841///
4842/// @code
4843/// union {
4844/// int i;
4845/// float f;
4846/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4847/// // f into the surrounding scope.x
4848/// @endcode
4849///
4850/// This routine is recursive, injecting the names of nested anonymous
4851/// structs/unions into the owning context and scope as well.
4852static bool
4853InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4854 RecordDecl *AnonRecord, AccessSpecifier AS,
4855 SmallVectorImpl<NamedDecl *> &Chaining) {
4856 bool Invalid = false;
4857
4858 // Look every FieldDecl and IndirectFieldDecl with a name.
4859 for (auto *D : AnonRecord->decls()) {
4860 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4861 cast<NamedDecl>(D)->getDeclName()) {
4862 ValueDecl *VD = cast<ValueDecl>(D);
4863 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4864 VD->getLocation(),
4865 AnonRecord->isUnion())) {
4866 // C++ [class.union]p2:
4867 // The names of the members of an anonymous union shall be
4868 // distinct from the names of any other entity in the
4869 // scope in which the anonymous union is declared.
4870 Invalid = true;
4871 } else {
4872 // C++ [class.union]p2:
4873 // For the purpose of name lookup, after the anonymous union
4874 // definition, the members of the anonymous union are
4875 // considered to have been defined in the scope in which the
4876 // anonymous union is declared.
4877 unsigned OldChainingSize = Chaining.size();
4878 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4879 Chaining.append(IF->chain_begin(), IF->chain_end());
4880 else
4881 Chaining.push_back(VD);
4882
4883 assert(Chaining.size() >= 2)((Chaining.size() >= 2) ? static_cast<void> (0) : __assert_fail
("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4883, __PRETTY_FUNCTION__))
;
4884 NamedDecl **NamedChain =
4885 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4886 for (unsigned i = 0; i < Chaining.size(); i++)
4887 NamedChain[i] = Chaining[i];
4888
4889 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4890 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4891 VD->getType(), {NamedChain, Chaining.size()});
4892
4893 for (const auto *Attr : VD->attrs())
4894 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4895
4896 IndirectField->setAccess(AS);
4897 IndirectField->setImplicit();
4898 SemaRef.PushOnScopeChains(IndirectField, S);
4899
4900 // That includes picking up the appropriate access specifier.
4901 if (AS != AS_none) IndirectField->setAccess(AS);
4902
4903 Chaining.resize(OldChainingSize);
4904 }
4905 }
4906 }
4907
4908 return Invalid;
4909}
4910
4911/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4912/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4913/// illegal input values are mapped to SC_None.
4914static StorageClass
4915StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4916 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4917 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4918, __PRETTY_FUNCTION__))
4918 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4918, __PRETTY_FUNCTION__))
;
4919 switch (StorageClassSpec) {
4920 case DeclSpec::SCS_unspecified: return SC_None;
4921 case DeclSpec::SCS_extern:
4922 if (DS.isExternInLinkageSpec())
4923 return SC_None;
4924 return SC_Extern;
4925 case DeclSpec::SCS_static: return SC_Static;
4926 case DeclSpec::SCS_auto: return SC_Auto;
4927 case DeclSpec::SCS_register: return SC_Register;
4928 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4929 // Illegal SCSs map to None: error reporting is up to the caller.
4930 case DeclSpec::SCS_mutable: // Fall through.
4931 case DeclSpec::SCS_typedef: return SC_None;
4932 }
4933 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4933)
;
4934}
4935
4936static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4937 assert(Record->hasInClassInitializer())((Record->hasInClassInitializer()) ? static_cast<void>
(0) : __assert_fail ("Record->hasInClassInitializer()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4937, __PRETTY_FUNCTION__))
;
4938
4939 for (const auto *I : Record->decls()) {
4940 const auto *FD = dyn_cast<FieldDecl>(I);
4941 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4942 FD = IFD->getAnonField();
4943 if (FD && FD->hasInClassInitializer())
4944 return FD->getLocation();
4945 }
4946
4947 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 4947)
;
4948}
4949
4950static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4951 SourceLocation DefaultInitLoc) {
4952 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4953 return;
4954
4955 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4956 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4957}
4958
4959static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4960 CXXRecordDecl *AnonUnion) {
4961 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4962 return;
4963
4964 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4965}
4966
4967/// BuildAnonymousStructOrUnion - Handle the declaration of an
4968/// anonymous structure or union. Anonymous unions are a C++ feature
4969/// (C++ [class.union]) and a C11 feature; anonymous structures
4970/// are a C11 feature and GNU C++ extension.
4971Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4972 AccessSpecifier AS,
4973 RecordDecl *Record,
4974 const PrintingPolicy &Policy) {
4975 DeclContext *Owner = Record->getDeclContext();
4976
4977 // Diagnose whether this anonymous struct/union is an extension.
4978 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4979 Diag(Record->getLocation(), diag::ext_anonymous_union);
4980 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4981 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4982 else if (!Record->isUnion() && !getLangOpts().C11)
4983 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4984
4985 // C and C++ require different kinds of checks for anonymous
4986 // structs/unions.
4987 bool Invalid = false;
4988 if (getLangOpts().CPlusPlus) {
4989 const char *PrevSpec = nullptr;
4990 if (Record->isUnion()) {
4991 // C++ [class.union]p6:
4992 // C++17 [class.union.anon]p2:
4993 // Anonymous unions declared in a named namespace or in the
4994 // global namespace shall be declared static.
4995 unsigned DiagID;
4996 DeclContext *OwnerScope = Owner->getRedeclContext();
4997 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4998 (OwnerScope->isTranslationUnit() ||
4999 (OwnerScope->isNamespace() &&
5000 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5001 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5002 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5003
5004 // Recover by adding 'static'.
5005 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5006 PrevSpec, DiagID, Policy);
5007 }
5008 // C++ [class.union]p6:
5009 // A storage class is not allowed in a declaration of an
5010 // anonymous union in a class scope.
5011 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5012 isa<RecordDecl>(Owner)) {
5013 Diag(DS.getStorageClassSpecLoc(),
5014 diag::err_anonymous_union_with_storage_spec)
5015 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5016
5017 // Recover by removing the storage specifier.
5018 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5019 SourceLocation(),
5020 PrevSpec, DiagID, Context.getPrintingPolicy());
5021 }
5022 }
5023
5024 // Ignore const/volatile/restrict qualifiers.
5025 if (DS.getTypeQualifiers()) {
5026 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5027 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5028 << Record->isUnion() << "const"
5029 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5030 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5031 Diag(DS.getVolatileSpecLoc(),
5032 diag::ext_anonymous_struct_union_qualified)
5033 << Record->isUnion() << "volatile"
5034 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5035 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5036 Diag(DS.getRestrictSpecLoc(),
5037 diag::ext_anonymous_struct_union_qualified)
5038 << Record->isUnion() << "restrict"
5039 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5040 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5041 Diag(DS.getAtomicSpecLoc(),
5042 diag::ext_anonymous_struct_union_qualified)
5043 << Record->isUnion() << "_Atomic"
5044 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5045 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5046 Diag(DS.getUnalignedSpecLoc(),
5047 diag::ext_anonymous_struct_union_qualified)
5048 << Record->isUnion() << "__unaligned"
5049 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5050
5051 DS.ClearTypeQualifiers();
5052 }
5053
5054 // C++ [class.union]p2:
5055 // The member-specification of an anonymous union shall only
5056 // define non-static data members. [Note: nested types and
5057 // functions cannot be declared within an anonymous union. ]
5058 for (auto *Mem : Record->decls()) {
5059 // Ignore invalid declarations; we already diagnosed them.
5060 if (Mem->isInvalidDecl())
5061 continue;
5062
5063 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5064 // C++ [class.union]p3:
5065 // An anonymous union shall not have private or protected
5066 // members (clause 11).
5067 assert(FD->getAccess() != AS_none)((FD->getAccess() != AS_none) ? static_cast<void> (0
) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 5067, __PRETTY_FUNCTION__))
;
5068 if (FD->getAccess() != AS_public) {
5069 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5070 << Record->isUnion() << (FD->getAccess() == AS_protected);
5071 Invalid = true;
5072 }
5073
5074 // C++ [class.union]p1
5075 // An object of a class with a non-trivial constructor, a non-trivial
5076 // copy constructor, a non-trivial destructor, or a non-trivial copy
5077 // assignment operator cannot be a member of a union, nor can an
5078 // array of such objects.
5079 if (CheckNontrivialField(FD))
5080 Invalid = true;
5081 } else if (Mem->isImplicit()) {
5082 // Any implicit members are fine.
5083 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5084 // This is a type that showed up in an
5085 // elaborated-type-specifier inside the anonymous struct or
5086 // union, but which actually declares a type outside of the
5087 // anonymous struct or union. It's okay.
5088 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5089 if (!MemRecord->isAnonymousStructOrUnion() &&
5090 MemRecord->getDeclName()) {
5091 // Visual C++ allows type definition in anonymous struct or union.
5092 if (getLangOpts().MicrosoftExt)
5093 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5094 << Record->isUnion();
5095 else {
5096 // This is a nested type declaration.
5097 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5098 << Record->isUnion();
5099 Invalid = true;
5100 }
5101 } else {
5102 // This is an anonymous type definition within another anonymous type.
5103 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5104 // not part of standard C++.
5105 Diag(MemRecord->getLocation(),
5106 diag::ext_anonymous_record_with_anonymous_type)
5107 << Record->isUnion();
5108 }
5109 } else if (isa<AccessSpecDecl>(Mem)) {
5110 // Any access specifier is fine.
5111 } else if (isa<StaticAssertDecl>(Mem)) {
5112 // In C++1z, static_assert declarations are also fine.
5113 } else {
5114 // We have something that isn't a non-static data
5115 // member. Complain about it.
5116 unsigned DK = diag::err_anonymous_record_bad_member;
5117 if (isa<TypeDecl>(Mem))
5118 DK = diag::err_anonymous_record_with_type;
5119 else if (isa<FunctionDecl>(Mem))
5120 DK = diag::err_anonymous_record_with_function;
5121 else if (isa<VarDecl>(Mem))
5122 DK = diag::err_anonymous_record_with_static;
5123
5124 // Visual C++ allows type definition in anonymous struct or union.
5125 if (getLangOpts().MicrosoftExt &&
5126 DK == diag::err_anonymous_record_with_type)
5127 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5128 << Record->isUnion();
5129 else {
5130 Diag(Mem->getLocation(), DK) << Record->isUnion();
5131 Invalid = true;
5132 }
5133 }
5134 }
5135
5136 // C++11 [class.union]p8 (DR1460):
5137 // At most one variant member of a union may have a
5138 // brace-or-equal-initializer.
5139 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5140 Owner->isRecord())
5141 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5142 cast<CXXRecordDecl>(Record));
5143 }
5144
5145 if (!Record->isUnion() && !Owner->isRecord()) {
5146 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5147 << getLangOpts().CPlusPlus;
5148 Invalid = true;
5149 }
5150
5151 // C++ [dcl.dcl]p3:
5152 // [If there are no declarators], and except for the declaration of an
5153 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5154 // names into the program
5155 // C++ [class.mem]p2:
5156 // each such member-declaration shall either declare at least one member
5157 // name of the class or declare at least one unnamed bit-field
5158 //
5159 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5160 if (getLangOpts().CPlusPlus && Record->field_empty())
5161 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5162
5163 // Mock up a declarator.
5164 Declarator Dc(DS, DeclaratorContext::MemberContext);
5165 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5166 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 5166, __PRETTY_FUNCTION__))
;
5167
5168 // Create a declaration for this anonymous struct/union.
5169 NamedDecl *Anon = nullptr;
5170 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5171 Anon = FieldDecl::Create(
5172 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5173 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5174 /*BitWidth=*/nullptr, /*Mutable=*/false,
5175 /*InitStyle=*/ICIS_NoInit);
5176 Anon->setAccess(AS);
5177 ProcessDeclAttributes(S, Anon, Dc);
5178
5179 if (getLangOpts().CPlusPlus)
5180 FieldCollector->Add(cast<FieldDecl>(Anon));
5181 } else {
5182 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5183 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5184 if (SCSpec == DeclSpec::SCS_mutable) {
5185 // mutable can only appear on non-static class members, so it's always
5186 // an error here
5187 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5188 Invalid = true;
5189 SC = SC_None;
5190 }
5191
5192 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 5192, __PRETTY_FUNCTION__))
;
5193 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5194 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5195 Context.getTypeDeclType(Record), TInfo, SC);
5196
5197 // Default-initialize the implicit variable. This initialization will be
5198 // trivial in almost all cases, except if a union member has an in-class
5199 // initializer:
5200 // union { int n = 0; };
5201 ActOnUninitializedDecl(Anon);
5202 }
5203 Anon->setImplicit();
5204
5205 // Mark this as an anonymous struct/union type.
5206 Record->setAnonymousStructOrUnion(true);
5207
5208 // Add the anonymous struct/union object to the current
5209 // context. We'll be referencing this object when we refer to one of
5210 // its members.
5211 Owner->addDecl(Anon);
5212
5213 // Inject the members of the anonymous struct/union into the owning
5214 // context and into the identifier resolver chain for name lookup
5215 // purposes.
5216 SmallVector<NamedDecl*, 2> Chain;
5217 Chain.push_back(Anon);
5218
5219 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5220 Invalid = true;
5221
5222 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5223 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5224 MangleNumberingContext *MCtx;
5225 Decl *ManglingContextDecl;
5226 std::tie(MCtx, ManglingContextDecl) =
5227 getCurrentMangleNumberContext(NewVD->getDeclContext());
5228 if (MCtx) {
5229 Context.setManglingNumber(
5230 NewVD, MCtx->getManglingNumber(
5231 NewVD, getMSManglingNumber(getLangOpts(), S)));
5232 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5233 }
5234 }
5235 }
5236
5237 if (Invalid)
5238 Anon->setInvalidDecl();
5239
5240 return Anon;
5241}
5242
5243/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5244/// Microsoft C anonymous structure.
5245/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5246/// Example:
5247///
5248/// struct A { int a; };
5249/// struct B { struct A; int b; };
5250///
5251/// void foo() {
5252/// B var;
5253/// var.a = 3;
5254/// }
5255///
5256Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5257 RecordDecl *Record) {
5258 assert(Record && "expected a record!")((Record && "expected a record!") ? static_cast<void
> (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 5258, __PRETTY_FUNCTION__))
;
5259
5260 // Mock up a declarator.
5261 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
5262 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5263 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 5263, __PRETTY_FUNCTION__))
;
5264
5265 auto *ParentDecl = cast<RecordDecl>(CurContext);
5266 QualType RecTy = Context.getTypeDeclType(Record);
5267
5268 // Create a declaration for this anonymous struct.
5269 NamedDecl *Anon =
5270 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5271 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5272 /*BitWidth=*/nullptr, /*Mutable=*/false,
5273 /*InitStyle=*/ICIS_NoInit);
5274 Anon->setImplicit();
5275
5276 // Add the anonymous struct object to the current context.
5277 CurContext->addDecl(Anon);
5278
5279 // Inject the members of the anonymous struct into the current
5280 // context and into the identifier resolver chain for name lookup
5281 // purposes.
5282 SmallVector<NamedDecl*, 2> Chain;
5283 Chain.push_back(Anon);
5284
5285 RecordDecl *RecordDef = Record->getDefinition();
5286 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5287 diag::err_field_incomplete_or_sizeless) ||
5288 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5289 AS_none, Chain)) {
5290 Anon->setInvalidDecl();
5291 ParentDecl->setInvalidDecl();
5292 }
5293
5294 return Anon;
5295}
5296
5297/// GetNameForDeclarator - Determine the full declaration name for the
5298/// given Declarator.
5299DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5300 return GetNameFromUnqualifiedId(D.getName());
5301}
5302
5303/// Retrieves the declaration name from a parsed unqualified-id.
5304DeclarationNameInfo
5305Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5306 DeclarationNameInfo NameInfo;
5307 NameInfo.setLoc(Name.StartLocation);
5308
5309 switch (Name.getKind()) {
5310
5311 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5312 case UnqualifiedIdKind::IK_Identifier:
5313 NameInfo.setName(Name.Identifier);
5314 return NameInfo;
5315
5316 case UnqualifiedIdKind::IK_DeductionGuideName: {
5317 // C++ [temp.deduct.guide]p3:
5318 // The simple-template-id shall name a class template specialization.
5319 // The template-name shall be the same identifier as the template-name
5320 // of the simple-template-id.
5321 // These together intend to imply that the template-name shall name a
5322 // class template.
5323 // FIXME: template<typename T> struct X {};
5324 // template<typename T> using Y = X<T>;
5325 // Y(int) -> Y<int>;
5326 // satisfies these rules but does not name a class template.
5327 TemplateName TN = Name.TemplateName.get().get();
5328 auto *Template = TN.getAsTemplateDecl();
5329 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5330 Diag(Name.StartLocation,
5331 diag::err_deduction_guide_name_not_class_template)
5332 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5333 if (Template)
5334 Diag(Template->getLocation(), diag::note_template_decl_here);
5335 return DeclarationNameInfo();
5336 }
5337
5338 NameInfo.setName(
5339 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5340 return NameInfo;
5341 }
5342
5343 case UnqualifiedIdKind::IK_OperatorFunctionId:
5344 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5345 Name.OperatorFunctionId.Operator));
5346 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
5347 = Name.OperatorFunctionId.SymbolLocations[0];
5348 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5349 = Name.EndLocation.getRawEncoding();
5350 return NameInfo;
5351
5352 case UnqualifiedIdKind::IK_LiteralOperatorId:
5353 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5354 Name.Identifier));
5355 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5356 return NameInfo;
5357
5358 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5359 TypeSourceInfo *TInfo;
5360 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5361 if (Ty.isNull())
5362 return DeclarationNameInfo();
5363 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5364 Context.getCanonicalType(Ty)));
5365 NameInfo.setNamedTypeInfo(TInfo);
5366 return NameInfo;
5367 }
5368
5369 case UnqualifiedIdKind::IK_ConstructorName: {
5370 TypeSourceInfo *TInfo;
5371 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5372 if (Ty.isNull())
5373 return DeclarationNameInfo();
5374 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5375 Context.getCanonicalType(Ty)));
5376 NameInfo.setNamedTypeInfo(TInfo);
5377 return NameInfo;
5378 }
5379
5380 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5381 // In well-formed code, we can only have a constructor
5382 // template-id that refers to the current context, so go there
5383 // to find the actual type being constructed.
5384 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5385 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5386 return DeclarationNameInfo();
5387
5388 // Determine the type of the class being constructed.
5389 QualType CurClassType = Context.getTypeDeclType(CurClass);
5390
5391 // FIXME: Check two things: that the template-id names the same type as
5392 // CurClassType, and that the template-id does not occur when the name
5393 // was qualified.
5394
5395 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5396 Context.getCanonicalType(CurClassType)));
5397 // FIXME: should we retrieve TypeSourceInfo?
5398 NameInfo.setNamedTypeInfo(nullptr);
5399 return NameInfo;
5400 }
5401
5402 case UnqualifiedIdKind::IK_DestructorName: {
5403 TypeSourceInfo *TInfo;
5404 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5405 if (Ty.isNull())
5406 return DeclarationNameInfo();
5407 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5408 Context.getCanonicalType(Ty)));
5409 NameInfo.setNamedTypeInfo(TInfo);
5410 return NameInfo;
5411 }
5412
5413 case UnqualifiedIdKind::IK_TemplateId: {
5414 TemplateName TName = Name.TemplateId->Template.get();
5415 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5416 return Context.getNameForTemplate(TName, TNameLoc);
5417 }
5418
5419 } // switch (Name.getKind())
5420
5421 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 5421)
;
5422}
5423
5424static QualType getCoreType(QualType Ty) {
5425 do {
5426 if (Ty->isPointerType() || Ty->isReferenceType())
5427 Ty = Ty->getPointeeType();
5428 else if (Ty->isArrayType())
5429 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5430 else
5431 return Ty.withoutLocalFastQualifiers();
5432 } while (true);
5433}
5434
5435/// hasSimilarParameters - Determine whether the C++ functions Declaration
5436/// and Definition have "nearly" matching parameters. This heuristic is
5437/// used to improve diagnostics in the case where an out-of-line function
5438/// definition doesn't match any declaration within the class or namespace.
5439/// Also sets Params to the list of indices to the parameters that differ
5440/// between the declaration and the definition. If hasSimilarParameters
5441/// returns true and Params is empty, then all of the parameters match.
5442static bool hasSimilarParameters(ASTContext &Context,
5443 FunctionDecl *Declaration,
5444 FunctionDecl *Definition,
5445 SmallVectorImpl<unsigned> &Params) {
5446 Params.clear();
5447 if (Declaration->param_size() != Definition->param_size())
5448 return false;
5449 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5450 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5451 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5452
5453 // The parameter types are identical
5454 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5455 continue;
5456
5457 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5458 QualType DefParamBaseTy = getCoreType(DefParamTy);
5459 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5460 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5461
5462 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5463 (DeclTyName && DeclTyName == DefTyName))
5464 Params.push_back(Idx);
5465 else // The two parameters aren't even close
5466 return false;
5467 }
5468
5469 return true;
5470}
5471
5472/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5473/// declarator needs to be rebuilt in the current instantiation.
5474/// Any bits of declarator which appear before the name are valid for
5475/// consideration here. That's specifically the type in the decl spec
5476/// and the base type in any member-pointer chunks.
5477static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5478 DeclarationName Name) {
5479 // The types we specifically need to rebuild are:
5480 // - typenames, typeofs, and decltypes
5481 // - types which will become injected class names
5482 // Of course, we also need to rebuild any type referencing such a
5483 // type. It's safest to just say "dependent", but we call out a
5484 // few cases here.
5485
5486 DeclSpec &DS = D.getMutableDeclSpec();
5487 switch (DS.getTypeSpecType()) {
5488 case DeclSpec::TST_typename:
5489 case DeclSpec::TST_typeofType:
5490 case DeclSpec::TST_underlyingType:
5491 case DeclSpec::TST_atomic: {
5492 // Grab the type from the parser.
5493 TypeSourceInfo *TSI = nullptr;
5494 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5495 if (T.isNull() || !T->isDependentType()) break;
5496
5497 // Make sure there's a type source info. This isn't really much
5498 // of a waste; most dependent types should have type source info
5499 // attached already.
5500 if (!TSI)
5501 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5502
5503 // Rebuild the type in the current instantiation.
5504 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5505 if (!TSI) return true;
5506
5507 // Store the new type back in the decl spec.
5508 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5509 DS.UpdateTypeRep(LocType);
5510 break;
5511 }
5512
5513 case DeclSpec::TST_decltype:
5514 case DeclSpec::TST_typeofExpr: {
5515 Expr *E = DS.getRepAsExpr();
5516 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5517 if (Result.isInvalid()) return true;
5518 DS.UpdateExprRep(Result.get());
5519 break;
5520 }
5521
5522 default:
5523 // Nothing to do for these decl specs.
5524 break;
5525 }
5526
5527 // It doesn't matter what order we do this in.
5528 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5529 DeclaratorChunk &Chunk = D.getTypeObject(I);
5530
5531 // The only type information in the declarator which can come
5532 // before the declaration name is the base type of a member
5533 // pointer.
5534 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5535 continue;
5536
5537 // Rebuild the scope specifier in-place.
5538 CXXScopeSpec &SS = Chunk.Mem.Scope();
5539 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5540 return true;
5541 }
5542
5543 return false;
5544}
5545
5546Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5547 D.setFunctionDefinitionKind(FDK_Declaration);
5548 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5549
5550 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5551 Dcl && Dcl->getDeclContext()->isFileContext())
5552 Dcl->setTopLevelDeclInObjCContainer();
5553
5554 if (getLangOpts().OpenCL)
5555 setCurrentOpenCLExtensionForDecl(Dcl);
5556
5557 return Dcl;
5558}
5559
5560/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5561/// If T is the name of a class, then each of the following shall have a
5562/// name different from T:
5563/// - every static data member of class T;
5564/// - every member function of class T
5565/// - every member of class T that is itself a type;
5566/// \returns true if the declaration name violates these rules.
5567bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5568 DeclarationNameInfo NameInfo) {
5569 DeclarationName Name = NameInfo.getName();
5570
5571 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5572 while (Record && Record->isAnonymousStructOrUnion())
5573 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5574 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5575 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5576 return true;
5577 }
5578
5579 return false;
5580}
5581
5582/// Diagnose a declaration whose declarator-id has the given
5583/// nested-name-specifier.
5584///
5585/// \param SS The nested-name-specifier of the declarator-id.
5586///
5587/// \param DC The declaration context to which the nested-name-specifier
5588/// resolves.
5589///
5590/// \param Name The name of the entity being declared.
5591///
5592/// \param Loc The location of the name of the entity being declared.
5593///
5594/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5595/// we're declaring an explicit / partial specialization / instantiation.
5596///
5597/// \returns true if we cannot safely recover from this error, false otherwise.
5598bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5599 DeclarationName Name,
5600 SourceLocation Loc, bool IsTemplateId) {
5601 DeclContext *Cur = CurContext;
5602 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5603 Cur = Cur->getParent();
5604
5605 // If the user provided a superfluous scope specifier that refers back to the
5606 // class in which the entity is already declared, diagnose and ignore it.
5607 //
5608 // class X {
5609 // void X::f();
5610 // };
5611 //
5612 // Note, it was once ill-formed to give redundant qualification in all
5613 // contexts, but that rule was removed by DR482.
5614 if (Cur->Equals(DC)) {
5615 if (Cur->isRecord()) {
5616 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5617 : diag::err_member_extra_qualification)
5618 << Name << FixItHint::CreateRemoval(SS.getRange());
5619 SS.clear();
5620 } else {
5621 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5622 }
5623 return false;
5624 }
5625
5626 // Check whether the qualifying scope encloses the scope of the original
5627 // declaration. For a template-id, we perform the checks in
5628 // CheckTemplateSpecializationScope.
5629 if (!Cur->Encloses(DC) && !IsTemplateId) {
5630 if (Cur->isRecord())
5631 Diag(Loc, diag::err_member_qualification)
5632 << Name << SS.getRange();
5633 else if (isa<TranslationUnitDecl>(DC))
5634 Diag(Loc, diag::err_invalid_declarator_global_scope)
5635 << Name << SS.getRange();
5636 else if (isa<FunctionDecl>(Cur))
5637 Diag(Loc, diag::err_invalid_declarator_in_function)
5638 << Name << SS.getRange();
5639 else if (isa<BlockDecl>(Cur))
5640 Diag(Loc, diag::err_invalid_declarator_in_block)
5641 << Name << SS.getRange();
5642 else
5643 Diag(Loc, diag::err_invalid_declarator_scope)
5644 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5645
5646 return true;
5647 }
5648
5649 if (Cur->isRecord()) {
5650 // Cannot qualify members within a class.
5651 Diag(Loc, diag::err_member_qualification)
5652 << Name << SS.getRange();
5653 SS.clear();
5654
5655 // C++ constructors and destructors with incorrect scopes can break
5656 // our AST invariants by having the wrong underlying types. If
5657 // that's the case, then drop this declaration entirely.
5658 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5659 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5660 !Context.hasSameType(Name.getCXXNameType(),
5661 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5662 return true;
5663
5664 return false;
5665 }
5666
5667 // C++11 [dcl.meaning]p1:
5668 // [...] "The nested-name-specifier of the qualified declarator-id shall
5669 // not begin with a decltype-specifer"
5670 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5671 while (SpecLoc.getPrefix())
5672 SpecLoc = SpecLoc.getPrefix();
5673 if (dyn_cast_or_null<DecltypeType>(
5674 SpecLoc.getNestedNameSpecifier()->getAsType()))
5675 Diag(Loc, diag::err_decltype_in_declarator)
5676 << SpecLoc.getTypeLoc().getSourceRange();
5677
5678 return false;
5679}
5680
5681NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5682 MultiTemplateParamsArg TemplateParamLists) {
5683 // TODO: consider using NameInfo for diagnostic.
5684 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5685 DeclarationName Name = NameInfo.getName();
5686
5687 // All of these full declarators require an identifier. If it doesn't have
5688 // one, the ParsedFreeStandingDeclSpec action should be used.
5689 if (D.isDecompositionDeclarator()) {
5690 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5691 } else if (!Name) {
5692 if (!D.isInvalidType()) // Reject this if we think it is valid.
5693 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5694 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5695 return nullptr;
5696 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5697 return nullptr;
5698
5699 // The scope passed in may not be a decl scope. Zip up the scope tree until
5700 // we find one that is.
5701 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5702 (S->getFlags() & Scope::TemplateParamScope) != 0)
5703 S = S->getParent();
5704
5705 DeclContext *DC = CurContext;
5706 if (D.getCXXScopeSpec().isInvalid())
5707 D.setInvalidType();
5708 else if (D.getCXXScopeSpec().isSet()) {
5709 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5710 UPPC_DeclarationQualifier))
5711 return nullptr;
5712
5713 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5714 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5715 if (!DC || isa<EnumDecl>(DC)) {
5716 // If we could not compute the declaration context, it's because the
5717 // declaration context is dependent but does not refer to a class,
5718 // class template, or class template partial specialization. Complain
5719 // and return early, to avoid the coming semantic disaster.
5720 Diag(D.getIdentifierLoc(),
5721 diag::err_template_qualified_declarator_no_match)
5722 << D.getCXXScopeSpec().getScopeRep()
5723 << D.getCXXScopeSpec().getRange();
5724 return nullptr;
5725 }
5726 bool IsDependentContext = DC->isDependentContext();
5727
5728 if (!IsDependentContext &&
5729 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5730 return nullptr;
5731
5732 // If a class is incomplete, do not parse entities inside it.
5733 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5734 Diag(D.getIdentifierLoc(),
5735 diag::err_member_def_undefined_record)
5736 << Name << DC << D.getCXXScopeSpec().getRange();
5737 return nullptr;
5738 }
5739 if (!D.getDeclSpec().isFriendSpecified()) {
5740 if (diagnoseQualifiedDeclaration(
5741 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5742 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5743 if (DC->isRecord())
5744 return nullptr;
5745
5746 D.setInvalidType();
5747 }
5748 }
5749
5750 // Check whether we need to rebuild the type of the given
5751 // declaration in the current instantiation.
5752 if (EnteringContext && IsDependentContext &&
5753 TemplateParamLists.size() != 0) {
5754 ContextRAII SavedContext(*this, DC);
5755 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5756 D.setInvalidType();
5757 }
5758 }
5759
5760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5761 QualType R = TInfo->getType();
5762
5763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5764 UPPC_DeclarationType))
5765 D.setInvalidType();
5766
5767 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5768 forRedeclarationInCurContext());
5769
5770 // See if this is a redefinition of a variable in the same scope.
5771 if (!D.getCXXScopeSpec().isSet()) {
5772 bool IsLinkageLookup = false;
5773 bool CreateBuiltins = false;
5774
5775 // If the declaration we're planning to build will be a function
5776 // or object with linkage, then look for another declaration with
5777 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5778 //
5779 // If the declaration we're planning to build will be declared with
5780 // external linkage in the translation unit, create any builtin with
5781 // the same name.
5782 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5783 /* Do nothing*/;
5784 else if (CurContext->isFunctionOrMethod() &&
5785 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5786 R->isFunctionType())) {
5787 IsLinkageLookup = true;
5788 CreateBuiltins =
5789 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5790 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5791 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5792 CreateBuiltins = true;
5793
5794 if (IsLinkageLookup) {
5795 Previous.clear(LookupRedeclarationWithLinkage);
5796 Previous.setRedeclarationKind(ForExternalRedeclaration);
5797 }
5798
5799 LookupName(Previous, S, CreateBuiltins);
5800 } else { // Something like "int foo::x;"
5801 LookupQualifiedName(Previous, DC);
5802
5803 // C++ [dcl.meaning]p1:
5804 // When the declarator-id is qualified, the declaration shall refer to a
5805 // previously declared member of the class or namespace to which the
5806 // qualifier refers (or, in the case of a namespace, of an element of the
5807 // inline namespace set of that namespace (7.3.1)) or to a specialization
5808 // thereof; [...]
5809 //
5810 // Note that we already checked the context above, and that we do not have
5811 // enough information to make sure that Previous contains the declaration
5812 // we want to match. For example, given:
5813 //
5814 // class X {
5815 // void f();
5816 // void f(float);
5817 // };
5818 //
5819 // void X::f(int) { } // ill-formed
5820 //
5821 // In this case, Previous will point to the overload set
5822 // containing the two f's declared in X, but neither of them
5823 // matches.
5824
5825 // C++ [dcl.meaning]p1:
5826 // [...] the member shall not merely have been introduced by a
5827 // using-declaration in the scope of the class or namespace nominated by
5828 // the nested-name-specifier of the declarator-id.
5829 RemoveUsingDecls(Previous);
5830 }
5831
5832 if (Previous.isSingleResult() &&
5833 Previous.getFoundDecl()->isTemplateParameter()) {
5834 // Maybe we will complain about the shadowed template parameter.
5835 if (!D.isInvalidType())
5836 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5837 Previous.getFoundDecl());
5838
5839 // Just pretend that we didn't see the previous declaration.
5840 Previous.clear();
5841 }
5842
5843 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5844 // Forget that the previous declaration is the injected-class-name.
5845 Previous.clear();
5846
5847 // In C++, the previous declaration we find might be a tag type
5848 // (class or enum). In this case, the new declaration will hide the
5849 // tag type. Note that this applies to functions, function templates, and
5850 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5851 if (Previous.isSingleTagDecl() &&
5852 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5853 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5854 Previous.clear();
5855
5856 // Check that there are no default arguments other than in the parameters
5857 // of a function declaration (C++ only).
5858 if (getLangOpts().CPlusPlus)
5859 CheckExtraCXXDefaultArguments(D);
5860
5861 NamedDecl *New;
5862
5863 bool AddToScope = true;
5864 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5865 if (TemplateParamLists.size()) {
5866 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5867 return nullptr;
5868 }
5869
5870 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5871 } else if (R->isFunctionType()) {
5872 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5873 TemplateParamLists,
5874 AddToScope);
5875 } else {
5876 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5877 AddToScope);
5878 }
5879
5880 if (!New)
5881 return nullptr;
5882
5883 // If this has an identifier and is not a function template specialization,
5884 // add it to the scope stack.
5885 if (New->getDeclName() && AddToScope)
5886 PushOnScopeChains(New, S);
5887
5888 if (isInOpenMPDeclareTargetContext())
5889 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5890
5891 return New;
5892}
5893
5894/// Helper method to turn variable array types into constant array
5895/// types in certain situations which would otherwise be errors (for
5896/// GCC compatibility).
5897static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5898 ASTContext &Context,
5899 bool &SizeIsNegative,
5900 llvm::APSInt &Oversized) {
5901 // This method tries to turn a variable array into a constant
5902 // array even when the size isn't an ICE. This is necessary
5903 // for compatibility with code that depends on gcc's buggy
5904 // constant expression folding, like struct {char x[(int)(char*)2];}
5905 SizeIsNegative = false;
5906 Oversized = 0;
5907
5908 if (T->isDependentType())
5909 return QualType();
5910
5911 QualifierCollector Qs;
5912 const Type *Ty = Qs.strip(T);
5913
5914 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5915 QualType Pointee = PTy->getPointeeType();
5916 QualType FixedType =
5917 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5918 Oversized);
5919 if (FixedType.isNull()) return FixedType;
5920 FixedType = Context.getPointerType(FixedType);
5921 return Qs.apply(Context, FixedType);
5922 }
5923 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5924 QualType Inner = PTy->getInnerType();
5925 QualType FixedType =
5926 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5927 Oversized);
5928 if (FixedType.isNull()) return FixedType;
5929 FixedType = Context.getParenType(FixedType);
5930 return Qs.apply(Context, FixedType);
5931 }
5932
5933 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5934 if (!VLATy)
5935 return QualType();
5936 // FIXME: We should probably handle this case
5937 if (VLATy->getElementType()->isVariablyModifiedType())
5938 return QualType();
5939
5940 Expr::EvalResult Result;
5941 if (!VLATy->getSizeExpr() ||
5942 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
5943 return QualType();
5944
5945 llvm::APSInt Res = Result.Val.getInt();
5946
5947 // Check whether the array size is negative.
5948 if (Res.isSigned() && Res.isNegative()) {
5949 SizeIsNegative = true;
5950 return QualType();
5951 }
5952
5953 // Check whether the array is too large to be addressed.
5954 unsigned ActiveSizeBits
5955 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5956 Res);
5957 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5958 Oversized = Res;
5959 return QualType();
5960 }
5961
5962 return Context.getConstantArrayType(
5963 VLATy->getElementType(), Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
5964}
5965
5966static void
5967FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5968 SrcTL = SrcTL.getUnqualifiedLoc();
5969 DstTL = DstTL.getUnqualifiedLoc();
5970 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5971 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5972 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5973 DstPTL.getPointeeLoc());
5974 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5975 return;
5976 }
5977 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5978 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5979 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5980 DstPTL.getInnerLoc());
5981 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5982 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5983 return;
5984 }
5985 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5986 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5987 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5988 TypeLoc DstElemTL = DstATL.getElementLoc();
5989 DstElemTL.initializeFullCopy(SrcElemTL);
5990 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5991 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5992 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5993}
5994
5995/// Helper method to turn variable array types into constant array
5996/// types in certain situations which would otherwise be errors (for
5997/// GCC compatibility).
5998static TypeSourceInfo*
5999TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6000 ASTContext &Context,
6001 bool &SizeIsNegative,
6002 llvm::APSInt &Oversized) {
6003 QualType FixedTy
6004 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6005 SizeIsNegative, Oversized);
6006 if (FixedTy.isNull())
6007 return nullptr;
6008 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6009 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6010 FixedTInfo->getTypeLoc());
6011 return FixedTInfo;
6012}
6013
6014/// Register the given locally-scoped extern "C" declaration so
6015/// that it can be found later for redeclarations. We include any extern "C"
6016/// declaration that is not visible in the translation unit here, not just
6017/// function-scope declarations.
6018void
6019Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6020 if (!getLangOpts().CPlusPlus &&
6021 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6022 // Don't need to track declarations in the TU in C.
6023 return;
6024
6025 // Note that we have a locally-scoped external with this name.
6026 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6027}
6028
6029NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6030 // FIXME: We can have multiple results via __attribute__((overloadable)).
6031 auto Result = Context.getExternCContextDecl()->lookup(Name);
6032 return Result.empty() ? nullptr : *Result.begin();
6033}
6034
6035/// Diagnose function specifiers on a declaration of an identifier that
6036/// does not identify a function.
6037void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6038 // FIXME: We should probably indicate the identifier in question to avoid
6039 // confusion for constructs like "virtual int a(), b;"
6040 if (DS.isVirtualSpecified())
6041 Diag(DS.getVirtualSpecLoc(),
6042 diag::err_virtual_non_function);
6043
6044 if (DS.hasExplicitSpecifier())
6045 Diag(DS.getExplicitSpecLoc(),
6046 diag::err_explicit_non_function);
6047
6048 if (DS.isNoreturnSpecified())
6049 Diag(DS.getNoreturnSpecLoc(),
6050 diag::err_noreturn_non_function);
6051}
6052
6053NamedDecl*
6054Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6055 TypeSourceInfo *TInfo, LookupResult &Previous) {
6056 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6057 if (D.getCXXScopeSpec().isSet()) {
6058 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6059 << D.getCXXScopeSpec().getRange();
6060 D.setInvalidType();
6061 // Pretend we didn't see the scope specifier.
6062 DC = CurContext;
6063 Previous.clear();
6064 }
6065
6066 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6067
6068 if (D.getDeclSpec().isInlineSpecified())
6069 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6070 << getLangOpts().CPlusPlus17;
6071 if (D.getDeclSpec().hasConstexprSpecifier())
6072 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6073 << 1 << D.getDeclSpec().getConstexprSpecifier();
6074
6075 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6076 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6077 Diag(D.getName().StartLocation,
6078 diag::err_deduction_guide_invalid_specifier)
6079 << "typedef";
6080 else
6081 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6082 << D.getName().getSourceRange();
6083 return nullptr;
6084 }
6085
6086 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6087 if (!NewTD) return nullptr;
6088
6089 // Handle attributes prior to checking for duplicates in MergeVarDecl
6090 ProcessDeclAttributes(S, NewTD, D);
6091
6092 CheckTypedefForVariablyModifiedType(S, NewTD);
6093
6094 bool Redeclaration = D.isRedeclaration();
6095 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6096 D.setRedeclaration(Redeclaration);
6097 return ND;
6098}
6099
6100void
6101Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6102 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6103 // then it shall have block scope.
6104 // Note that variably modified types must be fixed before merging the decl so
6105 // that redeclarations will match.
6106 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6107 QualType T = TInfo->getType();
6108 if (T->isVariablyModifiedType()) {
6109 setFunctionHasBranchProtectedScope();
6110
6111 if (S->getFnParent() == nullptr) {
6112 bool SizeIsNegative;
6113 llvm::APSInt Oversized;
6114 TypeSourceInfo *FixedTInfo =
6115 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6116 SizeIsNegative,
6117 Oversized);
6118 if (FixedTInfo) {
6119 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
6120 NewTD->setTypeSourceInfo(FixedTInfo);
6121 } else {
6122 if (SizeIsNegative)
6123 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6124 else if (T->isVariableArrayType())
6125 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6126 else if (Oversized.getBoolValue())
6127 Diag(NewTD->getLocation(), diag::err_array_too_large)
6128 << Oversized.toString(10);
6129 else
6130 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6131 NewTD->setInvalidDecl();
6132 }
6133 }
6134 }
6135}
6136
6137/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6138/// declares a typedef-name, either using the 'typedef' type specifier or via
6139/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6140NamedDecl*
6141Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6142 LookupResult &Previous, bool &Redeclaration) {
6143
6144 // Find the shadowed declaration before filtering for scope.
6145 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6146
6147 // Merge the decl with the existing one if appropriate. If the decl is
6148 // in an outer scope, it isn't the same thing.
6149 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6150 /*AllowInlineNamespace*/false);
6151 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6152 if (!Previous.empty()) {
6153 Redeclaration = true;
6154 MergeTypedefNameDecl(S, NewTD, Previous);
6155 } else {
6156 inferGslPointerAttribute(NewTD);
6157 }
6158
6159 if (ShadowedDecl && !Redeclaration)
6160 CheckShadow(NewTD, ShadowedDecl, Previous);
6161
6162 // If this is the C FILE type, notify the AST context.
6163 if (IdentifierInfo *II = NewTD->getIdentifier())
6164 if (!NewTD->isInvalidDecl() &&
6165 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6166 if (II->isStr("FILE"))
6167 Context.setFILEDecl(NewTD);
6168 else if (II->isStr("jmp_buf"))
6169 Context.setjmp_bufDecl(NewTD);
6170 else if (II->isStr("sigjmp_buf"))
6171 Context.setsigjmp_bufDecl(NewTD);
6172 else if (II->isStr("ucontext_t"))
6173 Context.setucontext_tDecl(NewTD);
6174 }
6175
6176 return NewTD;
6177}
6178
6179/// Determines whether the given declaration is an out-of-scope
6180/// previous declaration.
6181///
6182/// This routine should be invoked when name lookup has found a
6183/// previous declaration (PrevDecl) that is not in the scope where a
6184/// new declaration by the same name is being introduced. If the new
6185/// declaration occurs in a local scope, previous declarations with
6186/// linkage may still be considered previous declarations (C99
6187/// 6.2.2p4-5, C++ [basic.link]p6).
6188///
6189/// \param PrevDecl the previous declaration found by name
6190/// lookup
6191///
6192/// \param DC the context in which the new declaration is being
6193/// declared.
6194///
6195/// \returns true if PrevDecl is an out-of-scope previous declaration
6196/// for a new delcaration with the same name.
6197static bool
6198isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6199 ASTContext &Context) {
6200 if (!PrevDecl)
6201 return false;
6202
6203 if (!PrevDecl->hasLinkage())
6204 return false;
6205
6206 if (Context.getLangOpts().CPlusPlus) {
6207 // C++ [basic.link]p6:
6208 // If there is a visible declaration of an entity with linkage
6209 // having the same name and type, ignoring entities declared
6210 // outside the innermost enclosing namespace scope, the block
6211 // scope declaration declares that same entity and receives the
6212 // linkage of the previous declaration.
6213 DeclContext *OuterContext = DC->getRedeclContext();
6214 if (!OuterContext->isFunctionOrMethod())
6215 // This rule only applies to block-scope declarations.
6216 return false;
6217
6218 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6219 if (PrevOuterContext->isRecord())
6220 // We found a member function: ignore it.
6221 return false;
6222
6223 // Find the innermost enclosing namespace for the new and
6224 // previous declarations.
6225 OuterContext = OuterContext->getEnclosingNamespaceContext();
6226 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6227
6228 // The previous declaration is in a different namespace, so it
6229 // isn't the same function.
6230 if (!OuterContext->Equals(PrevOuterContext))
6231 return false;
6232 }
6233
6234 return true;
6235}
6236
6237static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6238 CXXScopeSpec &SS = D.getCXXScopeSpec();
6239 if (!SS.isSet()) return;
6240 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6241}
6242
6243bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6244 QualType type = decl->getType();
6245 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6246 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6247 // Various kinds of declaration aren't allowed to be __autoreleasing.
6248 unsigned kind = -1U;
6249 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6250 if (var->hasAttr<BlocksAttr>())
6251 kind = 0; // __block
6252 else if (!var->hasLocalStorage())
6253 kind = 1; // global
6254 } else if (isa<ObjCIvarDecl>(decl)) {
6255 kind = 3; // ivar
6256 } else if (isa<FieldDecl>(decl)) {
6257 kind = 2; // field
6258 }
6259
6260 if (kind != -1U) {
6261 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6262 << kind;
6263 }
6264 } else if (lifetime == Qualifiers::OCL_None) {
6265 // Try to infer lifetime.
6266 if (!type->isObjCLifetimeType())
6267 return false;
6268
6269 lifetime = type->getObjCARCImplicitLifetime();
6270 type = Context.getLifetimeQualifiedType(type, lifetime);
6271 decl->setType(type);
6272 }
6273
6274 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6275 // Thread-local variables cannot have lifetime.
6276 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6277 var->getTLSKind()) {
6278 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6279 << var->getType();
6280 return true;
6281 }
6282 }
6283
6284 return false;
6285}
6286
6287void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6288 if (Decl->getType().hasAddressSpace())
6289 return;
6290 if (Decl->getType()->isDependentType())
6291 return;
6292 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6293 QualType Type = Var->getType();
6294 if (Type->isSamplerT() || Type->isVoidType())
6295 return;
6296 LangAS ImplAS = LangAS::opencl_private;
6297 if ((getLangOpts().OpenCLCPlusPlus || getLangOpts().OpenCLVersion >= 200) &&
6298 Var->hasGlobalStorage())
6299 ImplAS = LangAS::opencl_global;
6300 // If the original type from a decayed type is an array type and that array
6301 // type has no address space yet, deduce it now.
6302 if (auto DT = dyn_cast<DecayedType>(Type)) {
6303 auto OrigTy = DT->getOriginalType();
6304 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6305 // Add the address space to the original array type and then propagate
6306 // that to the element type through `getAsArrayType`.
6307 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6308 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6309 // Re-generate the decayed type.
6310 Type = Context.getDecayedType(OrigTy);
6311 }
6312 }
6313 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6314 // Apply any qualifiers (including address space) from the array type to
6315 // the element type. This implements C99 6.7.3p8: "If the specification of
6316 // an array type includes any type qualifiers, the element type is so
6317 // qualified, not the array type."
6318 if (Type->isArrayType())
6319 Type = QualType(Context.getAsArrayType(Type), 0);
6320 Decl->setType(Type);
6321 }
6322}
6323
6324static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6325 // Ensure that an auto decl is deduced otherwise the checks below might cache
6326 // the wrong linkage.
6327 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6327, __PRETTY_FUNCTION__))
;
6328
6329 // 'weak' only applies to declarations with external linkage.
6330 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6331 if (!ND.isExternallyVisible()) {
6332 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6333 ND.dropAttr<WeakAttr>();
6334 }
6335 }
6336 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6337 if (ND.isExternallyVisible()) {
6338 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6339 ND.dropAttr<WeakRefAttr>();
6340 ND.dropAttr<AliasAttr>();
6341 }
6342 }
6343
6344 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6345 if (VD->hasInit()) {
6346 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6347 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6348, __PRETTY_FUNCTION__))
6348 !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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6348, __PRETTY_FUNCTION__))
;
6349 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6350 VD->dropAttr<AliasAttr>();
6351 }
6352 }
6353 }
6354
6355 // 'selectany' only applies to externally visible variable declarations.
6356 // It does not apply to functions.
6357 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6358 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6359 S.Diag(Attr->getLocation(),
6360 diag::err_attribute_selectany_non_extern_data);
6361 ND.dropAttr<SelectAnyAttr>();
6362 }
6363 }
6364
6365 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6366 auto *VD = dyn_cast<VarDecl>(&ND);
6367 bool IsAnonymousNS = false;
6368 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6369 if (VD) {
6370 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6371 while (NS && !IsAnonymousNS) {
6372 IsAnonymousNS = NS->isAnonymousNamespace();
6373 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6374 }
6375 }
6376 // dll attributes require external linkage. Static locals may have external
6377 // linkage but still cannot be explicitly imported or exported.
6378 // In Microsoft mode, a variable defined in anonymous namespace must have
6379 // external linkage in order to be exported.
6380 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6381 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6382 (!AnonNSInMicrosoftMode &&
6383 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6384 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6385 << &ND << Attr;
6386 ND.setInvalidDecl();
6387 }
6388 }
6389
6390 // Virtual functions cannot be marked as 'notail'.
6391 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6392 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6393 if (MD->isVirtual()) {
6394 S.Diag(ND.getLocation(),
6395 diag::err_invalid_attribute_on_virtual_function)
6396 << Attr;
6397 ND.dropAttr<NotTailCalledAttr>();
6398 }
6399
6400 // Check the attributes on the function type, if any.
6401 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6402 // Don't declare this variable in the second operand of the for-statement;
6403 // GCC miscompiles that by ending its lifetime before evaluating the
6404 // third operand. See gcc.gnu.org/PR86769.
6405 AttributedTypeLoc ATL;
6406 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6407 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6408 TL = ATL.getModifiedLoc()) {
6409 // The [[lifetimebound]] attribute can be applied to the implicit object
6410 // parameter of a non-static member function (other than a ctor or dtor)
6411 // by applying it to the function type.
6412 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6413 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6414 if (!MD || MD->isStatic()) {
6415 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6416 << !MD << A->getRange();
6417 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6418 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6419 << isa<CXXDestructorDecl>(MD) << A->getRange();
6420 }
6421 }
6422 }
6423 }
6424}
6425
6426static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6427 NamedDecl *NewDecl,
6428 bool IsSpecialization,
6429 bool IsDefinition) {
6430 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6431 return;
6432
6433 bool IsTemplate = false;
6434 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6435 OldDecl = OldTD->getTemplatedDecl();
6436 IsTemplate = true;
6437 if (!IsSpecialization)
6438 IsDefinition = false;
6439 }
6440 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6441 NewDecl = NewTD->getTemplatedDecl();
6442 IsTemplate = true;
6443 }
6444
6445 if (!OldDecl || !NewDecl)
6446 return;
6447
6448 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6449 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6450 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6451 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6452
6453 // dllimport and dllexport are inheritable attributes so we have to exclude
6454 // inherited attribute instances.
6455 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6456 (NewExportAttr && !NewExportAttr->isInherited());
6457
6458 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6459 // the only exception being explicit specializations.
6460 // Implicitly generated declarations are also excluded for now because there
6461 // is no other way to switch these to use dllimport or dllexport.
6462 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6463
6464 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6465 // Allow with a warning for free functions and global variables.
6466 bool JustWarn = false;
6467 if (!OldDecl->isCXXClassMember()) {
6468 auto *VD = dyn_cast<VarDecl>(OldDecl);
6469 if (VD && !VD->getDescribedVarTemplate())
6470 JustWarn = true;
6471 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6472 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6473 JustWarn = true;
6474 }
6475
6476 // We cannot change a declaration that's been used because IR has already
6477 // been emitted. Dllimported functions will still work though (modulo
6478 // address equality) as they can use the thunk.
6479 if (OldDecl->isUsed())
6480 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6481 JustWarn = false;
6482
6483 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6484 : diag::err_attribute_dll_redeclaration;
6485 S.Diag(NewDecl->getLocation(), DiagID)
6486 << NewDecl
6487 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6488 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6489 if (!JustWarn) {
6490 NewDecl->setInvalidDecl();
6491 return;
6492 }
6493 }
6494
6495 // A redeclaration is not allowed to drop a dllimport attribute, the only
6496 // exceptions being inline function definitions (except for function
6497 // templates), local extern declarations, qualified friend declarations or
6498 // special MSVC extension: in the last case, the declaration is treated as if
6499 // it were marked dllexport.
6500 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6501 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6502 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6503 // Ignore static data because out-of-line definitions are diagnosed
6504 // separately.
6505 IsStaticDataMember = VD->isStaticDataMember();
6506 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6507 VarDecl::DeclarationOnly;
6508 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6509 IsInline = FD->isInlined();
6510 IsQualifiedFriend = FD->getQualifier() &&
6511 FD->getFriendObjectKind() == Decl::FOK_Declared;
6512 }
6513
6514 if (OldImportAttr && !HasNewAttr &&
6515 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6516 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6517 if (IsMicrosoft && IsDefinition) {
6518 S.Diag(NewDecl->getLocation(),
6519 diag::warn_redeclaration_without_import_attribute)
6520 << NewDecl;
6521 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6522 NewDecl->dropAttr<DLLImportAttr>();
6523 NewDecl->addAttr(
6524 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6525 } else {
6526 S.Diag(NewDecl->getLocation(),
6527 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6528 << NewDecl << OldImportAttr;
6529 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6530 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6531 OldDecl->dropAttr<DLLImportAttr>();
6532 NewDecl->dropAttr<DLLImportAttr>();
6533 }
6534 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6535 // In MinGW, seeing a function declared inline drops the dllimport
6536 // attribute.
6537 OldDecl->dropAttr<DLLImportAttr>();
6538 NewDecl->dropAttr<DLLImportAttr>();
6539 S.Diag(NewDecl->getLocation(),
6540 diag::warn_dllimport_dropped_from_inline_function)
6541 << NewDecl << OldImportAttr;
6542 }
6543
6544 // A specialization of a class template member function is processed here
6545 // since it's a redeclaration. If the parent class is dllexport, the
6546 // specialization inherits that attribute. This doesn't happen automatically
6547 // since the parent class isn't instantiated until later.
6548 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6549 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6550 !NewImportAttr && !NewExportAttr) {
6551 if (const DLLExportAttr *ParentExportAttr =
6552 MD->getParent()->getAttr<DLLExportAttr>()) {
6553 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6554 NewAttr->setInherited(true);
6555 NewDecl->addAttr(NewAttr);
6556 }
6557 }
6558 }
6559}
6560
6561/// Given that we are within the definition of the given function,
6562/// will that definition behave like C99's 'inline', where the
6563/// definition is discarded except for optimization purposes?
6564static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6565 // Try to avoid calling GetGVALinkageForFunction.
6566
6567 // All cases of this require the 'inline' keyword.
6568 if (!FD->isInlined()) return false;
6569
6570 // This is only possible in C++ with the gnu_inline attribute.
6571 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6572 return false;
6573
6574 // Okay, go ahead and call the relatively-more-expensive function.
6575 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6576}
6577
6578/// Determine whether a variable is extern "C" prior to attaching
6579/// an initializer. We can't just call isExternC() here, because that
6580/// will also compute and cache whether the declaration is externally
6581/// visible, which might change when we attach the initializer.
6582///
6583/// This can only be used if the declaration is known to not be a
6584/// redeclaration of an internal linkage declaration.
6585///
6586/// For instance:
6587///
6588/// auto x = []{};
6589///
6590/// Attaching the initializer here makes this declaration not externally
6591/// visible, because its type has internal linkage.
6592///
6593/// FIXME: This is a hack.
6594template<typename T>
6595static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6596 if (S.getLangOpts().CPlusPlus) {
6597 // In C++, the overloadable attribute negates the effects of extern "C".
6598 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6599 return false;
6600
6601 // So do CUDA's host/device attributes.
6602 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6603 D->template hasAttr<CUDAHostAttr>()))
6604 return false;
6605 }
6606 return D->isExternC();
6607}
6608
6609static bool shouldConsiderLinkage(const VarDecl *VD) {
6610 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6611 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6612 isa<OMPDeclareMapperDecl>(DC))
6613 return VD->hasExternalStorage();
6614 if (DC->isFileContext())
6615 return true;
6616 if (DC->isRecord())
6617 return false;
6618 if (isa<RequiresExprBodyDecl>(DC))
6619 return false;
6620 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6620)
;
6621}
6622
6623static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6624 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6625 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6626 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6627 return true;
6628 if (DC->isRecord())
6629 return false;
6630 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6630)
;
6631}
6632
6633static bool hasParsedAttr(Scope *S, const Declarator &PD,
6634 ParsedAttr::Kind Kind) {
6635 // Check decl attributes on the DeclSpec.
6636 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6637 return true;
6638
6639 // Walk the declarator structure, checking decl attributes that were in a type
6640 // position to the decl itself.
6641 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6642 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6643 return true;
6644 }
6645
6646 // Finally, check attributes on the decl itself.
6647 return PD.getAttributes().hasAttribute(Kind);
6648}
6649
6650/// Adjust the \c DeclContext for a function or variable that might be a
6651/// function-local external declaration.
6652bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6653 if (!DC->isFunctionOrMethod())
6654 return false;
6655
6656 // If this is a local extern function or variable declared within a function
6657 // template, don't add it into the enclosing namespace scope until it is
6658 // instantiated; it might have a dependent type right now.
6659 if (DC->isDependentContext())
6660 return true;
6661
6662 // C++11 [basic.link]p7:
6663 // When a block scope declaration of an entity with linkage is not found to
6664 // refer to some other declaration, then that entity is a member of the
6665 // innermost enclosing namespace.
6666 //
6667 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6668 // semantically-enclosing namespace, not a lexically-enclosing one.
6669 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6670 DC = DC->getParent();
6671 return true;
6672}
6673
6674/// Returns true if given declaration has external C language linkage.
6675static bool isDeclExternC(const Decl *D) {
6676 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6677 return FD->isExternC();
6678 if (const auto *VD = dyn_cast<VarDecl>(D))
6679 return VD->isExternC();
6680
6681 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6681)
;
6682}
6683/// Returns true if there hasn't been any invalid type diagnosed.
6684static bool diagnoseOpenCLTypes(Scope *S, Sema &Se, Declarator &D,
6685 DeclContext *DC, QualType R) {
6686 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6687 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6688 // argument.
6689 if (R->isImageType() || R->isPipeType()) {
6690 Se.Diag(D.getIdentifierLoc(),
6691 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6692 << R;
6693 D.setInvalidType();
6694 return false;
6695 }
6696
6697 // OpenCL v1.2 s6.9.r:
6698 // The event type cannot be used to declare a program scope variable.
6699 // OpenCL v2.0 s6.9.q:
6700 // The clk_event_t and reserve_id_t types cannot be declared in program
6701 // scope.
6702 if (NULL__null == S->getParent()) {
6703 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6704 Se.Diag(D.getIdentifierLoc(),
6705 diag::err_invalid_type_for_program_scope_var)
6706 << R;
6707 D.setInvalidType();
6708 return false;
6709 }
6710 }
6711
6712 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6713 QualType NR = R;
6714 while (NR->isPointerType()) {
6715 if (NR->isFunctionPointerType()) {
6716 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6717 D.setInvalidType();
6718 return false;
6719 }
6720 NR = NR->getPointeeType();
6721 }
6722
6723 if (!Se.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6724 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6725 // half array type (unless the cl_khr_fp16 extension is enabled).
6726 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6727 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6728 D.setInvalidType();
6729 return false;
6730 }
6731 }
6732
6733 // OpenCL v1.2 s6.9.r:
6734 // The event type cannot be used with the __local, __constant and __global
6735 // address space qualifiers.
6736 if (R->isEventT()) {
6737 if (R.getAddressSpace() != LangAS::opencl_private) {
6738 Se.Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6739 D.setInvalidType();
6740 return false;
6741 }
6742 }
6743
6744 // C++ for OpenCL does not allow the thread_local storage qualifier.
6745 // OpenCL C does not support thread_local either, and
6746 // also reject all other thread storage class specifiers.
6747 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6748 if (TSC != TSCS_unspecified) {
6749 bool IsCXX = Se.getLangOpts().OpenCLCPlusPlus;
6750 Se.Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6751 diag::err_opencl_unknown_type_specifier)
6752 << IsCXX << Se.getLangOpts().getOpenCLVersionTuple().getAsString()
6753 << DeclSpec::getSpecifierName(TSC) << 1;
6754 D.setInvalidType();
6755 return false;
6756 }
6757
6758 if (R->isSamplerT()) {
6759 // OpenCL v1.2 s6.9.b p4:
6760 // The sampler type cannot be used with the __local and __global address
6761 // space qualifiers.
6762 if (R.getAddressSpace() == LangAS::opencl_local ||
6763 R.getAddressSpace() == LangAS::opencl_global) {
6764 Se.Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6765 D.setInvalidType();
6766 }
6767
6768 // OpenCL v1.2 s6.12.14.1:
6769 // A global sampler must be declared with either the constant address
6770 // space qualifier or with the const qualifier.
6771 if (DC->isTranslationUnit() &&
6772 !(R.getAddressSpace() == LangAS::opencl_constant ||
6773 R.isConstQualified())) {
6774 Se.Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6775 D.setInvalidType();
6776 }
6777 if (D.isInvalidType())
6778 return false;
6779 }
6780 return true;
6781}
6782
6783NamedDecl *Sema::ActOnVariableDeclarator(
6784 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6785 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6786 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6787 QualType R = TInfo->getType();
6788 DeclarationName Name = GetNameForDeclarator(D).getName();
6789
6790 IdentifierInfo *II = Name.getAsIdentifierInfo();
6791
6792 if (D.isDecompositionDeclarator()) {
6793 // Take the name of the first declarator as our name for diagnostic
6794 // purposes.
6795 auto &Decomp = D.getDecompositionDeclarator();
6796 if (!Decomp.bindings().empty()) {
6797 II = Decomp.bindings()[0].Name;
6798 Name = II;
6799 }
6800 } else if (!II) {
6801 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6802 return nullptr;
6803 }
6804
6805
6806 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6807 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6808
6809 // dllimport globals without explicit storage class are treated as extern. We
6810 // have to change the storage class this early to get the right DeclContext.
6811 if (SC == SC_None && !DC->isRecord() &&
6812 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6813 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6814 SC = SC_Extern;
6815
6816 DeclContext *OriginalDC = DC;
6817 bool IsLocalExternDecl = SC == SC_Extern &&
6818 adjustContextForLocalExternDecl(DC);
6819
6820 if (SCSpec == DeclSpec::SCS_mutable) {
6821 // mutable can only appear on non-static class members, so it's always
6822 // an error here
6823 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6824 D.setInvalidType();
6825 SC = SC_None;
6826 }
6827
6828 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6829 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6830 D.getDeclSpec().getStorageClassSpecLoc())) {
6831 // In C++11, the 'register' storage class specifier is deprecated.
6832 // Suppress the warning in system macros, it's used in macros in some
6833 // popular C system headers, such as in glibc's htonl() macro.
6834 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6835 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6836 : diag::warn_deprecated_register)
6837 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6838 }
6839
6840 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6841
6842 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6843 // C99 6.9p2: The storage-class specifiers auto and register shall not
6844 // appear in the declaration specifiers in an external declaration.
6845 // Global Register+Asm is a GNU extension we support.
6846 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6847 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6848 D.setInvalidType();
6849 }
6850 }
6851
6852 bool IsMemberSpecialization = false;
6853 bool IsVariableTemplateSpecialization = false;
6854 bool IsPartialSpecialization = false;
6855 bool IsVariableTemplate = false;
6856 VarDecl *NewVD = nullptr;
6857 VarTemplateDecl *NewTemplate = nullptr;
6858 TemplateParameterList *TemplateParams = nullptr;
6859 if (!getLangOpts().CPlusPlus) {
6860 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6861 II, R, TInfo, SC);
6862
6863 if (R->getContainedDeducedType())
6864 ParsingInitForAutoVars.insert(NewVD);
6865
6866 if (D.isInvalidType())
6867 NewVD->setInvalidDecl();
6868
6869 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
6870 NewVD->hasLocalStorage())
6871 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
6872 NTCUC_AutoVar, NTCUK_Destruct);
6873 } else {
6874 bool Invalid = false;
6875
6876 if (DC->isRecord() && !CurContext->isRecord()) {
6877 // This is an out-of-line definition of a static data member.
6878 switch (SC) {
6879 case SC_None:
6880 break;
6881 case SC_Static:
6882 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6883 diag::err_static_out_of_line)
6884 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6885 break;
6886 case SC_Auto:
6887 case SC_Register:
6888 case SC_Extern:
6889 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6890 // to names of variables declared in a block or to function parameters.
6891 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6892 // of class members
6893
6894 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6895 diag::err_storage_class_for_static_member)
6896 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6897 break;
6898 case SC_PrivateExtern:
6899 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6899)
;
6900 }
6901 }
6902
6903 if (SC == SC_Static && CurContext->isRecord()) {
6904 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6905 // Walk up the enclosing DeclContexts to check for any that are
6906 // incompatible with static data members.
6907 const DeclContext *FunctionOrMethod = nullptr;
6908 const CXXRecordDecl *AnonStruct = nullptr;
6909 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
6910 if (Ctxt->isFunctionOrMethod()) {
6911 FunctionOrMethod = Ctxt;
6912 break;
6913 }
6914 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
6915 if (ParentDecl && !ParentDecl->getDeclName()) {
6916 AnonStruct = ParentDecl;
6917 break;
6918 }
6919 }
6920 if (FunctionOrMethod) {
6921 // C++ [class.static.data]p5: A local class shall not have static data
6922 // members.
6923 Diag(D.getIdentifierLoc(),
6924 diag::err_static_data_member_not_allowed_in_local_class)
6925 << Name << RD->getDeclName() << RD->getTagKind();
6926 } else if (AnonStruct) {
6927 // C++ [class.static.data]p4: Unnamed classes and classes contained
6928 // directly or indirectly within unnamed classes shall not contain
6929 // static data members.
6930 Diag(D.getIdentifierLoc(),
6931 diag::err_static_data_member_not_allowed_in_anon_struct)
6932 << Name << AnonStruct->getTagKind();
6933 Invalid = true;
6934 } else if (RD->isUnion()) {
6935 // C++98 [class.union]p1: If a union contains a static data member,
6936 // the program is ill-formed. C++11 drops this restriction.
6937 Diag(D.getIdentifierLoc(),
6938 getLangOpts().CPlusPlus11
6939 ? diag::warn_cxx98_compat_static_data_member_in_union
6940 : diag::ext_static_data_member_in_union) << Name;
6941 }
6942 }
6943 }
6944
6945 // Match up the template parameter lists with the scope specifier, then
6946 // determine whether we have a template or a template specialization.
6947 bool InvalidScope = false;
6948 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6949 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6950 D.getCXXScopeSpec(),
6951 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6952 ? D.getName().TemplateId
6953 : nullptr,
6954 TemplateParamLists,
6955 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
6956 Invalid |= InvalidScope;
6957
6958 if (TemplateParams) {
6959 if (!TemplateParams->size() &&
6960 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6961 // There is an extraneous 'template<>' for this variable. Complain
6962 // about it, but allow the declaration of the variable.
6963 Diag(TemplateParams->getTemplateLoc(),
6964 diag::err_template_variable_noparams)
6965 << II
6966 << SourceRange(TemplateParams->getTemplateLoc(),
6967 TemplateParams->getRAngleLoc());
6968 TemplateParams = nullptr;
6969 } else {
6970 // Check that we can declare a template here.
6971 if (CheckTemplateDeclScope(S, TemplateParams))
6972 return nullptr;
6973
6974 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6975 // This is an explicit specialization or a partial specialization.
6976 IsVariableTemplateSpecialization = true;
6977 IsPartialSpecialization = TemplateParams->size() > 0;
6978 } else { // if (TemplateParams->size() > 0)
6979 // This is a template declaration.
6980 IsVariableTemplate = true;
6981
6982 // Only C++1y supports variable templates (N3651).
6983 Diag(D.getIdentifierLoc(),
6984 getLangOpts().CPlusPlus14
6985 ? diag::warn_cxx11_compat_variable_template
6986 : diag::ext_variable_template);
6987 }
6988 }
6989 } else {
6990 // Check that we can declare a member specialization here.
6991 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
6992 CheckTemplateDeclScope(S, TemplateParamLists.back()))
6993 return nullptr;
6994 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6996, __PRETTY_FUNCTION__))
6995 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6996, __PRETTY_FUNCTION__))
6996 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 6996, __PRETTY_FUNCTION__))
;
6997 }
6998
6999 if (IsVariableTemplateSpecialization) {
7000 SourceLocation TemplateKWLoc =
7001 TemplateParamLists.size() > 0
7002 ? TemplateParamLists[0]->getTemplateLoc()
7003 : SourceLocation();
7004 DeclResult Res = ActOnVarTemplateSpecialization(
7005 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7006 IsPartialSpecialization);
7007 if (Res.isInvalid())
7008 return nullptr;
7009 NewVD = cast<VarDecl>(Res.get());
7010 AddToScope = false;
7011 } else if (D.isDecompositionDeclarator()) {
7012 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7013 D.getIdentifierLoc(), R, TInfo, SC,
7014 Bindings);
7015 } else
7016 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7017 D.getIdentifierLoc(), II, R, TInfo, SC);
7018
7019 // If this is supposed to be a variable template, create it as such.
7020 if (IsVariableTemplate) {
7021 NewTemplate =
7022 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7023 TemplateParams, NewVD);
7024 NewVD->setDescribedVarTemplate(NewTemplate);
7025 }
7026
7027 // If this decl has an auto type in need of deduction, make a note of the
7028 // Decl so we can diagnose uses of it in its own initializer.
7029 if (R->getContainedDeducedType())
7030 ParsingInitForAutoVars.insert(NewVD);
7031
7032 if (D.isInvalidType() || Invalid) {
7033 NewVD->setInvalidDecl();
7034 if (NewTemplate)
7035 NewTemplate->setInvalidDecl();
7036 }
7037
7038 SetNestedNameSpecifier(*this, NewVD, D);
7039
7040 // If we have any template parameter lists that don't directly belong to
7041 // the variable (matching the scope specifier), store them.
7042 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7043 if (TemplateParamLists.size() > VDTemplateParamLists)
7044 NewVD->setTemplateParameterListsInfo(
7045 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7046 }
7047
7048 if (D.getDeclSpec().isInlineSpecified()) {
7049 if (!getLangOpts().CPlusPlus) {
7050 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7051 << 0;
7052 } else if (CurContext->isFunctionOrMethod()) {
7053 // 'inline' is not allowed on block scope variable declaration.
7054 Diag(D.getDeclSpec().getInlineSpecLoc(),
7055 diag::err_inline_declaration_block_scope) << Name
7056 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7057 } else {
7058 Diag(D.getDeclSpec().getInlineSpecLoc(),
7059 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7060 : diag::ext_inline_variable);
7061 NewVD->setInlineSpecified();
7062 }
7063 }
7064
7065 // Set the lexical context. If the declarator has a C++ scope specifier, the
7066 // lexical context will be different from the semantic context.
7067 NewVD->setLexicalDeclContext(CurContext);
7068 if (NewTemplate)
7069 NewTemplate->setLexicalDeclContext(CurContext);
7070
7071 if (IsLocalExternDecl) {
7072 if (D.isDecompositionDeclarator())
7073 for (auto *B : Bindings)
7074 B->setLocalExternDecl();
7075 else
7076 NewVD->setLocalExternDecl();
7077 }
7078
7079 bool EmitTLSUnsupportedError = false;
7080 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7081 // C++11 [dcl.stc]p4:
7082 // When thread_local is applied to a variable of block scope the
7083 // storage-class-specifier static is implied if it does not appear
7084 // explicitly.
7085 // Core issue: 'static' is not implied if the variable is declared
7086 // 'extern'.
7087 if (NewVD->hasLocalStorage() &&
7088 (SCSpec != DeclSpec::SCS_unspecified ||
7089 TSCS != DeclSpec::TSCS_thread_local ||
7090 !DC->isFunctionOrMethod()))
7091 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7092 diag::err_thread_non_global)
7093 << DeclSpec::getSpecifierName(TSCS);
7094 else if (!Context.getTargetInfo().isTLSSupported()) {
7095 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7096 getLangOpts().SYCLIsDevice) {
7097 // Postpone error emission until we've collected attributes required to
7098 // figure out whether it's a host or device variable and whether the
7099 // error should be ignored.
7100 EmitTLSUnsupportedError = true;
7101 // We still need to mark the variable as TLS so it shows up in AST with
7102 // proper storage class for other tools to use even if we're not going
7103 // to emit any code for it.
7104 NewVD->setTSCSpec(TSCS);
7105 } else
7106 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7107 diag::err_thread_unsupported);
7108 } else
7109 NewVD->setTSCSpec(TSCS);
7110 }
7111
7112 switch (D.getDeclSpec().getConstexprSpecifier()) {
7113 case CSK_unspecified:
7114 break;
7115
7116 case CSK_consteval:
7117 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7118 diag::err_constexpr_wrong_decl_kind)
7119 << D.getDeclSpec().getConstexprSpecifier();
7120 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7121
7122 case CSK_constexpr:
7123 NewVD->setConstexpr(true);
7124 MaybeAddCUDAConstantAttr(NewVD);
7125 // C++1z [dcl.spec.constexpr]p1:
7126 // A static data member declared with the constexpr specifier is
7127 // implicitly an inline variable.
7128 if (NewVD->isStaticDataMember() &&
7129 (getLangOpts().CPlusPlus17 ||
7130 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7131 NewVD->setImplicitlyInline();
7132 break;
7133
7134 case CSK_constinit:
7135 if (!NewVD->hasGlobalStorage())
7136 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7137 diag::err_constinit_local_variable);
7138 else
7139 NewVD->addAttr(ConstInitAttr::Create(
7140 Context, D.getDeclSpec().getConstexprSpecLoc(),
7141 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7142 break;
7143 }
7144
7145 // C99 6.7.4p3
7146 // An inline definition of a function with external linkage shall
7147 // not contain a definition of a modifiable object with static or
7148 // thread storage duration...
7149 // We only apply this when the function is required to be defined
7150 // elsewhere, i.e. when the function is not 'extern inline'. Note
7151 // that a local variable with thread storage duration still has to
7152 // be marked 'static'. Also note that it's possible to get these
7153 // semantics in C++ using __attribute__((gnu_inline)).
7154 if (SC == SC_Static && S->getFnParent() != nullptr &&
7155 !NewVD->getType().isConstQualified()) {
7156 FunctionDecl *CurFD = getCurFunctionDecl();
7157 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7158 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7159 diag::warn_static_local_in_extern_inline);
7160 MaybeSuggestAddingStaticToDecl(CurFD);
7161 }
7162 }
7163
7164 if (D.getDeclSpec().isModulePrivateSpecified()) {
7165 if (IsVariableTemplateSpecialization)
7166 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7167 << (IsPartialSpecialization ? 1 : 0)
7168 << FixItHint::CreateRemoval(
7169 D.getDeclSpec().getModulePrivateSpecLoc());
7170 else if (IsMemberSpecialization)
7171 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7172 << 2
7173 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7174 else if (NewVD->hasLocalStorage())
7175 Diag(NewVD->getLocation(), diag::err_module_private_local)
7176 << 0 << NewVD
7177 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7178 << FixItHint::CreateRemoval(
7179 D.getDeclSpec().getModulePrivateSpecLoc());
7180 else {
7181 NewVD->setModulePrivate();
7182 if (NewTemplate)
7183 NewTemplate->setModulePrivate();
7184 for (auto *B : Bindings)
7185 B->setModulePrivate();
7186 }
7187 }
7188
7189 if (getLangOpts().OpenCL) {
7190
7191 deduceOpenCLAddressSpace(NewVD);
7192
7193 diagnoseOpenCLTypes(S, *this, D, DC, NewVD->getType());
7194 }
7195
7196 // Handle attributes prior to checking for duplicates in MergeVarDecl
7197 ProcessDeclAttributes(S, NewVD, D);
7198
7199 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7200 getLangOpts().SYCLIsDevice) {
7201 if (EmitTLSUnsupportedError &&
7202 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7203 (getLangOpts().OpenMPIsDevice &&
7204 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7205 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7206 diag::err_thread_unsupported);
7207
7208 if (EmitTLSUnsupportedError &&
7209 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7210 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7211 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7212 // storage [duration]."
7213 if (SC == SC_None && S->getFnParent() != nullptr &&
7214 (NewVD->hasAttr<CUDASharedAttr>() ||
7215 NewVD->hasAttr<CUDAConstantAttr>())) {
7216 NewVD->setStorageClass(SC_Static);
7217 }
7218 }
7219
7220 // Ensure that dllimport globals without explicit storage class are treated as
7221 // extern. The storage class is set above using parsed attributes. Now we can
7222 // check the VarDecl itself.
7223 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 7225, __PRETTY_FUNCTION__))
7224 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 7225, __PRETTY_FUNCTION__))
7225 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 7225, __PRETTY_FUNCTION__))
;
7226
7227 // In auto-retain/release, infer strong retension for variables of
7228 // retainable type.
7229 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7230 NewVD->setInvalidDecl();
7231
7232 // Handle GNU asm-label extension (encoded as an attribute).
7233 if (Expr *E = (Expr*)D.getAsmLabel()) {
7234 // The parser guarantees this is a string.
7235 StringLiteral *SE = cast<StringLiteral>(E);
7236 StringRef Label = SE->getString();
7237 if (S->getFnParent() != nullptr) {
7238 switch (SC) {
7239 case SC_None:
7240 case SC_Auto:
7241 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7242 break;
7243 case SC_Register:
7244 // Local Named register
7245 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7246 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7247 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7248 break;
7249 case SC_Static:
7250 case SC_Extern:
7251 case SC_PrivateExtern:
7252 break;
7253 }
7254 } else if (SC == SC_Register) {
7255 // Global Named register
7256 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7257 const auto &TI = Context.getTargetInfo();
7258 bool HasSizeMismatch;
7259
7260 if (!TI.isValidGCCRegisterName(Label))
7261 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7262 else if (!TI.validateGlobalRegisterVariable(Label,
7263 Context.getTypeSize(R),
7264 HasSizeMismatch))
7265 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7266 else if (HasSizeMismatch)
7267 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7268 }
7269
7270 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7271 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7272 NewVD->setInvalidDecl(true);
7273 }
7274 }
7275
7276 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7277 /*IsLiteralLabel=*/true,
7278 SE->getStrTokenLoc(0)));
7279 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7280 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7281 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7282 if (I != ExtnameUndeclaredIdentifiers.end()) {
7283 if (isDeclExternC(NewVD)) {
7284 NewVD->addAttr(I->second);
7285 ExtnameUndeclaredIdentifiers.erase(I);
7286 } else
7287 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7288 << /*Variable*/1 << NewVD;
7289 }
7290 }
7291
7292 // Find the shadowed declaration before filtering for scope.
7293 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7294 ? getShadowedDeclaration(NewVD, Previous)
7295 : nullptr;
7296
7297 // Don't consider existing declarations that are in a different
7298 // scope and are out-of-semantic-context declarations (if the new
7299 // declaration has linkage).
7300 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7301 D.getCXXScopeSpec().isNotEmpty() ||
7302 IsMemberSpecialization ||
7303 IsVariableTemplateSpecialization);
7304
7305 // Check whether the previous declaration is in the same block scope. This
7306 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7307 if (getLangOpts().CPlusPlus &&
7308 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7309 NewVD->setPreviousDeclInSameBlockScope(
7310 Previous.isSingleResult() && !Previous.isShadowed() &&
7311 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7312
7313 if (!getLangOpts().CPlusPlus) {
7314 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7315 } else {
7316 // If this is an explicit specialization of a static data member, check it.
7317 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7318 CheckMemberSpecialization(NewVD, Previous))
7319 NewVD->setInvalidDecl();
7320
7321 // Merge the decl with the existing one if appropriate.
7322 if (!Previous.empty()) {
7323 if (Previous.isSingleResult() &&
7324 isa<FieldDecl>(Previous.getFoundDecl()) &&
7325 D.getCXXScopeSpec().isSet()) {
7326 // The user tried to define a non-static data member
7327 // out-of-line (C++ [dcl.meaning]p1).
7328 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7329 << D.getCXXScopeSpec().getRange();
7330 Previous.clear();
7331 NewVD->setInvalidDecl();
7332 }
7333 } else if (D.getCXXScopeSpec().isSet()) {
7334 // No previous declaration in the qualifying scope.
7335 Diag(D.getIdentifierLoc(), diag::err_no_member)
7336 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7337 << D.getCXXScopeSpec().getRange();
7338 NewVD->setInvalidDecl();
7339 }
7340
7341 if (!IsVariableTemplateSpecialization)
7342 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7343
7344 if (NewTemplate) {
7345 VarTemplateDecl *PrevVarTemplate =
7346 NewVD->getPreviousDecl()
7347 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7348 : nullptr;
7349
7350 // Check the template parameter list of this declaration, possibly
7351 // merging in the template parameter list from the previous variable
7352 // template declaration.
7353 if (CheckTemplateParameterList(
7354 TemplateParams,
7355 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7356 : nullptr,
7357 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7358 DC->isDependentContext())
7359 ? TPC_ClassTemplateMember
7360 : TPC_VarTemplate))
7361 NewVD->setInvalidDecl();
7362
7363 // If we are providing an explicit specialization of a static variable
7364 // template, make a note of that.
7365 if (PrevVarTemplate &&
7366 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7367 PrevVarTemplate->setMemberSpecialization();
7368 }
7369 }
7370
7371 // Diagnose shadowed variables iff this isn't a redeclaration.
7372 if (ShadowedDecl && !D.isRedeclaration())
7373 CheckShadow(NewVD, ShadowedDecl, Previous);
7374
7375 ProcessPragmaWeak(S, NewVD);
7376
7377 // If this is the first declaration of an extern C variable, update
7378 // the map of such variables.
7379 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7380 isIncompleteDeclExternC(*this, NewVD))
7381 RegisterLocallyScopedExternCDecl(NewVD, S);
7382
7383 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7384 MangleNumberingContext *MCtx;
7385 Decl *ManglingContextDecl;
7386 std::tie(MCtx, ManglingContextDecl) =
7387 getCurrentMangleNumberContext(NewVD->getDeclContext());
7388 if (MCtx) {
7389 Context.setManglingNumber(
7390 NewVD, MCtx->getManglingNumber(
7391 NewVD, getMSManglingNumber(getLangOpts(), S)));
7392 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7393 }
7394 }
7395
7396 // Special handling of variable named 'main'.
7397 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7398 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7399 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7400
7401 // C++ [basic.start.main]p3
7402 // A program that declares a variable main at global scope is ill-formed.
7403 if (getLangOpts().CPlusPlus)
7404 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7405
7406 // In C, and external-linkage variable named main results in undefined
7407 // behavior.
7408 else if (NewVD->hasExternalFormalLinkage())
7409 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7410 }
7411
7412 if (D.isRedeclaration() && !Previous.empty()) {
7413 NamedDecl *Prev = Previous.getRepresentativeDecl();
7414 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7415 D.isFunctionDefinition());
7416 }
7417
7418 if (NewTemplate) {
7419 if (NewVD->isInvalidDecl())
7420 NewTemplate->setInvalidDecl();
7421 ActOnDocumentableDecl(NewTemplate);
7422 return NewTemplate;
7423 }
7424
7425 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7426 CompleteMemberSpecialization(NewVD, Previous);
7427
7428 return NewVD;
7429}
7430
7431/// Enum describing the %select options in diag::warn_decl_shadow.
7432enum ShadowedDeclKind {
7433 SDK_Local,
7434 SDK_Global,
7435 SDK_StaticMember,
7436 SDK_Field,
7437 SDK_Typedef,
7438 SDK_Using
7439};
7440
7441/// Determine what kind of declaration we're shadowing.
7442static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7443 const DeclContext *OldDC) {
7444 if (isa<TypeAliasDecl>(ShadowedDecl))
7445 return SDK_Using;
7446 else if (isa<TypedefDecl>(ShadowedDecl))
7447 return SDK_Typedef;
7448 else if (isa<RecordDecl>(OldDC))
7449 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7450
7451 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7452}
7453
7454/// Return the location of the capture if the given lambda captures the given
7455/// variable \p VD, or an invalid source location otherwise.
7456static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7457 const VarDecl *VD) {
7458 for (const Capture &Capture : LSI->Captures) {
7459 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7460 return Capture.getLocation();
7461 }
7462 return SourceLocation();
7463}
7464
7465static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7466 const LookupResult &R) {
7467 // Only diagnose if we're shadowing an unambiguous field or variable.
7468 if (R.getResultKind() != LookupResult::Found)
7469 return false;
7470
7471 // Return false if warning is ignored.
7472 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7473}
7474
7475/// Return the declaration shadowed by the given variable \p D, or null
7476/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7477NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7478 const LookupResult &R) {
7479 if (!shouldWarnIfShadowedDecl(Diags, R))
7480 return nullptr;
7481
7482 // Don't diagnose declarations at file scope.
7483 if (D->hasGlobalStorage())
7484 return nullptr;
7485
7486 NamedDecl *ShadowedDecl = R.getFoundDecl();
7487 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7488 ? ShadowedDecl
7489 : nullptr;
7490}
7491
7492/// Return the declaration shadowed by the given typedef \p D, or null
7493/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7494NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7495 const LookupResult &R) {
7496 // Don't warn if typedef declaration is part of a class
7497 if (D->getDeclContext()->isRecord())
7498 return nullptr;
7499
7500 if (!shouldWarnIfShadowedDecl(Diags, R))
7501 return nullptr;
7502
7503 NamedDecl *ShadowedDecl = R.getFoundDecl();
7504 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7505}
7506
7507/// Diagnose variable or built-in function shadowing. Implements
7508/// -Wshadow.
7509///
7510/// This method is called whenever a VarDecl is added to a "useful"
7511/// scope.
7512///
7513/// \param ShadowedDecl the declaration that is shadowed by the given variable
7514/// \param R the lookup of the name
7515///
7516void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7517 const LookupResult &R) {
7518 DeclContext *NewDC = D->getDeclContext();
7519
7520 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7521 // Fields are not shadowed by variables in C++ static methods.
7522 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7523 if (MD->isStatic())
7524 return;
7525
7526 // Fields shadowed by constructor parameters are a special case. Usually
7527 // the constructor initializes the field with the parameter.
7528 if (isa<CXXConstructorDecl>(NewDC))
7529 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7530 // Remember that this was shadowed so we can either warn about its
7531 // modification or its existence depending on warning settings.
7532 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7533 return;
7534 }
7535 }
7536
7537 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7538 if (shadowedVar->isExternC()) {
7539 // For shadowing external vars, make sure that we point to the global
7540 // declaration, not a locally scoped extern declaration.
7541 for (auto I : shadowedVar->redecls())
7542 if (I->isFileVarDecl()) {
7543 ShadowedDecl = I;
7544 break;
7545 }
7546 }
7547
7548 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7549
7550 unsigned WarningDiag = diag::warn_decl_shadow;
7551 SourceLocation CaptureLoc;
7552 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7553 isa<CXXMethodDecl>(NewDC)) {
7554 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7555 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7556 if (RD->getLambdaCaptureDefault() == LCD_None) {
7557 // Try to avoid warnings for lambdas with an explicit capture list.
7558 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7559 // Warn only when the lambda captures the shadowed decl explicitly.
7560 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7561 if (CaptureLoc.isInvalid())
7562 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7563 } else {
7564 // Remember that this was shadowed so we can avoid the warning if the
7565 // shadowed decl isn't captured and the warning settings allow it.
7566 cast<LambdaScopeInfo>(getCurFunction())
7567 ->ShadowingDecls.push_back(
7568 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7569 return;
7570 }
7571 }
7572
7573 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7574 // A variable can't shadow a local variable in an enclosing scope, if
7575 // they are separated by a non-capturing declaration context.
7576 for (DeclContext *ParentDC = NewDC;
7577 ParentDC && !ParentDC->Equals(OldDC);
7578 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7579 // Only block literals, captured statements, and lambda expressions
7580 // can capture; other scopes don't.
7581 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7582 !isLambdaCallOperator(ParentDC)) {
7583 return;
7584 }
7585 }
7586 }
7587 }
7588 }
7589
7590 // Only warn about certain kinds of shadowing for class members.
7591 if (NewDC && NewDC->isRecord()) {
7592 // In particular, don't warn about shadowing non-class members.
7593 if (!OldDC->isRecord())
7594 return;
7595
7596 // TODO: should we warn about static data members shadowing
7597 // static data members from base classes?
7598
7599 // TODO: don't diagnose for inaccessible shadowed members.
7600 // This is hard to do perfectly because we might friend the
7601 // shadowing context, but that's just a false negative.
7602 }
7603
7604
7605 DeclarationName Name = R.getLookupName();
7606
7607 // Emit warning and note.
7608 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7609 return;
7610 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7611 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7612 if (!CaptureLoc.isInvalid())
7613 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7614 << Name << /*explicitly*/ 1;
7615 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7616}
7617
7618/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7619/// when these variables are captured by the lambda.
7620void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7621 for (const auto &Shadow : LSI->ShadowingDecls) {
7622 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7623 // Try to avoid the warning when the shadowed decl isn't captured.
7624 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7625 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7626 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7627 ? diag::warn_decl_shadow_uncaptured_local
7628 : diag::warn_decl_shadow)
7629 << Shadow.VD->getDeclName()
7630 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7631 if (!CaptureLoc.isInvalid())
7632 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7633 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7634 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7635 }
7636}
7637
7638/// Check -Wshadow without the advantage of a previous lookup.
7639void Sema::CheckShadow(Scope *S, VarDecl *D) {
7640 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7641 return;
7642
7643 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7644 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7645 LookupName(R, S);
7646 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7647 CheckShadow(D, ShadowedDecl, R);
7648}
7649
7650/// Check if 'E', which is an expression that is about to be modified, refers
7651/// to a constructor parameter that shadows a field.
7652void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7653 // Quickly ignore expressions that can't be shadowing ctor parameters.
7654 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7655 return;
7656 E = E->IgnoreParenImpCasts();
7657 auto *DRE = dyn_cast<DeclRefExpr>(E);
7658 if (!DRE)
7659 return;
7660 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7661 auto I = ShadowingDecls.find(D);
7662 if (I == ShadowingDecls.end())
7663 return;
7664 const NamedDecl *ShadowedDecl = I->second;
7665 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7666 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7667 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7668 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7669
7670 // Avoid issuing multiple warnings about the same decl.
7671 ShadowingDecls.erase(I);
7672}
7673
7674/// Check for conflict between this global or extern "C" declaration and
7675/// previous global or extern "C" declarations. This is only used in C++.
7676template<typename T>
7677static bool checkGlobalOrExternCConflict(
7678 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7679 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 7679, __PRETTY_FUNCTION__))
;
7680 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7681
7682 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7683 // The common case: this global doesn't conflict with any extern "C"
7684 // declaration.
7685 return false;
7686 }
7687
7688 if (Prev) {
7689 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7690 // Both the old and new declarations have C language linkage. This is a
7691 // redeclaration.
7692 Previous.clear();
7693 Previous.addDecl(Prev);
7694 return true;
7695 }
7696
7697 // This is a global, non-extern "C" declaration, and there is a previous
7698 // non-global extern "C" declaration. Diagnose if this is a variable
7699 // declaration.
7700 if (!isa<VarDecl>(ND))
7701 return false;
7702 } else {
7703 // The declaration is extern "C". Check for any declaration in the
7704 // translation unit which might conflict.
7705 if (IsGlobal) {
7706 // We have already performed the lookup into the translation unit.
7707 IsGlobal = false;
7708 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7709 I != E; ++I) {
7710 if (isa<VarDecl>(*I)) {
7711 Prev = *I;
7712 break;
7713 }
7714 }
7715 } else {
7716 DeclContext::lookup_result R =
7717 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7718 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7719 I != E; ++I) {
7720 if (isa<VarDecl>(*I)) {
7721 Prev = *I;
7722 break;
7723 }
7724 // FIXME: If we have any other entity with this name in global scope,
7725 // the declaration is ill-formed, but that is a defect: it breaks the
7726 // 'stat' hack, for instance. Only variables can have mangled name
7727 // clashes with extern "C" declarations, so only they deserve a
7728 // diagnostic.
7729 }
7730 }
7731
7732 if (!Prev)
7733 return false;
7734 }
7735
7736 // Use the first declaration's location to ensure we point at something which
7737 // is lexically inside an extern "C" linkage-spec.
7738 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 7738, __PRETTY_FUNCTION__))
;
7739 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7740 Prev = FD->getFirstDecl();
7741 else
7742 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7743
7744 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7745 << IsGlobal << ND;
7746 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7747 << IsGlobal;
7748 return false;
7749}
7750
7751/// Apply special rules for handling extern "C" declarations. Returns \c true
7752/// if we have found that this is a redeclaration of some prior entity.
7753///
7754/// Per C++ [dcl.link]p6:
7755/// Two declarations [for a function or variable] with C language linkage
7756/// with the same name that appear in different scopes refer to the same
7757/// [entity]. An entity with C language linkage shall not be declared with
7758/// the same name as an entity in global scope.
7759template<typename T>
7760static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7761 LookupResult &Previous) {
7762 if (!S.getLangOpts().CPlusPlus) {
7763 // In C, when declaring a global variable, look for a corresponding 'extern'
7764 // variable declared in function scope. We don't need this in C++, because
7765 // we find local extern decls in the surrounding file-scope DeclContext.
7766 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7767 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7768 Previous.clear();
7769 Previous.addDecl(Prev);
7770 return true;
7771 }
7772 }
7773 return false;
7774 }
7775
7776 // A declaration in the translation unit can conflict with an extern "C"
7777 // declaration.
7778 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7779 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7780
7781 // An extern "C" declaration can conflict with a declaration in the
7782 // translation unit or can be a redeclaration of an extern "C" declaration
7783 // in another scope.
7784 if (isIncompleteDeclExternC(S,ND))
7785 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7786
7787 // Neither global nor extern "C": nothing to do.
7788 return false;
7789}
7790
7791void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7792 // If the decl is already known invalid, don't check it.
7793 if (NewVD->isInvalidDecl())
7794 return;
7795
7796 QualType T = NewVD->getType();
7797
7798 // Defer checking an 'auto' type until its initializer is attached.
7799 if (T->isUndeducedType())
7800 return;
7801
7802 if (NewVD->hasAttrs())
7803 CheckAlignasUnderalignment(NewVD);
7804
7805 if (T->isObjCObjectType()) {
7806 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7807 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7808 T = Context.getObjCObjectPointerType(T);
7809 NewVD->setType(T);
7810 }
7811
7812 // Emit an error if an address space was applied to decl with local storage.
7813 // This includes arrays of objects with address space qualifiers, but not
7814 // automatic variables that point to other address spaces.
7815 // ISO/IEC TR 18037 S5.1.2
7816 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7817 T.getAddressSpace() != LangAS::Default) {
7818 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7819 NewVD->setInvalidDecl();
7820 return;
7821 }
7822
7823 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7824 // scope.
7825 if (getLangOpts().OpenCLVersion == 120 &&
7826 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7827 NewVD->isStaticLocal()) {
7828 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7829 NewVD->setInvalidDecl();
7830 return;
7831 }
7832
7833 if (getLangOpts().OpenCL) {
7834 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7835 if (NewVD->hasAttr<BlocksAttr>()) {
7836 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7837 return;
7838 }
7839
7840 if (T->isBlockPointerType()) {
7841 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7842 // can't use 'extern' storage class.
7843 if (!T.isConstQualified()) {
7844 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7845 << 0 /*const*/;
7846 NewVD->setInvalidDecl();
7847 return;
7848 }
7849 if (NewVD->hasExternalStorage()) {
7850 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7851 NewVD->setInvalidDecl();
7852 return;
7853 }
7854 }
7855 // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7856 // __constant address space.
7857 // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7858 // variables inside a function can also be declared in the global
7859 // address space.
7860 // C++ for OpenCL inherits rule from OpenCL C v2.0.
7861 // FIXME: Adding local AS in C++ for OpenCL might make sense.
7862 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7863 NewVD->hasExternalStorage()) {
7864 if (!T->isSamplerT() &&
7865 !T->isDependentType() &&
7866 !(T.getAddressSpace() == LangAS::opencl_constant ||
7867 (T.getAddressSpace() == LangAS::opencl_global &&
7868 (getLangOpts().OpenCLVersion == 200 ||
7869 getLangOpts().OpenCLCPlusPlus)))) {
7870 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7871 if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7872 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7873 << Scope << "global or constant";
7874 else
7875 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7876 << Scope << "constant";
7877 NewVD->setInvalidDecl();
7878 return;
7879 }
7880 } else {
7881 if (T.getAddressSpace() == LangAS::opencl_global) {
7882 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7883 << 1 /*is any function*/ << "global";
7884 NewVD->setInvalidDecl();
7885 return;
7886 }
7887 if (T.getAddressSpace() == LangAS::opencl_constant ||
7888 T.getAddressSpace() == LangAS::opencl_local) {
7889 FunctionDecl *FD = getCurFunctionDecl();
7890 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7891 // in functions.
7892 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7893 if (T.getAddressSpace() == LangAS::opencl_constant)
7894 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7895 << 0 /*non-kernel only*/ << "constant";
7896 else
7897 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7898 << 0 /*non-kernel only*/ << "local";
7899 NewVD->setInvalidDecl();
7900 return;
7901 }
7902 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7903 // in the outermost scope of a kernel function.
7904 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7905 if (!getCurScope()->isFunctionScope()) {
7906 if (T.getAddressSpace() == LangAS::opencl_constant)
7907 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7908 << "constant";
7909 else
7910 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7911 << "local";
7912 NewVD->setInvalidDecl();
7913 return;
7914 }
7915 }
7916 } else if (T.getAddressSpace() != LangAS::opencl_private &&
7917 // If we are parsing a template we didn't deduce an addr
7918 // space yet.
7919 T.getAddressSpace() != LangAS::Default) {
7920 // Do not allow other address spaces on automatic variable.
7921 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7922 NewVD->setInvalidDecl();
7923 return;
7924 }
7925 }
7926 }
7927
7928 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7929 && !NewVD->hasAttr<BlocksAttr>()) {
7930 if (getLangOpts().getGC() != LangOptions::NonGC)
7931 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7932 else {
7933 assert(!getLangOpts().ObjCAutoRefCount)((!getLangOpts().ObjCAutoRefCount) ? static_cast<void> (
0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 7933, __PRETTY_FUNCTION__))
;
7934 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7935 }
7936 }
7937
7938 bool isVM = T->isVariablyModifiedType();
7939 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7940 NewVD->hasAttr<BlocksAttr>())
7941 setFunctionHasBranchProtectedScope();
7942
7943 if ((isVM && NewVD->hasLinkage()) ||
7944 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7945 bool SizeIsNegative;
7946 llvm::APSInt Oversized;
7947 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7948 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7949 QualType FixedT;
7950 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
7951 FixedT = FixedTInfo->getType();
7952 else if (FixedTInfo) {
7953 // Type and type-as-written are canonically different. We need to fix up
7954 // both types separately.
7955 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7956 Oversized);
7957 }
7958 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7959 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7960 // FIXME: This won't give the correct result for
7961 // int a[10][n];
7962 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7963
7964 if (NewVD->isFileVarDecl())
7965 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7966 << SizeRange;
7967 else if (NewVD->isStaticLocal())
7968 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7969 << SizeRange;
7970 else
7971 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7972 << SizeRange;
7973 NewVD->setInvalidDecl();
7974 return;
7975 }
7976
7977 if (!FixedTInfo) {
7978 if (NewVD->isFileVarDecl())
7979 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7980 else
7981 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7982 NewVD->setInvalidDecl();
7983 return;
7984 }
7985
7986 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7987 NewVD->setType(FixedT);
7988 NewVD->setTypeSourceInfo(FixedTInfo);
7989 }
7990
7991 if (T->isVoidType()) {
7992 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7993 // of objects and functions.
7994 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7995 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7996 << T;
7997 NewVD->setInvalidDecl();
7998 return;
7999 }
8000 }
8001
8002 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8003 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8004 NewVD->setInvalidDecl();
8005 return;
8006 }
8007
8008 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8009 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8010 NewVD->setInvalidDecl();
8011 return;
8012 }
8013
8014 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8015 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8016 NewVD->setInvalidDecl();
8017 return;
8018 }
8019
8020 if (NewVD->isConstexpr() && !T->isDependentType() &&
8021 RequireLiteralType(NewVD->getLocation(), T,
8022 diag::err_constexpr_var_non_literal)) {
8023 NewVD->setInvalidDecl();
8024 return;
8025 }
8026}
8027
8028/// Perform semantic checking on a newly-created variable
8029/// declaration.
8030///
8031/// This routine performs all of the type-checking required for a
8032/// variable declaration once it has been built. It is used both to
8033/// check variables after they have been parsed and their declarators
8034/// have been translated into a declaration, and to check variables
8035/// that have been instantiated from a template.
8036///
8037/// Sets NewVD->isInvalidDecl() if an error was encountered.
8038///
8039/// Returns true if the variable declaration is a redeclaration.
8040bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8041 CheckVariableDeclarationType(NewVD);
8042
8043 // If the decl is already known invalid, don't check it.
8044 if (NewVD->isInvalidDecl())
8045 return false;
8046
8047 // If we did not find anything by this name, look for a non-visible
8048 // extern "C" declaration with the same name.
8049 if (Previous.empty() &&
8050 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8051 Previous.setShadowed();
8052
8053 if (!Previous.empty()) {
8054 MergeVarDecl(NewVD, Previous);
8055 return true;
8056 }
8057 return false;
8058}
8059
8060namespace {
8061struct FindOverriddenMethod {
8062 Sema *S;
8063 CXXMethodDecl *Method;
8064
8065 /// Member lookup function that determines whether a given C++
8066 /// method overrides a method in a base class, to be used with
8067 /// CXXRecordDecl::lookupInBases().
8068 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8069 RecordDecl *BaseRecord =
8070 Specifier->getType()->castAs<RecordType>()->getDecl();
8071
8072 DeclarationName Name = Method->getDeclName();
8073
8074 // FIXME: Do we care about other names here too?
8075 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8076 // We really want to find the base class destructor here.
8077 QualType T = S->Context.getTypeDeclType(BaseRecord);
8078 CanQualType CT = S->Context.getCanonicalType(T);
8079
8080 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
8081 }
8082
8083 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
8084 Path.Decls = Path.Decls.slice(1)) {
8085 NamedDecl *D = Path.Decls.front();
8086 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
8087 if (MD->isVirtual() &&
8088 !S->IsOverload(
8089 Method, MD, /*UseMemberUsingDeclRules=*/false,
8090 /*ConsiderCudaAttrs=*/true,
8091 // C++2a [class.virtual]p2 does not consider requires clauses
8092 // when overriding.
8093 /*ConsiderRequiresClauses=*/false))
8094 return true;
8095 }
8096 }
8097
8098 return false;
8099 }
8100};
8101} // end anonymous namespace
8102
8103/// AddOverriddenMethods - See if a method overrides any in the base classes,
8104/// and if so, check that it's a valid override and remember it.
8105bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8106 // Look for methods in base classes that this method might override.
8107 CXXBasePaths Paths;
8108 FindOverriddenMethod FOM;
8109 FOM.Method = MD;
8110 FOM.S = this;
8111 bool AddedAny = false;
8112 if (DC->lookupInBases(FOM, Paths)) {
8113 for (auto *I : Paths.found_decls()) {
8114 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
8115 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
8116 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
8117 !CheckOverridingFunctionAttributes(MD, OldMD) &&
8118 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
8119 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
8120 AddedAny = true;
8121 }
8122 }
8123 }
8124 }
8125
8126 return AddedAny;
8127}
8128
8129namespace {
8130 // Struct for holding all of the extra arguments needed by
8131 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8132 struct ActOnFDArgs {
8133 Scope *S;
8134 Declarator &D;
8135 MultiTemplateParamsArg TemplateParamLists;
8136 bool AddToScope;
8137 };
8138} // end anonymous namespace
8139
8140namespace {
8141
8142// Callback to only accept typo corrections that have a non-zero edit distance.
8143// Also only accept corrections that have the same parent decl.
8144class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8145 public:
8146 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8147 CXXRecordDecl *Parent)
8148 : Context(Context), OriginalFD(TypoFD),
8149 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8150
8151 bool ValidateCandidate(const TypoCorrection &candidate) override {
8152 if (candidate.getEditDistance() == 0)
8153 return false;
8154
8155 SmallVector<unsigned, 1> MismatchedParams;
8156 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8157 CDeclEnd = candidate.end();
8158 CDecl != CDeclEnd; ++CDecl) {
8159 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8160
8161 if (FD && !FD->hasBody() &&
8162 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8163 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8164 CXXRecordDecl *Parent = MD->getParent();
8165 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8166 return true;
8167 } else if (!ExpectedParent) {
8168 return true;
8169 }
8170 }
8171 }
8172
8173 return false;
8174 }
8175
8176 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8177 return std::make_unique<DifferentNameValidatorCCC>(*this);
8178 }
8179
8180 private:
8181 ASTContext &Context;
8182 FunctionDecl *OriginalFD;
8183 CXXRecordDecl *ExpectedParent;
8184};
8185
8186} // end anonymous namespace
8187
8188void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8189 TypoCorrectedFunctionDefinitions.insert(F);
8190}
8191
8192/// Generate diagnostics for an invalid function redeclaration.
8193///
8194/// This routine handles generating the diagnostic messages for an invalid
8195/// function redeclaration, including finding possible similar declarations
8196/// or performing typo correction if there are no previous declarations with
8197/// the same name.
8198///
8199/// Returns a NamedDecl iff typo correction was performed and substituting in
8200/// the new declaration name does not cause new errors.
8201static NamedDecl *DiagnoseInvalidRedeclaration(
8202 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8203 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8204 DeclarationName Name = NewFD->getDeclName();
8205 DeclContext *NewDC = NewFD->getDeclContext();
8206 SmallVector<unsigned, 1> MismatchedParams;
8207 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8208 TypoCorrection Correction;
8209 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8210 unsigned DiagMsg =
8211 IsLocalFriend ? diag::err_no_matching_local_friend :
8212 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8213 diag::err_member_decl_does_not_match;
8214 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8215 IsLocalFriend ? Sema::LookupLocalFriendName
8216 : Sema::LookupOrdinaryName,
8217 Sema::ForVisibleRedeclaration);
8218
8219 NewFD->setInvalidDecl();
8220 if (IsLocalFriend)
8221 SemaRef.LookupName(Prev, S);
8222 else
8223 SemaRef.LookupQualifiedName(Prev, NewDC);
8224 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8225, __PRETTY_FUNCTION__))
8225 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8225, __PRETTY_FUNCTION__))
;
8226 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8227 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8228 MD ? MD->getParent() : nullptr);
8229 if (!Prev.empty()) {
8230 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8231 Func != FuncEnd; ++Func) {
8232 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8233 if (FD &&
8234 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8235 // Add 1 to the index so that 0 can mean the mismatch didn't
8236 // involve a parameter
8237 unsigned ParamNum =
8238 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8239 NearMatches.push_back(std::make_pair(FD, ParamNum));
8240 }
8241 }
8242 // If the qualified name lookup yielded nothing, try typo correction
8243 } else if ((Correction = SemaRef.CorrectTypo(
8244 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8245 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8246 IsLocalFriend ? nullptr : NewDC))) {
8247 // Set up everything for the call to ActOnFunctionDeclarator
8248 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8249 ExtraArgs.D.getIdentifierLoc());
8250 Previous.clear();
8251 Previous.setLookupName(Correction.getCorrection());
8252 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8253 CDeclEnd = Correction.end();
8254 CDecl != CDeclEnd; ++CDecl) {
8255 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8256 if (FD && !FD->hasBody() &&
8257 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8258 Previous.addDecl(FD);
8259 }
8260 }
8261 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8262
8263 NamedDecl *Result;
8264 // Retry building the function declaration with the new previous
8265 // declarations, and with errors suppressed.
8266 {
8267 // Trap errors.
8268 Sema::SFINAETrap Trap(SemaRef);
8269
8270 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8271 // pieces need to verify the typo-corrected C++ declaration and hopefully
8272 // eliminate the need for the parameter pack ExtraArgs.
8273 Result = SemaRef.ActOnFunctionDeclarator(
8274 ExtraArgs.S, ExtraArgs.D,
8275 Correction.getCorrectionDecl()->getDeclContext(),
8276 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8277 ExtraArgs.AddToScope);
8278
8279 if (Trap.hasErrorOccurred())
8280 Result = nullptr;
8281 }
8282
8283 if (Result) {
8284 // Determine which correction we picked.
8285 Decl *Canonical = Result->getCanonicalDecl();
8286 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8287 I != E; ++I)
8288 if ((*I)->getCanonicalDecl() == Canonical)
8289 Correction.setCorrectionDecl(*I);
8290
8291 // Let Sema know about the correction.
8292 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8293 SemaRef.diagnoseTypo(
8294 Correction,
8295 SemaRef.PDiag(IsLocalFriend
8296 ? diag::err_no_matching_local_friend_suggest
8297 : diag::err_member_decl_does_not_match_suggest)
8298 << Name << NewDC << IsDefinition);
8299 return Result;
8300 }
8301
8302 // Pretend the typo correction never occurred
8303 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8304 ExtraArgs.D.getIdentifierLoc());
8305 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8306 Previous.clear();
8307 Previous.setLookupName(Name);
8308 }
8309
8310 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8311 << Name << NewDC << IsDefinition << NewFD->getLocation();
8312
8313 bool NewFDisConst = false;
8314 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8315 NewFDisConst = NewMD->isConst();
8316
8317 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8318 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8319 NearMatch != NearMatchEnd; ++NearMatch) {
8320 FunctionDecl *FD = NearMatch->first;
8321 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8322 bool FDisConst = MD && MD->isConst();
8323 bool IsMember = MD || !IsLocalFriend;
8324
8325 // FIXME: These notes are poorly worded for the local friend case.
8326 if (unsigned Idx = NearMatch->second) {
8327 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8328 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8329 if (Loc.isInvalid()) Loc = FD->getLocation();
8330 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8331 : diag::note_local_decl_close_param_match)
8332 << Idx << FDParam->getType()
8333 << NewFD->getParamDecl(Idx - 1)->getType();
8334 } else if (FDisConst != NewFDisConst) {
8335 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8336 << NewFDisConst << FD->getSourceRange().getEnd();
8337 } else
8338 SemaRef.Diag(FD->getLocation(),
8339 IsMember ? diag::note_member_def_close_match
8340 : diag::note_local_decl_close_match);
8341 }
8342 return nullptr;
8343}
8344
8345static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8346 switch (D.getDeclSpec().getStorageClassSpec()) {
8347 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8347)
;
8348 case DeclSpec::SCS_auto:
8349 case DeclSpec::SCS_register:
8350 case DeclSpec::SCS_mutable:
8351 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8352 diag::err_typecheck_sclass_func);
8353 D.getMutableDeclSpec().ClearStorageClassSpecs();
8354 D.setInvalidType();
8355 break;
8356 case DeclSpec::SCS_unspecified: break;
8357 case DeclSpec::SCS_extern:
8358 if (D.getDeclSpec().isExternInLinkageSpec())
8359 return SC_None;
8360 return SC_Extern;
8361 case DeclSpec::SCS_static: {
8362 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8363 // C99 6.7.1p5:
8364 // The declaration of an identifier for a function that has
8365 // block scope shall have no explicit storage-class specifier
8366 // other than extern
8367 // See also (C++ [dcl.stc]p4).
8368 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8369 diag::err_static_block_func);
8370 break;
8371 } else
8372 return SC_Static;
8373 }
8374 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8375 }
8376
8377 // No explicit storage class has already been returned
8378 return SC_None;
8379}
8380
8381static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8382 DeclContext *DC, QualType &R,
8383 TypeSourceInfo *TInfo,
8384 StorageClass SC,
8385 bool &IsVirtualOkay) {
8386 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8387 DeclarationName Name = NameInfo.getName();
8388
8389 FunctionDecl *NewFD = nullptr;
8390 bool isInline = D.getDeclSpec().isInlineSpecified();
8391
8392 if (!SemaRef.getLangOpts().CPlusPlus) {
8393 // Determine whether the function was written with a
8394 // prototype. This true when:
8395 // - there is a prototype in the declarator, or
8396 // - the type R of the function is some kind of typedef or other non-
8397 // attributed reference to a type name (which eventually refers to a
8398 // function type).
8399 bool HasPrototype =
8400 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8401 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8402
8403 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8404 R, TInfo, SC, isInline, HasPrototype,
8405 CSK_unspecified,
8406 /*TrailingRequiresClause=*/nullptr);
8407 if (D.isInvalidType())
8408 NewFD->setInvalidDecl();
8409
8410 return NewFD;
8411 }
8412
8413 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8414
8415 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8416 if (ConstexprKind == CSK_constinit) {
8417 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8418 diag::err_constexpr_wrong_decl_kind)
8419 << ConstexprKind;
8420 ConstexprKind = CSK_unspecified;
8421 D.getMutableDeclSpec().ClearConstexprSpec();
8422 }
8423 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8424
8425 // Check that the return type is not an abstract class type.
8426 // For record types, this is done by the AbstractClassUsageDiagnoser once
8427 // the class has been completely parsed.
8428 if (!DC->isRecord() &&
8429 SemaRef.RequireNonAbstractType(
8430 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8431 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8432 D.setInvalidType();
8433
8434 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8435 // This is a C++ constructor declaration.
8436 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8437, __PRETTY_FUNCTION__))
8437 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8437, __PRETTY_FUNCTION__))
;
8438
8439 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8440 return CXXConstructorDecl::Create(
8441 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8442 TInfo, ExplicitSpecifier, isInline,
8443 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8444 TrailingRequiresClause);
8445
8446 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8447 // This is a C++ destructor declaration.
8448 if (DC->isRecord()) {
8449 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8450 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8451 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8452 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8453 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8454 TrailingRequiresClause);
8455
8456 // If the destructor needs an implicit exception specification, set it
8457 // now. FIXME: It'd be nice to be able to create the right type to start
8458 // with, but the type needs to reference the destructor declaration.
8459 if (SemaRef.getLangOpts().CPlusPlus11)
8460 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8461
8462 IsVirtualOkay = true;
8463 return NewDD;
8464
8465 } else {
8466 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8467 D.setInvalidType();
8468
8469 // Create a FunctionDecl to satisfy the function definition parsing
8470 // code path.
8471 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8472 D.getIdentifierLoc(), Name, R, TInfo, SC,
8473 isInline,
8474 /*hasPrototype=*/true, ConstexprKind,
8475 TrailingRequiresClause);
8476 }
8477
8478 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8479 if (!DC->isRecord()) {
8480 SemaRef.Diag(D.getIdentifierLoc(),
8481 diag::err_conv_function_not_member);
8482 return nullptr;
8483 }
8484
8485 SemaRef.CheckConversionDeclarator(D, R, SC);
8486 if (D.isInvalidType())
8487 return nullptr;
8488
8489 IsVirtualOkay = true;
8490 return CXXConversionDecl::Create(
8491 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8492 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8493 TrailingRequiresClause);
8494
8495 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8496 if (TrailingRequiresClause)
8497 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8498 diag::err_trailing_requires_clause_on_deduction_guide)
8499 << TrailingRequiresClause->getSourceRange();
8500 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8501
8502 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8503 ExplicitSpecifier, NameInfo, R, TInfo,
8504 D.getEndLoc());
8505 } else if (DC->isRecord()) {
8506 // If the name of the function is the same as the name of the record,
8507 // then this must be an invalid constructor that has a return type.
8508 // (The parser checks for a return type and makes the declarator a
8509 // constructor if it has no return type).
8510 if (Name.getAsIdentifierInfo() &&
8511 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8512 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8513 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8514 << SourceRange(D.getIdentifierLoc());
8515 return nullptr;
8516 }
8517
8518 // This is a C++ method declaration.
8519 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8520 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8521 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8522 TrailingRequiresClause);
8523 IsVirtualOkay = !Ret->isStatic();
8524 return Ret;
8525 } else {
8526 bool isFriend =
8527 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8528 if (!isFriend && SemaRef.CurContext->isRecord())
8529 return nullptr;
8530
8531 // Determine whether the function was written with a
8532 // prototype. This true when:
8533 // - we're in C++ (where every function has a prototype),
8534 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8535 R, TInfo, SC, isInline, true /*HasPrototype*/,
8536 ConstexprKind, TrailingRequiresClause);
8537 }
8538}
8539
8540enum OpenCLParamType {
8541 ValidKernelParam,
8542 PtrPtrKernelParam,
8543 PtrKernelParam,
8544 InvalidAddrSpacePtrKernelParam,
8545 InvalidKernelParam,
8546 RecordKernelParam
8547};
8548
8549static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8550 // Size dependent types are just typedefs to normal integer types
8551 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8552 // integers other than by their names.
8553 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8554
8555 // Remove typedefs one by one until we reach a typedef
8556 // for a size dependent type.
8557 QualType DesugaredTy = Ty;
8558 do {
8559 ArrayRef<StringRef> Names(SizeTypeNames);
8560 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8561 if (Names.end() != Match)
8562 return true;
8563
8564 Ty = DesugaredTy;
8565 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8566 } while (DesugaredTy != Ty);
8567
8568 return false;
8569}
8570
8571static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8572 if (PT->isPointerType()) {
8573 QualType PointeeType = PT->getPointeeType();
8574 if (PointeeType->isPointerType())
8575 return PtrPtrKernelParam;
8576 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8577 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8578 PointeeType.getAddressSpace() == LangAS::Default)
8579 return InvalidAddrSpacePtrKernelParam;
8580 return PtrKernelParam;
8581 }
8582
8583 // OpenCL v1.2 s6.9.k:
8584 // Arguments to kernel functions in a program cannot be declared with the
8585 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8586 // uintptr_t or a struct and/or union that contain fields declared to be one
8587 // of these built-in scalar types.
8588 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8589 return InvalidKernelParam;
8590
8591 if (PT->isImageType())
8592 return PtrKernelParam;
8593
8594 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8595 return InvalidKernelParam;
8596
8597 // OpenCL extension spec v1.2 s9.5:
8598 // This extension adds support for half scalar and vector types as built-in
8599 // types that can be used for arithmetic operations, conversions etc.
8600 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8601 return InvalidKernelParam;
8602
8603 if (PT->isRecordType())
8604 return RecordKernelParam;
8605
8606 // Look into an array argument to check if it has a forbidden type.
8607 if (PT->isArrayType()) {
8608 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8609 // Call ourself to check an underlying type of an array. Since the
8610 // getPointeeOrArrayElementType returns an innermost type which is not an
8611 // array, this recursive call only happens once.
8612 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8613 }
8614
8615 return ValidKernelParam;
8616}
8617
8618static void checkIsValidOpenCLKernelParameter(
8619 Sema &S,
8620 Declarator &D,
8621 ParmVarDecl *Param,
8622 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8623 QualType PT = Param->getType();
8624
8625 // Cache the valid types we encounter to avoid rechecking structs that are
8626 // used again
8627 if (ValidTypes.count(PT.getTypePtr()))
8628 return;
8629
8630 switch (getOpenCLKernelParameterType(S, PT)) {
8631 case PtrPtrKernelParam:
8632 // OpenCL v1.2 s6.9.a:
8633 // A kernel function argument cannot be declared as a
8634 // pointer to a pointer type.
8635 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8636 D.setInvalidType();
8637 return;
8638
8639 case InvalidAddrSpacePtrKernelParam:
8640 // OpenCL v1.0 s6.5:
8641 // __kernel function arguments declared to be a pointer of a type can point
8642 // to one of the following address spaces only : __global, __local or
8643 // __constant.
8644 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8645 D.setInvalidType();
8646 return;
8647
8648 // OpenCL v1.2 s6.9.k:
8649 // Arguments to kernel functions in a program cannot be declared with the
8650 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8651 // uintptr_t or a struct and/or union that contain fields declared to be
8652 // one of these built-in scalar types.
8653
8654 case InvalidKernelParam:
8655 // OpenCL v1.2 s6.8 n:
8656 // A kernel function argument cannot be declared
8657 // of event_t type.
8658 // Do not diagnose half type since it is diagnosed as invalid argument
8659 // type for any function elsewhere.
8660 if (!PT->isHalfType()) {
8661 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8662
8663 // Explain what typedefs are involved.
8664 const TypedefType *Typedef = nullptr;
8665 while ((Typedef = PT->getAs<TypedefType>())) {
8666 SourceLocation Loc = Typedef->getDecl()->getLocation();
8667 // SourceLocation may be invalid for a built-in type.
8668 if (Loc.isValid())
8669 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8670 PT = Typedef->desugar();
8671 }
8672 }
8673
8674 D.setInvalidType();
8675 return;
8676
8677 case PtrKernelParam:
8678 case ValidKernelParam:
8679 ValidTypes.insert(PT.getTypePtr());
8680 return;
8681
8682 case RecordKernelParam:
8683 break;
8684 }
8685
8686 // Track nested structs we will inspect
8687 SmallVector<const Decl *, 4> VisitStack;
8688
8689 // Track where we are in the nested structs. Items will migrate from
8690 // VisitStack to HistoryStack as we do the DFS for bad field.
8691 SmallVector<const FieldDecl *, 4> HistoryStack;
8692 HistoryStack.push_back(nullptr);
8693
8694 // At this point we already handled everything except of a RecordType or
8695 // an ArrayType of a RecordType.
8696 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8696, __PRETTY_FUNCTION__))
;
8697 const RecordType *RecTy =
8698 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8699 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8700
8701 VisitStack.push_back(RecTy->getDecl());
8702 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8702, __PRETTY_FUNCTION__))
;
8703
8704 do {
8705 const Decl *Next = VisitStack.pop_back_val();
8706 if (!Next) {
8707 assert(!HistoryStack.empty())((!HistoryStack.empty()) ? static_cast<void> (0) : __assert_fail
("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8707, __PRETTY_FUNCTION__))
;
8708 // Found a marker, we have gone up a level
8709 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8710 ValidTypes.insert(Hist->getType().getTypePtr());
8711
8712 continue;
8713 }
8714
8715 // Adds everything except the original parameter declaration (which is not a
8716 // field itself) to the history stack.
8717 const RecordDecl *RD;
8718 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8719 HistoryStack.push_back(Field);
8720
8721 QualType FieldTy = Field->getType();
8722 // Other field types (known to be valid or invalid) are handled while we
8723 // walk around RecordDecl::fields().
8724 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8725, __PRETTY_FUNCTION__))
8725 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8725, __PRETTY_FUNCTION__))
;
8726 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8727
8728 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8729 } else {
8730 RD = cast<RecordDecl>(Next);
8731 }
8732
8733 // Add a null marker so we know when we've gone back up a level
8734 VisitStack.push_back(nullptr);
8735
8736 for (const auto *FD : RD->fields()) {
8737 QualType QT = FD->getType();
8738
8739 if (ValidTypes.count(QT.getTypePtr()))
8740 continue;
8741
8742 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8743 if (ParamType == ValidKernelParam)
8744 continue;
8745
8746 if (ParamType == RecordKernelParam) {
8747 VisitStack.push_back(FD);
8748 continue;
8749 }
8750
8751 // OpenCL v1.2 s6.9.p:
8752 // Arguments to kernel functions that are declared to be a struct or union
8753 // do not allow OpenCL objects to be passed as elements of the struct or
8754 // union.
8755 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8756 ParamType == InvalidAddrSpacePtrKernelParam) {
8757 S.Diag(Param->getLocation(),
8758 diag::err_record_with_pointers_kernel_param)
8759 << PT->isUnionType()
8760 << PT;
8761 } else {
8762 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8763 }
8764
8765 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8766 << OrigRecDecl->getDeclName();
8767
8768 // We have an error, now let's go back up through history and show where
8769 // the offending field came from
8770 for (ArrayRef<const FieldDecl *>::const_iterator
8771 I = HistoryStack.begin() + 1,
8772 E = HistoryStack.end();
8773 I != E; ++I) {
8774 const FieldDecl *OuterField = *I;
8775 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8776 << OuterField->getType();
8777 }
8778
8779 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8780 << QT->isPointerType()
8781 << QT;
8782 D.setInvalidType();
8783 return;
8784 }
8785 } while (!VisitStack.empty());
8786}
8787
8788/// Find the DeclContext in which a tag is implicitly declared if we see an
8789/// elaborated type specifier in the specified context, and lookup finds
8790/// nothing.
8791static DeclContext *getTagInjectionContext(DeclContext *DC) {
8792 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8793 DC = DC->getParent();
8794 return DC;
8795}
8796
8797/// Find the Scope in which a tag is implicitly declared if we see an
8798/// elaborated type specifier in the specified context, and lookup finds
8799/// nothing.
8800static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8801 while (S->isClassScope() ||
8802 (LangOpts.CPlusPlus &&
8803 S->isFunctionPrototypeScope()) ||
8804 ((S->getFlags() & Scope::DeclScope) == 0) ||
8805 (S->getEntity() && S->getEntity()->isTransparentContext()))
8806 S = S->getParent();
8807 return S;
8808}
8809
8810NamedDecl*
8811Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8812 TypeSourceInfo *TInfo, LookupResult &Previous,
8813 MultiTemplateParamsArg TemplateParamListsRef,
8814 bool &AddToScope) {
8815 QualType R = TInfo->getType();
8816
8817 assert(R->isFunctionType())((R->isFunctionType()) ? static_cast<void> (0) : __assert_fail
("R->isFunctionType()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 8817, __PRETTY_FUNCTION__))
;
8818 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
8819 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
8820
8821 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
8822 for (TemplateParameterList *TPL : TemplateParamListsRef)
8823 TemplateParamLists.push_back(TPL);
8824 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
8825 if (!TemplateParamLists.empty() &&
8826 Invented->getDepth() == TemplateParamLists.back()->getDepth())
8827 TemplateParamLists.back() = Invented;
8828 else
8829 TemplateParamLists.push_back(Invented);
8830 }
8831
8832 // TODO: consider using NameInfo for diagnostic.
8833 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8834 DeclarationName Name = NameInfo.getName();
8835 StorageClass SC = getFunctionStorageClass(*this, D);
8836
8837 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8838 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8839 diag::err_invalid_thread)
8840 << DeclSpec::getSpecifierName(TSCS);
8841
8842 if (D.isFirstDeclarationOfMember())
8843 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8844 D.getIdentifierLoc());
8845
8846 bool isFriend = false;
8847 FunctionTemplateDecl *FunctionTemplate = nullptr;
8848 bool isMemberSpecialization = false;
8849 bool isFunctionTemplateSpecialization = false;
8850
8851 bool isDependentClassScopeExplicitSpecialization = false;
8852 bool HasExplicitTemplateArgs = false;
8853 TemplateArgumentListInfo TemplateArgs;
8854
8855 bool isVirtualOkay = false;
8856
8857 DeclContext *OriginalDC = DC;
8858 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8859
8860 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8861 isVirtualOkay);
8862 if (!NewFD) return nullptr;
8863
8864 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8865 NewFD->setTopLevelDeclInObjCContainer();
8866
8867 // Set the lexical context. If this is a function-scope declaration, or has a
8868 // C++ scope specifier, or is the object of a friend declaration, the lexical
8869 // context will be different from the semantic context.
8870 NewFD->setLexicalDeclContext(CurContext);
8871
8872 if (IsLocalExternDecl)
8873 NewFD->setLocalExternDecl();
8874
8875 if (getLangOpts().CPlusPlus) {
8876 bool isInline = D.getDeclSpec().isInlineSpecified();
8877 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8878 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
8879 isFriend = D.getDeclSpec().isFriendSpecified();
8880 if (isFriend && !isInline && D.isFunctionDefinition()) {
8881 // C++ [class.friend]p5
8882 // A function can be defined in a friend declaration of a
8883 // class . . . . Such a function is implicitly inline.
8884 NewFD->setImplicitlyInline();
8885 }
8886
8887 // If this is a method defined in an __interface, and is not a constructor
8888 // or an overloaded operator, then set the pure flag (isVirtual will already
8889 // return true).
8890 if (const CXXRecordDecl *Parent =
8891 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8892 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8893 NewFD->setPure(true);
8894
8895 // C++ [class.union]p2
8896 // A union can have member functions, but not virtual functions.
8897 if (isVirtual && Parent->isUnion())
8898 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8899 }
8900
8901 SetNestedNameSpecifier(*this, NewFD, D);
8902 isMemberSpecialization = false;
8903 isFunctionTemplateSpecialization = false;
8904 if (D.isInvalidType())
8905 NewFD->setInvalidDecl();
8906
8907 // Match up the template parameter lists with the scope specifier, then
8908 // determine whether we have a template or a template specialization.
8909 bool Invalid = false;
8910 TemplateParameterList *TemplateParams =
8911 MatchTemplateParametersToScopeSpecifier(
8912 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8913 D.getCXXScopeSpec(),
8914 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8915 ? D.getName().TemplateId
8916 : nullptr,
8917 TemplateParamLists, isFriend, isMemberSpecialization,
8918 Invalid);
8919 if (TemplateParams) {
8920 // Check that we can declare a template here.
8921 if (CheckTemplateDeclScope(S, TemplateParams))
8922 NewFD->setInvalidDecl();
8923
8924 if (TemplateParams->size() > 0) {
8925 // This is a function template
8926
8927 // A destructor cannot be a template.
8928 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8929 Diag(NewFD->getLocation(), diag::err_destructor_template);
8930 NewFD->setInvalidDecl();
8931 }
8932
8933 // If we're adding a template to a dependent context, we may need to
8934 // rebuilding some of the types used within the template parameter list,
8935 // now that we know what the current instantiation is.
8936 if (DC->isDependentContext()) {
8937 ContextRAII SavedContext(*this, DC);
8938 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8939 Invalid = true;
8940 }
8941
8942 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8943 NewFD->getLocation(),
8944 Name, TemplateParams,
8945 NewFD);
8946 FunctionTemplate->setLexicalDeclContext(CurContext);
8947 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8948
8949 // For source fidelity, store the other template param lists.
8950 if (TemplateParamLists.size() > 1) {
8951 NewFD->setTemplateParameterListsInfo(Context,
8952 ArrayRef<TemplateParameterList *>(TemplateParamLists)
8953 .drop_back(1));
8954 }
8955 } else {
8956 // This is a function template specialization.
8957 isFunctionTemplateSpecialization = true;
8958 // For source fidelity, store all the template param lists.
8959 if (TemplateParamLists.size() > 0)
8960 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8961
8962 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8963 if (isFriend) {
8964 // We want to remove the "template<>", found here.
8965 SourceRange RemoveRange = TemplateParams->getSourceRange();
8966
8967 // If we remove the template<> and the name is not a
8968 // template-id, we're actually silently creating a problem:
8969 // the friend declaration will refer to an untemplated decl,
8970 // and clearly the user wants a template specialization. So
8971 // we need to insert '<>' after the name.
8972 SourceLocation InsertLoc;
8973 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8974 InsertLoc = D.getName().getSourceRange().getEnd();
8975 InsertLoc = getLocForEndOfToken(InsertLoc);
8976 }
8977
8978 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8979 << Name << RemoveRange
8980 << FixItHint::CreateRemoval(RemoveRange)
8981 << FixItHint::CreateInsertion(InsertLoc, "<>");
8982 }
8983 }
8984 } else {
8985 // Check that we can declare a template here.
8986 if (!TemplateParamLists.empty() && isMemberSpecialization &&
8987 CheckTemplateDeclScope(S, TemplateParamLists.back()))
8988 NewFD->setInvalidDecl();
8989
8990 // All template param lists were matched against the scope specifier:
8991 // this is NOT (an explicit specialization of) a template.
8992 if (TemplateParamLists.size() > 0)
8993 // For source fidelity, store all the template param lists.
8994 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8995 }
8996
8997 if (Invalid) {
8998 NewFD->setInvalidDecl();
8999 if (FunctionTemplate)
9000 FunctionTemplate->setInvalidDecl();
9001 }
9002
9003 // C++ [dcl.fct.spec]p5:
9004 // The virtual specifier shall only be used in declarations of
9005 // nonstatic class member functions that appear within a
9006 // member-specification of a class declaration; see 10.3.
9007 //
9008 if (isVirtual && !NewFD->isInvalidDecl()) {
9009 if (!isVirtualOkay) {
9010 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9011 diag::err_virtual_non_function);
9012 } else if (!CurContext->isRecord()) {
9013 // 'virtual' was specified outside of the class.
9014 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9015 diag::err_virtual_out_of_class)
9016 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9017 } else if (NewFD->getDescribedFunctionTemplate()) {
9018 // C++ [temp.mem]p3:
9019 // A member function template shall not be virtual.
9020 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9021 diag::err_virtual_member_function_template)
9022 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9023 } else {
9024 // Okay: Add virtual to the method.
9025 NewFD->setVirtualAsWritten(true);
9026 }
9027
9028 if (getLangOpts().CPlusPlus14 &&
9029 NewFD->getReturnType()->isUndeducedType())
9030 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9031 }
9032
9033 if (getLangOpts().CPlusPlus14 &&
9034 (NewFD->isDependentContext() ||
9035 (isFriend && CurContext->isDependentContext())) &&
9036 NewFD->getReturnType()->isUndeducedType()) {
9037 // If the function template is referenced directly (for instance, as a
9038 // member of the current instantiation), pretend it has a dependent type.
9039 // This is not really justified by the standard, but is the only sane
9040 // thing to do.
9041 // FIXME: For a friend function, we have not marked the function as being
9042 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9043 const FunctionProtoType *FPT =
9044 NewFD->getType()->castAs<FunctionProtoType>();
9045 QualType Result =
9046 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9047 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9048 FPT->getExtProtoInfo()));
9049 }
9050
9051 // C++ [dcl.fct.spec]p3:
9052 // The inline specifier shall not appear on a block scope function
9053 // declaration.
9054 if (isInline && !NewFD->isInvalidDecl()) {
9055 if (CurContext->isFunctionOrMethod()) {
9056 // 'inline' is not allowed on block scope function declaration.
9057 Diag(D.getDeclSpec().getInlineSpecLoc(),
9058 diag::err_inline_declaration_block_scope) << Name
9059 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9060 }
9061 }
9062
9063 // C++ [dcl.fct.spec]p6:
9064 // The explicit specifier shall be used only in the declaration of a
9065 // constructor or conversion function within its class definition;
9066 // see 12.3.1 and 12.3.2.
9067 if (hasExplicit && !NewFD->isInvalidDecl() &&
9068 !isa<CXXDeductionGuideDecl>(NewFD)) {
9069 if (!CurContext->isRecord()) {
9070 // 'explicit' was specified outside of the class.
9071 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9072 diag::err_explicit_out_of_class)
9073 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9074 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9075 !isa<CXXConversionDecl>(NewFD)) {
9076 // 'explicit' was specified on a function that wasn't a constructor
9077 // or conversion function.
9078 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9079 diag::err_explicit_non_ctor_or_conv_function)
9080 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9081 }
9082 }
9083
9084 if (ConstexprSpecKind ConstexprKind =
9085 D.getDeclSpec().getConstexprSpecifier()) {
9086 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9087 // are implicitly inline.
9088 NewFD->setImplicitlyInline();
9089
9090 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9091 // be either constructors or to return a literal type. Therefore,
9092 // destructors cannot be declared constexpr.
9093 if (isa<CXXDestructorDecl>(NewFD) &&
9094 (!getLangOpts().CPlusPlus20 || ConstexprKind == CSK_consteval)) {
9095 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9096 << ConstexprKind;
9097 NewFD->setConstexprKind(getLangOpts().CPlusPlus20 ? CSK_unspecified : CSK_constexpr);
9098 }
9099 // C++20 [dcl.constexpr]p2: An allocation function, or a
9100 // deallocation function shall not be declared with the consteval
9101 // specifier.
9102 if (ConstexprKind == CSK_consteval &&
9103 (NewFD->getOverloadedOperator() == OO_New ||
9104 NewFD->getOverloadedOperator() == OO_Array_New ||
9105 NewFD->getOverloadedOperator() == OO_Delete ||
9106 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9107 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9108 diag::err_invalid_consteval_decl_kind)
9109 << NewFD;
9110 NewFD->setConstexprKind(CSK_constexpr);
9111 }
9112 }
9113
9114 // If __module_private__ was specified, mark the function accordingly.
9115 if (D.getDeclSpec().isModulePrivateSpecified()) {
9116 if (isFunctionTemplateSpecialization) {
9117 SourceLocation ModulePrivateLoc
9118 = D.getDeclSpec().getModulePrivateSpecLoc();
9119 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9120 << 0
9121 << FixItHint::CreateRemoval(ModulePrivateLoc);
9122 } else {
9123 NewFD->setModulePrivate();
9124 if (FunctionTemplate)
9125 FunctionTemplate->setModulePrivate();
9126 }
9127 }
9128
9129 if (isFriend) {
9130 if (FunctionTemplate) {
9131 FunctionTemplate->setObjectOfFriendDecl();
9132 FunctionTemplate->setAccess(AS_public);
9133 }
9134 NewFD->setObjectOfFriendDecl();
9135 NewFD->setAccess(AS_public);
9136 }
9137
9138 // If a function is defined as defaulted or deleted, mark it as such now.
9139 // We'll do the relevant checks on defaulted / deleted functions later.
9140 switch (D.getFunctionDefinitionKind()) {
9141 case FDK_Declaration:
9142 case FDK_Definition:
9143 break;
9144
9145 case FDK_Defaulted:
9146 NewFD->setDefaulted();
9147 break;
9148
9149 case FDK_Deleted:
9150 NewFD->setDeletedAsWritten();
9151 break;
9152 }
9153
9154 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9155 D.isFunctionDefinition()) {
9156 // C++ [class.mfct]p2:
9157 // A member function may be defined (8.4) in its class definition, in
9158 // which case it is an inline member function (7.1.2)
9159 NewFD->setImplicitlyInline();
9160 }
9161
9162 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9163 !CurContext->isRecord()) {
9164 // C++ [class.static]p1:
9165 // A data or function member of a class may be declared static
9166 // in a class definition, in which case it is a static member of
9167 // the class.
9168
9169 // Complain about the 'static' specifier if it's on an out-of-line
9170 // member function definition.
9171
9172 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9173 // member function template declaration and class member template
9174 // declaration (MSVC versions before 2015), warn about this.
9175 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9176 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9177 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9178 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9179 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9180 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9181 }
9182
9183 // C++11 [except.spec]p15:
9184 // A deallocation function with no exception-specification is treated
9185 // as if it were specified with noexcept(true).
9186 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9187 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9188 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9189 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9190 NewFD->setType(Context.getFunctionType(
9191 FPT->getReturnType(), FPT->getParamTypes(),
9192 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9193 }
9194
9195 // Filter out previous declarations that don't match the scope.
9196 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9197 D.getCXXScopeSpec().isNotEmpty() ||
9198 isMemberSpecialization ||
9199 isFunctionTemplateSpecialization);
9200
9201 // Handle GNU asm-label extension (encoded as an attribute).
9202 if (Expr *E = (Expr*) D.getAsmLabel()) {
9203 // The parser guarantees this is a string.
9204 StringLiteral *SE = cast<StringLiteral>(E);
9205 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9206 /*IsLiteralLabel=*/true,
9207 SE->getStrTokenLoc(0)));
9208 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9209 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9210 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9211 if (I != ExtnameUndeclaredIdentifiers.end()) {
9212 if (isDeclExternC(NewFD)) {
9213 NewFD->addAttr(I->second);
9214 ExtnameUndeclaredIdentifiers.erase(I);
9215 } else
9216 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9217 << /*Variable*/0 << NewFD;
9218 }
9219 }
9220
9221 // Copy the parameter declarations from the declarator D to the function
9222 // declaration NewFD, if they are available. First scavenge them into Params.
9223 SmallVector<ParmVarDecl*, 16> Params;
9224 unsigned FTIIdx;
9225 if (D.isFunctionDeclarator(FTIIdx)) {
9226 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9227
9228 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9229 // function that takes no arguments, not a function that takes a
9230 // single void argument.
9231 // We let through "const void" here because Sema::GetTypeForDeclarator
9232 // already checks for that case.
9233 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9234 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9235 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9236 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9236, __PRETTY_FUNCTION__))
;
9237 Param->setDeclContext(NewFD);
9238 Params.push_back(Param);
9239
9240 if (Param->isInvalidDecl())
9241 NewFD->setInvalidDecl();
9242 }
9243 }
9244
9245 if (!getLangOpts().CPlusPlus) {
9246 // In C, find all the tag declarations from the prototype and move them
9247 // into the function DeclContext. Remove them from the surrounding tag
9248 // injection context of the function, which is typically but not always
9249 // the TU.
9250 DeclContext *PrototypeTagContext =
9251 getTagInjectionContext(NewFD->getLexicalDeclContext());
9252 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9253 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9254
9255 // We don't want to reparent enumerators. Look at their parent enum
9256 // instead.
9257 if (!TD) {
9258 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9259 TD = cast<EnumDecl>(ECD->getDeclContext());
9260 }
9261 if (!TD)
9262 continue;
9263 DeclContext *TagDC = TD->getLexicalDeclContext();
9264 if (!TagDC->containsDecl(TD))
9265 continue;
9266 TagDC->removeDecl(TD);
9267 TD->setDeclContext(NewFD);
9268 NewFD->addDecl(TD);
9269
9270 // Preserve the lexical DeclContext if it is not the surrounding tag
9271 // injection context of the FD. In this example, the semantic context of
9272 // E will be f and the lexical context will be S, while both the
9273 // semantic and lexical contexts of S will be f:
9274 // void f(struct S { enum E { a } f; } s);
9275 if (TagDC != PrototypeTagContext)
9276 TD->setLexicalDeclContext(TagDC);
9277 }
9278 }
9279 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9280 // When we're declaring a function with a typedef, typeof, etc as in the
9281 // following example, we'll need to synthesize (unnamed)
9282 // parameters for use in the declaration.
9283 //
9284 // @code
9285 // typedef void fn(int);
9286 // fn f;
9287 // @endcode
9288
9289 // Synthesize a parameter for each argument type.
9290 for (const auto &AI : FT->param_types()) {
9291 ParmVarDecl *Param =
9292 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9293 Param->setScopeInfo(0, Params.size());
9294 Params.push_back(Param);
9295 }
9296 } else {
9297 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9298, __PRETTY_FUNCTION__))
9298 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9298, __PRETTY_FUNCTION__))
;
9299 }
9300
9301 // Finally, we know we have the right number of parameters, install them.
9302 NewFD->setParams(Params);
9303
9304 if (D.getDeclSpec().isNoreturnSpecified())
9305 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9306 D.getDeclSpec().getNoreturnSpecLoc(),
9307 AttributeCommonInfo::AS_Keyword));
9308
9309 // Functions returning a variably modified type violate C99 6.7.5.2p2
9310 // because all functions have linkage.
9311 if (!NewFD->isInvalidDecl() &&
9312 NewFD->getReturnType()->isVariablyModifiedType()) {
9313 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9314 NewFD->setInvalidDecl();
9315 }
9316
9317 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9318 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9319 !NewFD->hasAttr<SectionAttr>())
9320 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9321 Context, PragmaClangTextSection.SectionName,
9322 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9323
9324 // Apply an implicit SectionAttr if #pragma code_seg is active.
9325 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9326 !NewFD->hasAttr<SectionAttr>()) {
9327 NewFD->addAttr(SectionAttr::CreateImplicit(
9328 Context, CodeSegStack.CurrentValue->getString(),
9329 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9330 SectionAttr::Declspec_allocate));
9331 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9332 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9333 ASTContext::PSF_Read,
9334 NewFD))
9335 NewFD->dropAttr<SectionAttr>();
9336 }
9337
9338 // Apply an implicit CodeSegAttr from class declspec or
9339 // apply an implicit SectionAttr from #pragma code_seg if active.
9340 if (!NewFD->hasAttr<CodeSegAttr>()) {
9341 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9342 D.isFunctionDefinition())) {
9343 NewFD->addAttr(SAttr);
9344 }
9345 }
9346
9347 // Handle attributes.
9348 ProcessDeclAttributes(S, NewFD, D);
9349
9350 if (getLangOpts().OpenCL) {
9351 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9352 // type declaration will generate a compilation error.
9353 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9354 if (AddressSpace != LangAS::Default) {
9355 Diag(NewFD->getLocation(),
9356 diag::err_opencl_return_value_with_address_space);
9357 NewFD->setInvalidDecl();
9358 }
9359 }
9360
9361 if (!getLangOpts().CPlusPlus) {
9362 // Perform semantic checking on the function declaration.
9363 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9364 CheckMain(NewFD, D.getDeclSpec());
9365
9366 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9367 CheckMSVCRTEntryPoint(NewFD);
9368
9369 if (!NewFD->isInvalidDecl())
9370 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9371 isMemberSpecialization));
9372 else if (!Previous.empty())
9373 // Recover gracefully from an invalid redeclaration.
9374 D.setRedeclaration(true);
9375 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9377, __PRETTY_FUNCTION__))
9376 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9377, __PRETTY_FUNCTION__))
9377 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9377, __PRETTY_FUNCTION__))
;
9378
9379 // Diagnose no-prototype function declarations with calling conventions that
9380 // don't support variadic calls. Only do this in C and do it after merging
9381 // possibly prototyped redeclarations.
9382 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9383 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9384 CallingConv CC = FT->getExtInfo().getCC();
9385 if (!supportsVariadicCall(CC)) {
9386 // Windows system headers sometimes accidentally use stdcall without
9387 // (void) parameters, so we relax this to a warning.
9388 int DiagID =
9389 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9390 Diag(NewFD->getLocation(), DiagID)
9391 << FunctionType::getNameForCallConv(CC);
9392 }
9393 }
9394
9395 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9396 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9397 checkNonTrivialCUnion(NewFD->getReturnType(),
9398 NewFD->getReturnTypeSourceRange().getBegin(),
9399 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9400 } else {
9401 // C++11 [replacement.functions]p3:
9402 // The program's definitions shall not be specified as inline.
9403 //
9404 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9405 //
9406 // Suppress the diagnostic if the function is __attribute__((used)), since
9407 // that forces an external definition to be emitted.
9408 if (D.getDeclSpec().isInlineSpecified() &&
9409 NewFD->isReplaceableGlobalAllocationFunction() &&
9410 !NewFD->hasAttr<UsedAttr>())
9411 Diag(D.getDeclSpec().getInlineSpecLoc(),
9412 diag::ext_operator_new_delete_declared_inline)
9413 << NewFD->getDeclName();
9414
9415 // If the declarator is a template-id, translate the parser's template
9416 // argument list into our AST format.
9417 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9418 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9419 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9420 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9421 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9422 TemplateId->NumArgs);
9423 translateTemplateArguments(TemplateArgsPtr,
9424 TemplateArgs);
9425
9426 HasExplicitTemplateArgs = true;
9427
9428 if (NewFD->isInvalidDecl()) {
9429 HasExplicitTemplateArgs = false;
9430 } else if (FunctionTemplate) {
9431 // Function template with explicit template arguments.
9432 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9433 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9434
9435 HasExplicitTemplateArgs = false;
9436 } else {
9437 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9439, __PRETTY_FUNCTION__))
9438 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9439, __PRETTY_FUNCTION__))
9439 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9439, __PRETTY_FUNCTION__))
;
9440 // "friend void foo<>(int);" is an implicit specialization decl.
9441 isFunctionTemplateSpecialization = true;
9442 }
9443 } else if (isFriend && isFunctionTemplateSpecialization) {
9444 // This combination is only possible in a recovery case; the user
9445 // wrote something like:
9446 // template <> friend void foo(int);
9447 // which we're recovering from as if the user had written:
9448 // friend void foo<>(int);
9449 // Go ahead and fake up a template id.
9450 HasExplicitTemplateArgs = true;
9451 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9452 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9453 }
9454
9455 // We do not add HD attributes to specializations here because
9456 // they may have different constexpr-ness compared to their
9457 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9458 // may end up with different effective targets. Instead, a
9459 // specialization inherits its target attributes from its template
9460 // in the CheckFunctionTemplateSpecialization() call below.
9461 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9462 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9463
9464 // If it's a friend (and only if it's a friend), it's possible
9465 // that either the specialized function type or the specialized
9466 // template is dependent, and therefore matching will fail. In
9467 // this case, don't check the specialization yet.
9468 bool InstantiationDependent = false;
9469 if (isFunctionTemplateSpecialization && isFriend &&
9470 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9471 TemplateSpecializationType::anyDependentTemplateArguments(
9472 TemplateArgs,
9473 InstantiationDependent))) {
9474 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9475, __PRETTY_FUNCTION__))
9475 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9475, __PRETTY_FUNCTION__))
;
9476 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9477 Previous))
9478 NewFD->setInvalidDecl();
9479 } else if (isFunctionTemplateSpecialization) {
9480 if (CurContext->isDependentContext() && CurContext->isRecord()
9481 && !isFriend) {
9482 isDependentClassScopeExplicitSpecialization = true;
9483 } else if (!NewFD->isInvalidDecl() &&
9484 CheckFunctionTemplateSpecialization(
9485 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9486 Previous))
9487 NewFD->setInvalidDecl();
9488
9489 // C++ [dcl.stc]p1:
9490 // A storage-class-specifier shall not be specified in an explicit
9491 // specialization (14.7.3)
9492 FunctionTemplateSpecializationInfo *Info =
9493 NewFD->getTemplateSpecializationInfo();
9494 if (Info && SC != SC_None) {
9495 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9496 Diag(NewFD->getLocation(),
9497 diag::err_explicit_specialization_inconsistent_storage_class)
9498 << SC
9499 << FixItHint::CreateRemoval(
9500 D.getDeclSpec().getStorageClassSpecLoc());
9501
9502 else
9503 Diag(NewFD->getLocation(),
9504 diag::ext_explicit_specialization_storage_class)
9505 << FixItHint::CreateRemoval(
9506 D.getDeclSpec().getStorageClassSpecLoc());
9507 }
9508 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9509 if (CheckMemberSpecialization(NewFD, Previous))
9510 NewFD->setInvalidDecl();
9511 }
9512
9513 // Perform semantic checking on the function declaration.
9514 if (!isDependentClassScopeExplicitSpecialization) {
9515 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9516 CheckMain(NewFD, D.getDeclSpec());
9517
9518 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9519 CheckMSVCRTEntryPoint(NewFD);
9520
9521 if (!NewFD->isInvalidDecl())
9522 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9523 isMemberSpecialization));
9524 else if (!Previous.empty())
9525 // Recover gracefully from an invalid redeclaration.
9526 D.setRedeclaration(true);
9527 }
9528
9529 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9531, __PRETTY_FUNCTION__))
9530 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9531, __PRETTY_FUNCTION__))
9531 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 9531, __PRETTY_FUNCTION__))
;
9532
9533 NamedDecl *PrincipalDecl = (FunctionTemplate
9534 ? cast<NamedDecl>(FunctionTemplate)
9535 : NewFD);
9536
9537 if (isFriend && NewFD->getPreviousDecl()) {
9538 AccessSpecifier Access = AS_public;
9539 if (!NewFD->isInvalidDecl())
9540 Access = NewFD->getPreviousDecl()->getAccess();
9541
9542 NewFD->setAccess(Access);
9543 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9544 }
9545
9546 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9547 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9548 PrincipalDecl->setNonMemberOperator();
9549
9550 // If we have a function template, check the template parameter
9551 // list. This will check and merge default template arguments.
9552 if (FunctionTemplate) {
9553 FunctionTemplateDecl *PrevTemplate =
9554 FunctionTemplate->getPreviousDecl();
9555 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9556 PrevTemplate ? PrevTemplate->getTemplateParameters()
9557 : nullptr,
9558 D.getDeclSpec().isFriendSpecified()
9559 ? (D.isFunctionDefinition()
9560 ? TPC_FriendFunctionTemplateDefinition
9561 : TPC_FriendFunctionTemplate)
9562 : (D.getCXXScopeSpec().isSet() &&
9563 DC && DC->isRecord() &&
9564 DC->isDependentContext())
9565 ? TPC_ClassTemplateMember
9566 : TPC_FunctionTemplate);
9567 }
9568
9569 if (NewFD->isInvalidDecl()) {
9570 // Ignore all the rest of this.
9571 } else if (!D.isRedeclaration()) {
9572 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9573 AddToScope };
9574 // Fake up an access specifier if it's supposed to be a class member.
9575 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9576 NewFD->setAccess(AS_public);
9577
9578 // Qualified decls generally require a previous declaration.
9579 if (D.getCXXScopeSpec().isSet()) {
9580 // ...with the major exception of templated-scope or
9581 // dependent-scope friend declarations.
9582
9583 // TODO: we currently also suppress this check in dependent
9584 // contexts because (1) the parameter depth will be off when
9585 // matching friend templates and (2) we might actually be
9586 // selecting a friend based on a dependent factor. But there
9587 // are situations where these conditions don't apply and we
9588 // can actually do this check immediately.
9589 //
9590 // Unless the scope is dependent, it's always an error if qualified
9591 // redeclaration lookup found nothing at all. Diagnose that now;
9592 // nothing will diagnose that error later.
9593 if (isFriend &&
9594 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9595 (!Previous.empty() && CurContext->isDependentContext()))) {
9596 // ignore these
9597 } else {
9598 // The user tried to provide an out-of-line definition for a
9599 // function that is a member of a class or namespace, but there
9600 // was no such member function declared (C++ [class.mfct]p2,
9601 // C++ [namespace.memdef]p2). For example:
9602 //
9603 // class X {
9604 // void f() const;
9605 // };
9606 //
9607 // void X::f() { } // ill-formed
9608 //
9609 // Complain about this problem, and attempt to suggest close
9610 // matches (e.g., those that differ only in cv-qualifiers and
9611 // whether the parameter types are references).
9612
9613 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9614 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9615 AddToScope = ExtraArgs.AddToScope;
9616 return Result;
9617 }
9618 }
9619
9620 // Unqualified local friend declarations are required to resolve
9621 // to something.
9622 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9623 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9624 *this, Previous, NewFD, ExtraArgs, true, S)) {
9625 AddToScope = ExtraArgs.AddToScope;
9626 return Result;
9627 }
9628 }
9629 } else if (!D.isFunctionDefinition() &&
9630 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9631 !isFriend && !isFunctionTemplateSpecialization &&
9632 !isMemberSpecialization) {
9633 // An out-of-line member function declaration must also be a
9634 // definition (C++ [class.mfct]p2).
9635 // Note that this is not the case for explicit specializations of
9636 // function templates or member functions of class templates, per
9637 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9638 // extension for compatibility with old SWIG code which likes to
9639 // generate them.
9640 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9641 << D.getCXXScopeSpec().getRange();
9642 }
9643 }
9644
9645 // In C builtins get merged with implicitly lazily created declarations.
9646 // In C++ we need to check if it's a builtin and add the BuiltinAttr here.
9647 if (getLangOpts().CPlusPlus) {
9648 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9649 if (unsigned BuiltinID = II->getBuiltinID()) {
9650 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9651 // Declarations for builtins with custom typechecking by definition
9652 // don't make sense. Don't attempt typechecking and simply add the
9653 // attribute.
9654 if (Context.BuiltinInfo.hasCustomTypechecking(BuiltinID)) {
9655 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9656 } else {
9657 ASTContext::GetBuiltinTypeError Error;
9658 LookupNecessaryTypesForBuiltin(S, BuiltinID);
9659 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9660
9661 if (!Error && !BuiltinType.isNull() &&
9662 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9663 NewFD->getType(), BuiltinType))
9664 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9665 }
9666 } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9667 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9668 // FIXME: We should consider this a builtin only in the std namespace.
9669 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9670 }
9671 }
9672 }
9673 }
9674
9675 ProcessPragmaWeak(S, NewFD);
9676 checkAttributesAfterMerging(*this, *NewFD);
9677
9678 AddKnownFunctionAttributes(NewFD);
9679
9680 if (NewFD->hasAttr<OverloadableAttr>() &&
9681 !NewFD->getType()->getAs<FunctionProtoType>()) {
9682 Diag(NewFD->getLocation(),
9683 diag::err_attribute_overloadable_no_prototype)
9684 << NewFD;
9685
9686 // Turn this into a variadic function with no parameters.
9687 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9688 FunctionProtoType::ExtProtoInfo EPI(
9689 Context.getDefaultCallingConvention(true, false));
9690 EPI.Variadic = true;
9691 EPI.ExtInfo = FT->getExtInfo();
9692
9693 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9694 NewFD->setType(R);
9695 }
9696
9697 // If there's a #pragma GCC visibility in scope, and this isn't a class
9698 // member, set the visibility of this function.
9699 if (!DC->isRecord() && NewFD->isExternallyVisible())
9700 AddPushedVisibilityAttribute(NewFD);
9701
9702 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9703 // marking the function.
9704 AddCFAuditedAttribute(NewFD);
9705
9706 // If this is a function definition, check if we have to apply optnone due to
9707 // a pragma.
9708 if(D.isFunctionDefinition())
9709 AddRangeBasedOptnone(NewFD);
9710
9711 // If this is the first declaration of an extern C variable, update
9712 // the map of such variables.
9713 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9714 isIncompleteDeclExternC(*this, NewFD))
9715 RegisterLocallyScopedExternCDecl(NewFD, S);
9716
9717 // Set this FunctionDecl's range up to the right paren.
9718 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9719
9720 if (D.isRedeclaration() && !Previous.empty()) {
9721 NamedDecl *Prev = Previous.getRepresentativeDecl();
9722 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9723 isMemberSpecialization ||
9724 isFunctionTemplateSpecialization,
9725 D.isFunctionDefinition());
9726 }
9727
9728 if (getLangOpts().CUDA) {
9729 IdentifierInfo *II = NewFD->getIdentifier();
9730 if (II && II->isStr(getCudaConfigureFuncName()) &&
9731 !NewFD->isInvalidDecl() &&
9732 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9733 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9734 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9735 << getCudaConfigureFuncName();
9736 Context.setcudaConfigureCallDecl(NewFD);
9737 }
9738
9739 // Variadic functions, other than a *declaration* of printf, are not allowed
9740 // in device-side CUDA code, unless someone passed
9741 // -fcuda-allow-variadic-functions.
9742 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9743 (NewFD->hasAttr<CUDADeviceAttr>() ||
9744 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9745 !(II && II->isStr("printf") && NewFD->isExternC() &&
9746 !D.isFunctionDefinition())) {
9747 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9748 }
9749 }
9750
9751 MarkUnusedFileScopedDecl(NewFD);
9752
9753
9754
9755 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9756 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9757 if ((getLangOpts().OpenCLVersion >= 120)
9758 && (SC == SC_Static)) {
9759 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9760 D.setInvalidType();
9761 }
9762
9763 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9764 if (!NewFD->getReturnType()->isVoidType()) {
9765 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9766 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9767 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9768 : FixItHint());
9769 D.setInvalidType();
9770 }
9771
9772 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9773 for (auto Param : NewFD->parameters())
9774 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9775
9776 if (getLangOpts().OpenCLCPlusPlus) {
9777 if (DC->isRecord()) {
9778 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9779 D.setInvalidType();
9780 }
9781 if (FunctionTemplate) {
9782 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9783 D.setInvalidType();
9784 }
9785 }
9786 }
9787
9788 if (getLangOpts().CPlusPlus) {
9789 if (FunctionTemplate) {
9790 if (NewFD->isInvalidDecl())
9791 FunctionTemplate->setInvalidDecl();
9792 return FunctionTemplate;
9793 }
9794
9795 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9796 CompleteMemberSpecialization(NewFD, Previous);
9797 }
9798
9799 for (const ParmVarDecl *Param : NewFD->parameters()) {
9800 QualType PT = Param->getType();
9801
9802 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9803 // types.
9804 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
9805 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9806 QualType ElemTy = PipeTy->getElementType();
9807 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9808 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9809 D.setInvalidType();
9810 }
9811 }
9812 }
9813 }
9814
9815 // Here we have an function template explicit specialization at class scope.
9816 // The actual specialization will be postponed to template instatiation
9817 // time via the ClassScopeFunctionSpecializationDecl node.
9818 if (isDependentClassScopeExplicitSpecialization) {
9819 ClassScopeFunctionSpecializationDecl *NewSpec =
9820 ClassScopeFunctionSpecializationDecl::Create(
9821 Context, CurContext, NewFD->getLocation(),
9822 cast<CXXMethodDecl>(NewFD),
9823 HasExplicitTemplateArgs, TemplateArgs);
9824 CurContext->addDecl(NewSpec);
9825 AddToScope = false;
9826 }
9827
9828 // Diagnose availability attributes. Availability cannot be used on functions
9829 // that are run during load/unload.
9830 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9831 if (NewFD->hasAttr<ConstructorAttr>()) {
9832 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9833 << 1;
9834 NewFD->dropAttr<AvailabilityAttr>();
9835 }
9836 if (NewFD->hasAttr<DestructorAttr>()) {
9837 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9838 << 2;
9839 NewFD->dropAttr<AvailabilityAttr>();
9840 }
9841 }
9842
9843 // Diagnose no_builtin attribute on function declaration that are not a
9844 // definition.
9845 // FIXME: We should really be doing this in
9846 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
9847 // the FunctionDecl and at this point of the code
9848 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
9849 // because Sema::ActOnStartOfFunctionDef has not been called yet.
9850 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
9851 switch (D.getFunctionDefinitionKind()) {
9852 case FDK_Defaulted:
9853 case FDK_Deleted:
9854 Diag(NBA->getLocation(),
9855 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
9856 << NBA->getSpelling();
9857 break;
9858 case FDK_Declaration:
9859 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
9860 << NBA->getSpelling();
9861 break;
9862 case FDK_Definition:
9863 break;
9864 }
9865
9866 return NewFD;
9867}
9868
9869/// Return a CodeSegAttr from a containing class. The Microsoft docs say
9870/// when __declspec(code_seg) "is applied to a class, all member functions of
9871/// the class and nested classes -- this includes compiler-generated special
9872/// member functions -- are put in the specified segment."
9873/// The actual behavior is a little more complicated. The Microsoft compiler
9874/// won't check outer classes if there is an active value from #pragma code_seg.
9875/// The CodeSeg is always applied from the direct parent but only from outer
9876/// classes when the #pragma code_seg stack is empty. See:
9877/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9878/// available since MS has removed the page.
9879static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
9880 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9881 if (!Method)
9882 return nullptr;
9883 const CXXRecordDecl *Parent = Method->getParent();
9884 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9885 Attr *NewAttr = SAttr->clone(S.getASTContext());
9886 NewAttr->setImplicit(true);
9887 return NewAttr;
9888 }
9889
9890 // The Microsoft compiler won't check outer classes for the CodeSeg
9891 // when the #pragma code_seg stack is active.
9892 if (S.CodeSegStack.CurrentValue)
9893 return nullptr;
9894
9895 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9896 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9897 Attr *NewAttr = SAttr->clone(S.getASTContext());
9898 NewAttr->setImplicit(true);
9899 return NewAttr;
9900 }
9901 }
9902 return nullptr;
9903}
9904
9905/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9906/// containing class. Otherwise it will return implicit SectionAttr if the
9907/// function is a definition and there is an active value on CodeSegStack
9908/// (from the current #pragma code-seg value).
9909///
9910/// \param FD Function being declared.
9911/// \param IsDefinition Whether it is a definition or just a declarartion.
9912/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9913/// nullptr if no attribute should be added.
9914Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9915 bool IsDefinition) {
9916 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
9917 return A;
9918 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9919 CodeSegStack.CurrentValue)
9920 return SectionAttr::CreateImplicit(
9921 getASTContext(), CodeSegStack.CurrentValue->getString(),
9922 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9923 SectionAttr::Declspec_allocate);
9924 return nullptr;
9925}
9926
9927/// Determines if we can perform a correct type check for \p D as a
9928/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9929/// best-effort check.
9930///
9931/// \param NewD The new declaration.
9932/// \param OldD The old declaration.
9933/// \param NewT The portion of the type of the new declaration to check.
9934/// \param OldT The portion of the type of the old declaration to check.
9935bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
9936 QualType NewT, QualType OldT) {
9937 if (!NewD->getLexicalDeclContext()->isDependentContext())
9938 return true;
9939
9940 // For dependently-typed local extern declarations and friends, we can't
9941 // perform a correct type check in general until instantiation:
9942 //
9943 // int f();
9944 // template<typename T> void g() { T f(); }
9945 //
9946 // (valid if g() is only instantiated with T = int).
9947 if (NewT->isDependentType() &&
9948 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9949 return false;
9950
9951 // Similarly, if the previous declaration was a dependent local extern
9952 // declaration, we don't really know its type yet.
9953 if (OldT->isDependentType() && OldD->isLocalExternDecl())
9954 return false;
9955
9956 return true;
9957}
9958
9959/// Checks if the new declaration declared in dependent context must be
9960/// put in the same redeclaration chain as the specified declaration.
9961///
9962/// \param D Declaration that is checked.
9963/// \param PrevDecl Previous declaration found with proper lookup method for the
9964/// same declaration name.
9965/// \returns True if D must be added to the redeclaration chain which PrevDecl
9966/// belongs to.
9967///
9968bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9969 if (!D->getLexicalDeclContext()->isDependentContext())
9970 return true;
9971
9972 // Don't chain dependent friend function definitions until instantiation, to
9973 // permit cases like
9974 //
9975 // void func();
9976 // template<typename T> class C1 { friend void func() {} };
9977 // template<typename T> class C2 { friend void func() {} };
9978 //
9979 // ... which is valid if only one of C1 and C2 is ever instantiated.
9980 //
9981 // FIXME: This need only apply to function definitions. For now, we proxy
9982 // this by checking for a file-scope function. We do not want this to apply
9983 // to friend declarations nominating member functions, because that gets in
9984 // the way of access checks.
9985 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9986 return false;
9987
9988 auto *VD = dyn_cast<ValueDecl>(D);
9989 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9990 return !VD || !PrevVD ||
9991 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9992 PrevVD->getType());
9993}
9994
9995/// Check the target attribute of the function for MultiVersion
9996/// validity.
9997///
9998/// Returns true if there was an error, false otherwise.
9999static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10000 const auto *TA = FD->getAttr<TargetAttr>();
10001 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10001, __PRETTY_FUNCTION__))
;
10002 ParsedTargetAttr ParseInfo = TA->parse();
10003 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10004 enum ErrType { Feature = 0, Architecture = 1 };
10005
10006 if (!ParseInfo.Architecture.empty() &&
10007 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10008 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10009 << Architecture << ParseInfo.Architecture;
10010 return true;
10011 }
10012
10013 for (const auto &Feat : ParseInfo.Features) {
10014 auto BareFeat = StringRef{Feat}.substr(1);
10015 if (Feat[0] == '-') {
10016 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10017 << Feature << ("no-" + BareFeat).str();
10018 return true;
10019 }
10020
10021 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10022 !TargetInfo.isValidFeatureName(BareFeat)) {
10023 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10024 << Feature << BareFeat;
10025 return true;
10026 }
10027 }
10028 return false;
10029}
10030
10031// Provide a white-list of attributes that are allowed to be combined with
10032// multiversion functions.
10033static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10034 MultiVersionKind MVType) {
10035 // Note: this list/diagnosis must match the list in
10036 // checkMultiversionAttributesAllSame.
10037 switch (Kind) {
10038 default:
10039 return false;
10040 case attr::Used:
10041 return MVType == MultiVersionKind::Target;
10042 case attr::NonNull:
10043 case attr::NoThrow:
10044 return true;
10045 }
10046}
10047
10048static bool checkNonMultiVersionCompatAttributes(Sema &S,
10049 const FunctionDecl *FD,
10050 const FunctionDecl *CausedFD,
10051 MultiVersionKind MVType) {
10052 bool IsCPUSpecificCPUDispatchMVType =
10053 MVType == MultiVersionKind::CPUDispatch ||
10054 MVType == MultiVersionKind::CPUSpecific;
10055 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10056 Sema &S, const Attr *A) {
10057 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10058 << IsCPUSpecificCPUDispatchMVType << A;
10059 if (CausedFD)
10060 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10061 return true;
10062 };
10063
10064 for (const Attr *A : FD->attrs()) {
10065 switch (A->getKind()) {
10066 case attr::CPUDispatch:
10067 case attr::CPUSpecific:
10068 if (MVType != MultiVersionKind::CPUDispatch &&
10069 MVType != MultiVersionKind::CPUSpecific)
10070 return Diagnose(S, A);
10071 break;
10072 case attr::Target:
10073 if (MVType != MultiVersionKind::Target)
10074 return Diagnose(S, A);
10075 break;
10076 default:
10077 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10078 return Diagnose(S, A);
10079 break;
10080 }
10081 }
10082 return false;
10083}
10084
10085bool Sema::areMultiversionVariantFunctionsCompatible(
10086 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10087 const PartialDiagnostic &NoProtoDiagID,
10088 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10089 const PartialDiagnosticAt &NoSupportDiagIDAt,
10090 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10091 bool ConstexprSupported, bool CLinkageMayDiffer) {
10092 enum DoesntSupport {
10093 FuncTemplates = 0,
10094 VirtFuncs = 1,
10095 DeducedReturn = 2,
10096 Constructors = 3,
10097 Destructors = 4,
10098 DeletedFuncs = 5,
10099 DefaultedFuncs = 6,
10100 ConstexprFuncs = 7,
10101 ConstevalFuncs = 8,
10102 };
10103 enum Different {
10104 CallingConv = 0,
10105 ReturnType = 1,
10106 ConstexprSpec = 2,
10107 InlineSpec = 3,
10108 StorageClass = 4,
10109 Linkage = 5,
10110 };
10111
10112 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10113 !OldFD->getType()->getAs<FunctionProtoType>()) {
10114 Diag(OldFD->getLocation(), NoProtoDiagID);
10115 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10116 return true;
10117 }
10118
10119 if (NoProtoDiagID.getDiagID() != 0 &&
10120 !NewFD->getType()->getAs<FunctionProtoType>())
10121 return Diag(NewFD->getLocation(), NoProtoDiagID);
10122
10123 if (!TemplatesSupported &&
10124 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10125 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10126 << FuncTemplates;
10127
10128 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10129 if (NewCXXFD->isVirtual())
10130 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10131 << VirtFuncs;
10132
10133 if (isa<CXXConstructorDecl>(NewCXXFD))
10134 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10135 << Constructors;
10136
10137 if (isa<CXXDestructorDecl>(NewCXXFD))
10138 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10139 << Destructors;
10140 }
10141
10142 if (NewFD->isDeleted())
10143 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10144 << DeletedFuncs;
10145
10146 if (NewFD->isDefaulted())
10147 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10148 << DefaultedFuncs;
10149
10150 if (!ConstexprSupported && NewFD->isConstexpr())
10151 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10152 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10153
10154 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10155 const auto *NewType = cast<FunctionType>(NewQType);
10156 QualType NewReturnType = NewType->getReturnType();
10157
10158 if (NewReturnType->isUndeducedType())
10159 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10160 << DeducedReturn;
10161
10162 // Ensure the return type is identical.
10163 if (OldFD) {
10164 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10165 const auto *OldType = cast<FunctionType>(OldQType);
10166 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10167 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10168
10169 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10170 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10171
10172 QualType OldReturnType = OldType->getReturnType();
10173
10174 if (OldReturnType != NewReturnType)
10175 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10176
10177 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10178 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10179
10180 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10181 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10182
10183 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10184 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10185
10186 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10187 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10188
10189 if (CheckEquivalentExceptionSpec(
10190 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10191 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10192 return true;
10193 }
10194 return false;
10195}
10196
10197static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10198 const FunctionDecl *NewFD,
10199 bool CausesMV,
10200 MultiVersionKind MVType) {
10201 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10202 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10203 if (OldFD)
10204 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10205 return true;
10206 }
10207
10208 bool IsCPUSpecificCPUDispatchMVType =
10209 MVType == MultiVersionKind::CPUDispatch ||
10210 MVType == MultiVersionKind::CPUSpecific;
10211
10212 if (CausesMV && OldFD &&
10213 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10214 return true;
10215
10216 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10217 return true;
10218
10219 // Only allow transition to MultiVersion if it hasn't been used.
10220 if (OldFD && CausesMV && OldFD->isUsed(false))
10221 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10222
10223 return S.areMultiversionVariantFunctionsCompatible(
10224 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10225 PartialDiagnosticAt(NewFD->getLocation(),
10226 S.PDiag(diag::note_multiversioning_caused_here)),
10227 PartialDiagnosticAt(NewFD->getLocation(),
10228 S.PDiag(diag::err_multiversion_doesnt_support)
10229 << IsCPUSpecificCPUDispatchMVType),
10230 PartialDiagnosticAt(NewFD->getLocation(),
10231 S.PDiag(diag::err_multiversion_diff)),
10232 /*TemplatesSupported=*/false,
10233 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10234 /*CLinkageMayDiffer=*/false);
10235}
10236
10237/// Check the validity of a multiversion function declaration that is the
10238/// first of its kind. Also sets the multiversion'ness' of the function itself.
10239///
10240/// This sets NewFD->isInvalidDecl() to true if there was an error.
10241///
10242/// Returns true if there was an error, false otherwise.
10243static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10244 MultiVersionKind MVType,
10245 const TargetAttr *TA) {
10246 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10247, __PRETTY_FUNCTION__))
10247 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10247, __PRETTY_FUNCTION__))
;
10248
10249 // Target only causes MV if it is default, otherwise this is a normal
10250 // function.
10251 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10252 return false;
10253
10254 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10255 FD->setInvalidDecl();
10256 return true;
10257 }
10258
10259 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10260 FD->setInvalidDecl();
10261 return true;
10262 }
10263
10264 FD->setIsMultiVersion();
10265 return false;
10266}
10267
10268static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10269 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10270 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10271 return true;
10272 }
10273
10274 return false;
10275}
10276
10277static bool CheckTargetCausesMultiVersioning(
10278 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10279 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10280 LookupResult &Previous) {
10281 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10282 ParsedTargetAttr NewParsed = NewTA->parse();
10283 // Sort order doesn't matter, it just needs to be consistent.
10284 llvm::sort(NewParsed.Features);
10285
10286 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10287 // to change, this is a simple redeclaration.
10288 if (!NewTA->isDefaultVersion() &&
10289 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10290 return false;
10291
10292 // Otherwise, this decl causes MultiVersioning.
10293 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10294 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10295 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10296 NewFD->setInvalidDecl();
10297 return true;
10298 }
10299
10300 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10301 MultiVersionKind::Target)) {
10302 NewFD->setInvalidDecl();
10303 return true;
10304 }
10305
10306 if (CheckMultiVersionValue(S, NewFD)) {
10307 NewFD->setInvalidDecl();
10308 return true;
10309 }
10310
10311 // If this is 'default', permit the forward declaration.
10312 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10313 Redeclaration = true;
10314 OldDecl = OldFD;
10315 OldFD->setIsMultiVersion();
10316 NewFD->setIsMultiVersion();
10317 return false;
10318 }
10319
10320 if (CheckMultiVersionValue(S, OldFD)) {
10321 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10322 NewFD->setInvalidDecl();
10323 return true;
10324 }
10325
10326 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10327
10328 if (OldParsed == NewParsed) {
10329 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10330 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10331 NewFD->setInvalidDecl();
10332 return true;
10333 }
10334
10335 for (const auto *FD : OldFD->redecls()) {
10336 const auto *CurTA = FD->getAttr<TargetAttr>();
10337 // We allow forward declarations before ANY multiversioning attributes, but
10338 // nothing after the fact.
10339 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10340 (!CurTA || CurTA->isInherited())) {
10341 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10342 << 0;
10343 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10344 NewFD->setInvalidDecl();
10345 return true;
10346 }
10347 }
10348
10349 OldFD->setIsMultiVersion();
10350 NewFD->setIsMultiVersion();
10351 Redeclaration = false;
10352 MergeTypeWithPrevious = false;
10353 OldDecl = nullptr;
10354 Previous.clear();
10355 return false;
10356}
10357
10358/// Check the validity of a new function declaration being added to an existing
10359/// multiversioned declaration collection.
10360static bool CheckMultiVersionAdditionalDecl(
10361 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10362 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10363 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10364 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10365 LookupResult &Previous) {
10366
10367 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10368 // Disallow mixing of multiversioning types.
10369 if ((OldMVType == MultiVersionKind::Target &&
10370 NewMVType != MultiVersionKind::Target) ||
10371 (NewMVType == MultiVersionKind::Target &&
10372 OldMVType != MultiVersionKind::Target)) {
10373 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10374 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10375 NewFD->setInvalidDecl();
10376 return true;
10377 }
10378
10379 ParsedTargetAttr NewParsed;
10380 if (NewTA) {
10381 NewParsed = NewTA->parse();
10382 llvm::sort(NewParsed.Features);
10383 }
10384
10385 bool UseMemberUsingDeclRules =
10386 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10387
10388 // Next, check ALL non-overloads to see if this is a redeclaration of a
10389 // previous member of the MultiVersion set.
10390 for (NamedDecl *ND : Previous) {
10391 FunctionDecl *CurFD = ND->getAsFunction();
10392 if (!CurFD)
10393 continue;
10394 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10395 continue;
10396
10397 if (NewMVType == MultiVersionKind::Target) {
10398 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10399 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10400 NewFD->setIsMultiVersion();
10401 Redeclaration = true;
10402 OldDecl = ND;
10403 return false;
10404 }
10405
10406 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10407 if (CurParsed == NewParsed) {
10408 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10409 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10410 NewFD->setInvalidDecl();
10411 return true;
10412 }
10413 } else {
10414 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10415 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10416 // Handle CPUDispatch/CPUSpecific versions.
10417 // Only 1 CPUDispatch function is allowed, this will make it go through
10418 // the redeclaration errors.
10419 if (NewMVType == MultiVersionKind::CPUDispatch &&
10420 CurFD->hasAttr<CPUDispatchAttr>()) {
10421 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10422 std::equal(
10423 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10424 NewCPUDisp->cpus_begin(),
10425 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10426 return Cur->getName() == New->getName();
10427 })) {
10428 NewFD->setIsMultiVersion();
10429 Redeclaration = true;
10430 OldDecl = ND;
10431 return false;
10432 }
10433
10434 // If the declarations don't match, this is an error condition.
10435 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10436 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10437 NewFD->setInvalidDecl();
10438 return true;
10439 }
10440 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10441
10442 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10443 std::equal(
10444 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10445 NewCPUSpec->cpus_begin(),
10446 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10447 return Cur->getName() == New->getName();
10448 })) {
10449 NewFD->setIsMultiVersion();
10450 Redeclaration = true;
10451 OldDecl = ND;
10452 return false;
10453 }
10454
10455 // Only 1 version of CPUSpecific is allowed for each CPU.
10456 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10457 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10458 if (CurII == NewII) {
10459 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10460 << NewII;
10461 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10462 NewFD->setInvalidDecl();
10463 return true;
10464 }
10465 }
10466 }
10467 }
10468 // If the two decls aren't the same MVType, there is no possible error
10469 // condition.
10470 }
10471 }
10472
10473 // Else, this is simply a non-redecl case. Checking the 'value' is only
10474 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10475 // handled in the attribute adding step.
10476 if (NewMVType == MultiVersionKind::Target &&
10477 CheckMultiVersionValue(S, NewFD)) {
10478 NewFD->setInvalidDecl();
10479 return true;
10480 }
10481
10482 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10483 !OldFD->isMultiVersion(), NewMVType)) {
10484 NewFD->setInvalidDecl();
10485 return true;
10486 }
10487
10488 // Permit forward declarations in the case where these two are compatible.
10489 if (!OldFD->isMultiVersion()) {
10490 OldFD->setIsMultiVersion();
10491 NewFD->setIsMultiVersion();
10492 Redeclaration = true;
10493 OldDecl = OldFD;
10494 return false;
10495 }
10496
10497 NewFD->setIsMultiVersion();
10498 Redeclaration = false;
10499 MergeTypeWithPrevious = false;
10500 OldDecl = nullptr;
10501 Previous.clear();
10502 return false;
10503}
10504
10505
10506/// Check the validity of a mulitversion function declaration.
10507/// Also sets the multiversion'ness' of the function itself.
10508///
10509/// This sets NewFD->isInvalidDecl() to true if there was an error.
10510///
10511/// Returns true if there was an error, false otherwise.
10512static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10513 bool &Redeclaration, NamedDecl *&OldDecl,
10514 bool &MergeTypeWithPrevious,
10515 LookupResult &Previous) {
10516 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10517 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10518 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10519
10520 // Mixing Multiversioning types is prohibited.
10521 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10522 (NewCPUDisp && NewCPUSpec)) {
10523 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10524 NewFD->setInvalidDecl();
10525 return true;
10526 }
10527
10528 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10529
10530 // Main isn't allowed to become a multiversion function, however it IS
10531 // permitted to have 'main' be marked with the 'target' optimization hint.
10532 if (NewFD->isMain()) {
10533 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10534 MVType == MultiVersionKind::CPUDispatch ||
10535 MVType == MultiVersionKind::CPUSpecific) {
10536 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10537 NewFD->setInvalidDecl();
10538 return true;
10539 }
10540 return false;
10541 }
10542
10543 if (!OldDecl || !OldDecl->getAsFunction() ||
10544 OldDecl->getDeclContext()->getRedeclContext() !=
10545 NewFD->getDeclContext()->getRedeclContext()) {
10546 // If there's no previous declaration, AND this isn't attempting to cause
10547 // multiversioning, this isn't an error condition.
10548 if (MVType == MultiVersionKind::None)
10549 return false;
10550 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10551 }
10552
10553 FunctionDecl *OldFD = OldDecl->getAsFunction();
10554
10555 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10556 return false;
10557
10558 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10559 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10560 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10561 NewFD->setInvalidDecl();
10562 return true;
10563 }
10564
10565 // Handle the target potentially causes multiversioning case.
10566 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10567 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10568 Redeclaration, OldDecl,
10569 MergeTypeWithPrevious, Previous);
10570
10571 // At this point, we have a multiversion function decl (in OldFD) AND an
10572 // appropriate attribute in the current function decl. Resolve that these are
10573 // still compatible with previous declarations.
10574 return CheckMultiVersionAdditionalDecl(
10575 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10576 OldDecl, MergeTypeWithPrevious, Previous);
10577}
10578
10579/// Perform semantic checking of a new function declaration.
10580///
10581/// Performs semantic analysis of the new function declaration
10582/// NewFD. This routine performs all semantic checking that does not
10583/// require the actual declarator involved in the declaration, and is
10584/// used both for the declaration of functions as they are parsed
10585/// (called via ActOnDeclarator) and for the declaration of functions
10586/// that have been instantiated via C++ template instantiation (called
10587/// via InstantiateDecl).
10588///
10589/// \param IsMemberSpecialization whether this new function declaration is
10590/// a member specialization (that replaces any definition provided by the
10591/// previous declaration).
10592///
10593/// This sets NewFD->isInvalidDecl() to true if there was an error.
10594///
10595/// \returns true if the function declaration is a redeclaration.
10596bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10597 LookupResult &Previous,
10598 bool IsMemberSpecialization) {
10599 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10600, __PRETTY_FUNCTION__))
10600 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10600, __PRETTY_FUNCTION__))
;
10601
10602 // Determine whether the type of this function should be merged with
10603 // a previous visible declaration. This never happens for functions in C++,
10604 // and always happens in C if the previous declaration was visible.
10605 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10606 !Previous.isShadowed();
10607
10608 bool Redeclaration = false;
10609 NamedDecl *OldDecl = nullptr;
10610 bool MayNeedOverloadableChecks = false;
10611
10612 // Merge or overload the declaration with an existing declaration of
10613 // the same name, if appropriate.
10614 if (!Previous.empty()) {
10615 // Determine whether NewFD is an overload of PrevDecl or
10616 // a declaration that requires merging. If it's an overload,
10617 // there's no more work to do here; we'll just add the new
10618 // function to the scope.
10619 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10620 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10621 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10622 Redeclaration = true;
10623 OldDecl = Candidate;
10624 }
10625 } else {
10626 MayNeedOverloadableChecks = true;
10627 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10628 /*NewIsUsingDecl*/ false)) {
10629 case Ovl_Match:
10630 Redeclaration = true;
10631 break;
10632
10633 case Ovl_NonFunction:
10634 Redeclaration = true;
10635 break;
10636
10637 case Ovl_Overload:
10638 Redeclaration = false;
10639 break;
10640 }
10641 }
10642 }
10643
10644 // Check for a previous extern "C" declaration with this name.
10645 if (!Redeclaration &&
10646 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10647 if (!Previous.empty()) {
10648 // This is an extern "C" declaration with the same name as a previous
10649 // declaration, and thus redeclares that entity...
10650 Redeclaration = true;
10651 OldDecl = Previous.getFoundDecl();
10652 MergeTypeWithPrevious = false;
10653
10654 // ... except in the presence of __attribute__((overloadable)).
10655 if (OldDecl->hasAttr<OverloadableAttr>() ||
10656 NewFD->hasAttr<OverloadableAttr>()) {
10657 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10658 MayNeedOverloadableChecks = true;
10659 Redeclaration = false;
10660 OldDecl = nullptr;
10661 }
10662 }
10663 }
10664 }
10665
10666 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10667 MergeTypeWithPrevious, Previous))
10668 return Redeclaration;
10669
10670 // C++11 [dcl.constexpr]p8:
10671 // A constexpr specifier for a non-static member function that is not
10672 // a constructor declares that member function to be const.
10673 //
10674 // This needs to be delayed until we know whether this is an out-of-line
10675 // definition of a static member function.
10676 //
10677 // This rule is not present in C++1y, so we produce a backwards
10678 // compatibility warning whenever it happens in C++11.
10679 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10680 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10681 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10682 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10683 CXXMethodDecl *OldMD = nullptr;
10684 if (OldDecl)
10685 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10686 if (!OldMD || !OldMD->isStatic()) {
10687 const FunctionProtoType *FPT =
10688 MD->getType()->castAs<FunctionProtoType>();
10689 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10690 EPI.TypeQuals.addConst();
10691 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10692 FPT->getParamTypes(), EPI));
10693
10694 // Warn that we did this, if we're not performing template instantiation.
10695 // In that case, we'll have warned already when the template was defined.
10696 if (!inTemplateInstantiation()) {
10697 SourceLocation AddConstLoc;
10698 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10699 .IgnoreParens().getAs<FunctionTypeLoc>())
10700 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10701
10702 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10703 << FixItHint::CreateInsertion(AddConstLoc, " const");
10704 }
10705 }
10706 }
10707
10708 if (Redeclaration) {
10709 // NewFD and OldDecl represent declarations that need to be
10710 // merged.
10711 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10712 NewFD->setInvalidDecl();
10713 return Redeclaration;
10714 }
10715
10716 Previous.clear();
10717 Previous.addDecl(OldDecl);
10718
10719 if (FunctionTemplateDecl *OldTemplateDecl =
10720 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10721 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10722 FunctionTemplateDecl *NewTemplateDecl
10723 = NewFD->getDescribedFunctionTemplate();
10724 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10724, __PRETTY_FUNCTION__))
;
10725
10726 // The call to MergeFunctionDecl above may have created some state in
10727 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10728 // can add it as a redeclaration.
10729 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10730
10731 NewFD->setPreviousDeclaration(OldFD);
10732 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10733 if (NewFD->isCXXClassMember()) {
10734 NewFD->setAccess(OldTemplateDecl->getAccess());
10735 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10736 }
10737
10738 // If this is an explicit specialization of a member that is a function
10739 // template, mark it as a member specialization.
10740 if (IsMemberSpecialization &&
10741 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10742 NewTemplateDecl->setMemberSpecialization();
10743 assert(OldTemplateDecl->isMemberSpecialization())((OldTemplateDecl->isMemberSpecialization()) ? static_cast
<void> (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10743, __PRETTY_FUNCTION__))
;
10744 // Explicit specializations of a member template do not inherit deleted
10745 // status from the parent member template that they are specializing.
10746 if (OldFD->isDeleted()) {
10747 // FIXME: This assert will not hold in the presence of modules.
10748 assert(OldFD->getCanonicalDecl() == OldFD)((OldFD->getCanonicalDecl() == OldFD) ? static_cast<void
> (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10748, __PRETTY_FUNCTION__))
;
10749 // FIXME: We need an update record for this AST mutation.
10750 OldFD->setDeletedAsWritten(false);
10751 }
10752 }
10753
10754 } else {
10755 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10756 auto *OldFD = cast<FunctionDecl>(OldDecl);
10757 // This needs to happen first so that 'inline' propagates.
10758 NewFD->setPreviousDeclaration(OldFD);
10759 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10760 if (NewFD->isCXXClassMember())
10761 NewFD->setAccess(OldFD->getAccess());
10762 }
10763 }
10764 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10765 !NewFD->getAttr<OverloadableAttr>()) {
10766 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10771, __PRETTY_FUNCTION__))
10767 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10771, __PRETTY_FUNCTION__))
10768 [](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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10771, __PRETTY_FUNCTION__))
10769 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10771, __PRETTY_FUNCTION__))
10770 })) &&(((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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10771, __PRETTY_FUNCTION__))
10771 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10771, __PRETTY_FUNCTION__))
;
10772
10773 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10774 const auto *FD = dyn_cast<FunctionDecl>(ND);
10775 return FD && !FD->hasAttr<OverloadableAttr>();
10776 });
10777
10778 if (OtherUnmarkedIter != Previous.end()) {
10779 Diag(NewFD->getLocation(),
10780 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10781 Diag((*OtherUnmarkedIter)->getLocation(),
10782 diag::note_attribute_overloadable_prev_overload)
10783 << false;
10784
10785 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10786 }
10787 }
10788
10789 // Semantic checking for this function declaration (in isolation).
10790
10791 if (getLangOpts().CPlusPlus) {
10792 // C++-specific checks.
10793 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10794 CheckConstructor(Constructor);
10795 } else if (CXXDestructorDecl *Destructor =
10796 dyn_cast<CXXDestructorDecl>(NewFD)) {
10797 CXXRecordDecl *Record = Destructor->getParent();
10798 QualType ClassType = Context.getTypeDeclType(Record);
10799
10800 // FIXME: Shouldn't we be able to perform this check even when the class
10801 // type is dependent? Both gcc and edg can handle that.
10802 if (!ClassType->isDependentType()) {
10803 DeclarationName Name
10804 = Context.DeclarationNames.getCXXDestructorName(
10805 Context.getCanonicalType(ClassType));
10806 if (NewFD->getDeclName() != Name) {
10807 Diag(NewFD->getLocation(), diag::err_destructor_name);
10808 NewFD->setInvalidDecl();
10809 return Redeclaration;
10810 }
10811 }
10812 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10813 if (auto *TD = Guide->getDescribedFunctionTemplate())
10814 CheckDeductionGuideTemplate(TD);
10815
10816 // A deduction guide is not on the list of entities that can be
10817 // explicitly specialized.
10818 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10819 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10820 << /*explicit specialization*/ 1;
10821 }
10822
10823 // Find any virtual functions that this function overrides.
10824 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10825 if (!Method->isFunctionTemplateSpecialization() &&
10826 !Method->getDescribedFunctionTemplate() &&
10827 Method->isCanonicalDecl()) {
10828 AddOverriddenMethods(Method->getParent(), Method);
10829 }
10830 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
10831 // C++2a [class.virtual]p6
10832 // A virtual method shall not have a requires-clause.
10833 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
10834 diag::err_constrained_virtual_method);
10835
10836 if (Method->isStatic())
10837 checkThisInStaticMemberFunctionType(Method);
10838 }
10839
10840 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
10841 ActOnConversionDeclarator(Conversion);
10842
10843 // Extra checking for C++ overloaded operators (C++ [over.oper]).
10844 if (NewFD->isOverloadedOperator() &&
10845 CheckOverloadedOperatorDeclaration(NewFD)) {
10846 NewFD->setInvalidDecl();
10847 return Redeclaration;
10848 }
10849
10850 // Extra checking for C++0x literal operators (C++0x [over.literal]).
10851 if (NewFD->getLiteralIdentifier() &&
10852 CheckLiteralOperatorDeclaration(NewFD)) {
10853 NewFD->setInvalidDecl();
10854 return Redeclaration;
10855 }
10856
10857 // In C++, check default arguments now that we have merged decls. Unless
10858 // the lexical context is the class, because in this case this is done
10859 // during delayed parsing anyway.
10860 if (!CurContext->isRecord())
10861 CheckCXXDefaultArguments(NewFD);
10862
10863 // If this function declares a builtin function, check the type of this
10864 // declaration against the expected type for the builtin.
10865 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10866 ASTContext::GetBuiltinTypeError Error;
10867 LookupNecessaryTypesForBuiltin(S, BuiltinID);
10868 QualType T = Context.GetBuiltinType(BuiltinID, Error);
10869 // If the type of the builtin differs only in its exception
10870 // specification, that's OK.
10871 // FIXME: If the types do differ in this way, it would be better to
10872 // retain the 'noexcept' form of the type.
10873 if (!T.isNull() &&
10874 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10875 NewFD->getType()))
10876 // The type of this function differs from the type of the builtin,
10877 // so forget about the builtin entirely.
10878 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
10879 }
10880
10881 // If this function is declared as being extern "C", then check to see if
10882 // the function returns a UDT (class, struct, or union type) that is not C
10883 // compatible, and if it does, warn the user.
10884 // But, issue any diagnostic on the first declaration only.
10885 if (Previous.empty() && NewFD->isExternC()) {
10886 QualType R = NewFD->getReturnType();
10887 if (R->isIncompleteType() && !R->isVoidType())
10888 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10889 << NewFD << R;
10890 else if (!R.isPODType(Context) && !R->isVoidType() &&
10891 !R->isObjCObjectPointerType())
10892 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10893 }
10894
10895 // C++1z [dcl.fct]p6:
10896 // [...] whether the function has a non-throwing exception-specification
10897 // [is] part of the function type
10898 //
10899 // This results in an ABI break between C++14 and C++17 for functions whose
10900 // declared type includes an exception-specification in a parameter or
10901 // return type. (Exception specifications on the function itself are OK in
10902 // most cases, and exception specifications are not permitted in most other
10903 // contexts where they could make it into a mangling.)
10904 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10905 auto HasNoexcept = [&](QualType T) -> bool {
10906 // Strip off declarator chunks that could be between us and a function
10907 // type. We don't need to look far, exception specifications are very
10908 // restricted prior to C++17.
10909 if (auto *RT = T->getAs<ReferenceType>())
10910 T = RT->getPointeeType();
10911 else if (T->isAnyPointerType())
10912 T = T->getPointeeType();
10913 else if (auto *MPT = T->getAs<MemberPointerType>())
10914 T = MPT->getPointeeType();
10915 if (auto *FPT = T->getAs<FunctionProtoType>())
10916 if (FPT->isNothrow())
10917 return true;
10918 return false;
10919 };
10920
10921 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10922 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10923 for (QualType T : FPT->param_types())
10924 AnyNoexcept |= HasNoexcept(T);
10925 if (AnyNoexcept)
10926 Diag(NewFD->getLocation(),
10927 diag::warn_cxx17_compat_exception_spec_in_signature)
10928 << NewFD;
10929 }
10930
10931 if (!Redeclaration && LangOpts.CUDA)
10932 checkCUDATargetOverload(NewFD, Previous);
10933 }
10934 return Redeclaration;
10935}
10936
10937void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
10938 // C++11 [basic.start.main]p3:
10939 // A program that [...] declares main to be inline, static or
10940 // constexpr is ill-formed.
10941 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
10942 // appear in a declaration of main.
10943 // static main is not an error under C99, but we should warn about it.
10944 // We accept _Noreturn main as an extension.
10945 if (FD->getStorageClass() == SC_Static)
10946 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10947 ? diag::err_static_main : diag::warn_static_main)
10948 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10949 if (FD->isInlineSpecified())
10950 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10951 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10952 if (DS.isNoreturnSpecified()) {
10953 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10954 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
10955 Diag(NoreturnLoc, diag::ext_noreturn_main);
10956 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10957 << FixItHint::CreateRemoval(NoreturnRange);
10958 }
10959 if (FD->isConstexpr()) {
10960 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10961 << FD->isConsteval()
10962 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10963 FD->setConstexprKind(CSK_unspecified);
10964 }
10965
10966 if (getLangOpts().OpenCL) {
10967 Diag(FD->getLocation(), diag::err_opencl_no_main)
10968 << FD->hasAttr<OpenCLKernelAttr>();
10969 FD->setInvalidDecl();
10970 return;
10971 }
10972
10973 QualType T = FD->getType();
10974 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 10974, __PRETTY_FUNCTION__))
;
10975 const FunctionType* FT = T->castAs<FunctionType>();
10976
10977 // Set default calling convention for main()
10978 if (FT->getCallConv() != CC_C) {
10979 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
10980 FD->setType(QualType(FT, 0));
10981 T = Context.getCanonicalType(FD->getType());
10982 }
10983
10984 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10985 // In C with GNU extensions we allow main() to have non-integer return
10986 // type, but we should warn about the extension, and we disable the
10987 // implicit-return-zero rule.
10988
10989 // GCC in C mode accepts qualified 'int'.
10990 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10991 FD->setHasImplicitReturnZero(true);
10992 else {
10993 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10994 SourceRange RTRange = FD->getReturnTypeSourceRange();
10995 if (RTRange.isValid())
10996 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10997 << FixItHint::CreateReplacement(RTRange, "int");
10998 }
10999 } else {
11000 // In C and C++, main magically returns 0 if you fall off the end;
11001 // set the flag which tells us that.
11002 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11003
11004 // All the standards say that main() should return 'int'.
11005 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11006 FD->setHasImplicitReturnZero(true);
11007 else {
11008 // Otherwise, this is just a flat-out error.
11009 SourceRange RTRange = FD->getReturnTypeSourceRange();
11010 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11011 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11012 : FixItHint());
11013 FD->setInvalidDecl(true);
11014 }
11015 }
11016
11017 // Treat protoless main() as nullary.
11018 if (isa<FunctionNoProtoType>(FT)) return;
11019
11020 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11021 unsigned nparams = FTP->getNumParams();
11022 assert(FD->getNumParams() == nparams)((FD->getNumParams() == nparams) ? static_cast<void>
(0) : __assert_fail ("FD->getNumParams() == nparams", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11022, __PRETTY_FUNCTION__))
;
11023
11024 bool HasExtraParameters = (nparams > 3);
11025
11026 if (FTP->isVariadic()) {
11027 Diag(FD->getLocation(), diag::ext_variadic_main);
11028 // FIXME: if we had information about the location of the ellipsis, we
11029 // could add a FixIt hint to remove it as a parameter.
11030 }
11031
11032 // Darwin passes an undocumented fourth argument of type char**. If
11033 // other platforms start sprouting these, the logic below will start
11034 // getting shifty.
11035 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11036 HasExtraParameters = false;
11037
11038 if (HasExtraParameters) {
11039 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11040 FD->setInvalidDecl(true);
11041 nparams = 3;
11042 }
11043
11044 // FIXME: a lot of the following diagnostics would be improved
11045 // if we had some location information about types.
11046
11047 QualType CharPP =
11048 Context.getPointerType(Context.getPointerType(Context.CharTy));
11049 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11050
11051 for (unsigned i = 0; i < nparams; ++i) {
11052 QualType AT = FTP->getParamType(i);
11053
11054 bool mismatch = true;
11055
11056 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11057 mismatch = false;
11058 else if (Expected[i] == CharPP) {
11059 // As an extension, the following forms are okay:
11060 // char const **
11061 // char const * const *
11062 // char * const *
11063
11064 QualifierCollector qs;
11065 const PointerType* PT;
11066 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11067 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11068 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11069 Context.CharTy)) {
11070 qs.removeConst();
11071 mismatch = !qs.empty();
11072 }
11073 }
11074
11075 if (mismatch) {
11076 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11077 // TODO: suggest replacing given type with expected type
11078 FD->setInvalidDecl(true);
11079 }
11080 }
11081
11082 if (nparams == 1 && !FD->isInvalidDecl()) {
11083 Diag(FD->getLocation(), diag::warn_main_one_arg);
11084 }
11085
11086 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11087 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11088 FD->setInvalidDecl();
11089 }
11090}
11091
11092void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11093 QualType T = FD->getType();
11094 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11094, __PRETTY_FUNCTION__))
;
11095 const FunctionType *FT = T->castAs<FunctionType>();
11096
11097 // Set an implicit return of 'zero' if the function can return some integral,
11098 // enumeration, pointer or nullptr type.
11099 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11100 FT->getReturnType()->isAnyPointerType() ||
11101 FT->getReturnType()->isNullPtrType())
11102 // DllMain is exempt because a return value of zero means it failed.
11103 if (FD->getName() != "DllMain")
11104 FD->setHasImplicitReturnZero(true);
11105
11106 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11107 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11108 FD->setInvalidDecl();
11109 }
11110}
11111
11112bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11113 // FIXME: Need strict checking. In C89, we need to check for
11114 // any assignment, increment, decrement, function-calls, or
11115 // commas outside of a sizeof. In C99, it's the same list,
11116 // except that the aforementioned are allowed in unevaluated
11117 // expressions. Everything else falls under the
11118 // "may accept other forms of constant expressions" exception.
11119 //
11120 // Regular C++ code will not end up here (exceptions: language extensions,
11121 // OpenCL C++ etc), so the constant expression rules there don't matter.
11122 if (Init->isValueDependent()) {
11123 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11124, __PRETTY_FUNCTION__))
11124 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11124, __PRETTY_FUNCTION__))
;
11125 return true;
11126 }
11127 const Expr *Culprit;
11128 if (Init->isConstantInitializer(Context, false, &Culprit))
11129 return false;
11130 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11131 << Culprit->getSourceRange();
11132 return true;
11133}
11134
11135namespace {
11136 // Visits an initialization expression to see if OrigDecl is evaluated in
11137 // its own initialization and throws a warning if it does.
11138 class SelfReferenceChecker
11139 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11140 Sema &S;
11141 Decl *OrigDecl;
11142 bool isRecordType;
11143 bool isPODType;
11144 bool isReferenceType;
11145
11146 bool isInitList;
11147 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11148
11149 public:
11150 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11151
11152 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11153 S(S), OrigDecl(OrigDecl) {
11154 isPODType = false;
11155 isRecordType = false;
11156 isReferenceType = false;
11157 isInitList = false;
11158 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11159 isPODType = VD->getType().isPODType(S.Context);
11160 isRecordType = VD->getType()->isRecordType();
11161 isReferenceType = VD->getType()->isReferenceType();
11162 }
11163 }
11164
11165 // For most expressions, just call the visitor. For initializer lists,
11166 // track the index of the field being initialized since fields are
11167 // initialized in order allowing use of previously initialized fields.
11168 void CheckExpr(Expr *E) {
11169 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11170 if (!InitList) {
11171 Visit(E);
11172 return;
11173 }
11174
11175 // Track and increment the index here.
11176 isInitList = true;
11177 InitFieldIndex.push_back(0);
11178 for (auto Child : InitList->children()) {
11179 CheckExpr(cast<Expr>(Child));
11180 ++InitFieldIndex.back();
11181 }
11182 InitFieldIndex.pop_back();
11183 }
11184
11185 // Returns true if MemberExpr is checked and no further checking is needed.
11186 // Returns false if additional checking is required.
11187 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11188 llvm::SmallVector<FieldDecl*, 4> Fields;
11189 Expr *Base = E;
11190 bool ReferenceField = false;
11191
11192 // Get the field members used.
11193 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11194 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11195 if (!FD)
11196 return false;
11197 Fields.push_back(FD);
11198 if (FD->getType()->isReferenceType())
11199 ReferenceField = true;
11200 Base = ME->getBase()->IgnoreParenImpCasts();
11201 }
11202
11203 // Keep checking only if the base Decl is the same.
11204 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11205 if (!DRE || DRE->getDecl() != OrigDecl)
11206 return false;
11207
11208 // A reference field can be bound to an unininitialized field.
11209 if (CheckReference && !ReferenceField)
11210 return true;
11211
11212 // Convert FieldDecls to their index number.
11213 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11214 for (const FieldDecl *I : llvm::reverse(Fields))
11215 UsedFieldIndex.push_back(I->getFieldIndex());
11216
11217 // See if a warning is needed by checking the first difference in index
11218 // numbers. If field being used has index less than the field being
11219 // initialized, then the use is safe.
11220 for (auto UsedIter = UsedFieldIndex.begin(),
11221 UsedEnd = UsedFieldIndex.end(),
11222 OrigIter = InitFieldIndex.begin(),
11223 OrigEnd = InitFieldIndex.end();
11224 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11225 if (*UsedIter < *OrigIter)
11226 return true;
11227 if (*UsedIter > *OrigIter)
11228 break;
11229 }
11230
11231 // TODO: Add a different warning which will print the field names.
11232 HandleDeclRefExpr(DRE);
11233 return true;
11234 }
11235
11236 // For most expressions, the cast is directly above the DeclRefExpr.
11237 // For conditional operators, the cast can be outside the conditional
11238 // operator if both expressions are DeclRefExpr's.
11239 void HandleValue(Expr *E) {
11240 E = E->IgnoreParens();
11241 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11242 HandleDeclRefExpr(DRE);
11243 return;
11244 }
11245
11246 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11247 Visit(CO->getCond());
11248 HandleValue(CO->getTrueExpr());
11249 HandleValue(CO->getFalseExpr());
11250 return;
11251 }
11252
11253 if (BinaryConditionalOperator *BCO =
11254 dyn_cast<BinaryConditionalOperator>(E)) {
11255 Visit(BCO->getCond());
11256 HandleValue(BCO->getFalseExpr());
11257 return;
11258 }
11259
11260 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11261 HandleValue(OVE->getSourceExpr());
11262 return;
11263 }
11264
11265 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11266 if (BO->getOpcode() == BO_Comma) {
11267 Visit(BO->getLHS());
11268 HandleValue(BO->getRHS());
11269 return;
11270 }
11271 }
11272
11273 if (isa<MemberExpr>(E)) {
11274 if (isInitList) {
11275 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11276 false /*CheckReference*/))
11277 return;
11278 }
11279
11280 Expr *Base = E->IgnoreParenImpCasts();
11281 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11282 // Check for static member variables and don't warn on them.
11283 if (!isa<FieldDecl>(ME->getMemberDecl()))
11284 return;
11285 Base = ME->getBase()->IgnoreParenImpCasts();
11286 }
11287 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11288 HandleDeclRefExpr(DRE);
11289 return;
11290 }
11291
11292 Visit(E);
11293 }
11294
11295 // Reference types not handled in HandleValue are handled here since all
11296 // uses of references are bad, not just r-value uses.
11297 void VisitDeclRefExpr(DeclRefExpr *E) {
11298 if (isReferenceType)
11299 HandleDeclRefExpr(E);
11300 }
11301
11302 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11303 if (E->getCastKind() == CK_LValueToRValue) {
11304 HandleValue(E->getSubExpr());
11305 return;
11306 }
11307
11308 Inherited::VisitImplicitCastExpr(E);
11309 }
11310
11311 void VisitMemberExpr(MemberExpr *E) {
11312 if (isInitList) {
11313 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11314 return;
11315 }
11316
11317 // Don't warn on arrays since they can be treated as pointers.
11318 if (E->getType()->canDecayToPointerType()) return;
11319
11320 // Warn when a non-static method call is followed by non-static member
11321 // field accesses, which is followed by a DeclRefExpr.
11322 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11323 bool Warn = (MD && !MD->isStatic());
11324 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11325 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11326 if (!isa<FieldDecl>(ME->getMemberDecl()))
11327 Warn = false;
11328 Base = ME->getBase()->IgnoreParenImpCasts();
11329 }
11330
11331 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11332 if (Warn)
11333 HandleDeclRefExpr(DRE);
11334 return;
11335 }
11336
11337 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11338 // Visit that expression.
11339 Visit(Base);
11340 }
11341
11342 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11343 Expr *Callee = E->getCallee();
11344
11345 if (isa<UnresolvedLookupExpr>(Callee))
11346 return Inherited::VisitCXXOperatorCallExpr(E);
11347
11348 Visit(Callee);
11349 for (auto Arg: E->arguments())
11350 HandleValue(Arg->IgnoreParenImpCasts());
11351 }
11352
11353 void VisitUnaryOperator(UnaryOperator *E) {
11354 // For POD record types, addresses of its own members are well-defined.
11355 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11356 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11357 if (!isPODType)
11358 HandleValue(E->getSubExpr());
11359 return;
11360 }
11361
11362 if (E->isIncrementDecrementOp()) {
11363 HandleValue(E->getSubExpr());
11364 return;
11365 }
11366
11367 Inherited::VisitUnaryOperator(E);
11368 }
11369
11370 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11371
11372 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11373 if (E->getConstructor()->isCopyConstructor()) {
11374 Expr *ArgExpr = E->getArg(0);
11375 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11376 if (ILE->getNumInits() == 1)
11377 ArgExpr = ILE->getInit(0);
11378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11379 if (ICE->getCastKind() == CK_NoOp)
11380 ArgExpr = ICE->getSubExpr();
11381 HandleValue(ArgExpr);
11382 return;
11383 }
11384 Inherited::VisitCXXConstructExpr(E);
11385 }
11386
11387 void VisitCallExpr(CallExpr *E) {
11388 // Treat std::move as a use.
11389 if (E->isCallToStdMove()) {
11390 HandleValue(E->getArg(0));
11391 return;
11392 }
11393
11394 Inherited::VisitCallExpr(E);
11395 }
11396
11397 void VisitBinaryOperator(BinaryOperator *E) {
11398 if (E->isCompoundAssignmentOp()) {
11399 HandleValue(E->getLHS());
11400 Visit(E->getRHS());
11401 return;
11402 }
11403
11404 Inherited::VisitBinaryOperator(E);
11405 }
11406
11407 // A custom visitor for BinaryConditionalOperator is needed because the
11408 // regular visitor would check the condition and true expression separately
11409 // but both point to the same place giving duplicate diagnostics.
11410 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11411 Visit(E->getCond());
11412 Visit(E->getFalseExpr());
11413 }
11414
11415 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11416 Decl* ReferenceDecl = DRE->getDecl();
11417 if (OrigDecl != ReferenceDecl) return;
11418 unsigned diag;
11419 if (isReferenceType) {
11420 diag = diag::warn_uninit_self_reference_in_reference_init;
11421 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11422 diag = diag::warn_static_self_reference_in_init;
11423 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11424 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11425 DRE->getDecl()->getType()->isRecordType()) {
11426 diag = diag::warn_uninit_self_reference_in_init;
11427 } else {
11428 // Local variables will be handled by the CFG analysis.
11429 return;
11430 }
11431
11432 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11433 S.PDiag(diag)
11434 << DRE->getDecl() << OrigDecl->getLocation()
11435 << DRE->getSourceRange());
11436 }
11437 };
11438
11439 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11440 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11441 bool DirectInit) {
11442 // Parameters arguments are occassionially constructed with itself,
11443 // for instance, in recursive functions. Skip them.
11444 if (isa<ParmVarDecl>(OrigDecl))
11445 return;
11446
11447 E = E->IgnoreParens();
11448
11449 // Skip checking T a = a where T is not a record or reference type.
11450 // Doing so is a way to silence uninitialized warnings.
11451 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11452 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11453 if (ICE->getCastKind() == CK_LValueToRValue)
11454 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11455 if (DRE->getDecl() == OrigDecl)
11456 return;
11457
11458 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11459 }
11460} // end anonymous namespace
11461
11462namespace {
11463 // Simple wrapper to add the name of a variable or (if no variable is
11464 // available) a DeclarationName into a diagnostic.
11465 struct VarDeclOrName {
11466 VarDecl *VDecl;
11467 DeclarationName Name;
11468
11469 friend const Sema::SemaDiagnosticBuilder &
11470 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11471 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11472 }
11473 };
11474} // end anonymous namespace
11475
11476QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11477 DeclarationName Name, QualType Type,
11478 TypeSourceInfo *TSI,
11479 SourceRange Range, bool DirectInit,
11480 Expr *Init) {
11481 bool IsInitCapture = !VDecl
25.1
'VDecl' is non-null
25.1
'VDecl' is non-null
25.1
'VDecl' is non-null
;
11482 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11483, __PRETTY_FUNCTION__))
26
Assuming the condition is true
27
'?' condition is true
11483 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11483, __PRETTY_FUNCTION__))
;
11484
11485 VarDeclOrName VN{VDecl, Name};
11486
11487 DeducedType *Deduced = Type->getContainedDeducedType();
11488 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11488, __PRETTY_FUNCTION__))
;
28
Assuming 'Deduced' is non-null
29
'?' condition is true
11489
11490 // C++11 [dcl.spec.auto]p3
11491 if (!Init
29.1
'Init' is non-null
29.1
'Init' is non-null
29.1
'Init' is non-null
) {
30
Taking false branch
11492 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11492, __PRETTY_FUNCTION__))
;
11493
11494 // Except for class argument deduction, and then for an initializing
11495 // declaration only, i.e. no static at class scope or extern.
11496 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11497 VDecl->hasExternalStorage() ||
11498 VDecl->isStaticDataMember()) {
11499 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11500 << VDecl->getDeclName() << Type;
11501 return QualType();
11502 }
11503 }
11504
11505 ArrayRef<Expr*> DeduceInits;
11506 if (Init
30.1
'Init' is non-null
30.1
'Init' is non-null
30.1
'Init' is non-null
)
31
Taking true branch
11507 DeduceInits = Init;
32
Value assigned to 'Init'
11508
11509 if (DirectInit) {
33
Assuming 'DirectInit' is true
34
Taking true branch
11510 if (auto *PL
36.1
'PL' is null
36.1
'PL' is null
36.1
'PL' is null
= dyn_cast_or_null<ParenListExpr>(Init))
35
Assuming null pointer is passed into cast
36
Assuming pointer value is null
37
Taking false branch
11511 DeduceInits = PL->exprs();
11512 }
11513
11514 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
38
Assuming 'Deduced' is not a 'DeducedTemplateSpecializationType'
39
Taking false branch
11515 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11515, __PRETTY_FUNCTION__))
;
11516 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11517 InitializationKind Kind = InitializationKind::CreateForInit(
11518 VDecl->getLocation(), DirectInit, Init);
11519 // FIXME: Initialization should not be taking a mutable list of inits.
11520 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11521 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11522 InitsCopy);
11523 }
11524
11525 if (DirectInit
39.1
'DirectInit' is true
39.1
'DirectInit' is true
39.1
'DirectInit' is true
) {
40
Taking true branch
11526 if (auto *IL = dyn_cast<InitListExpr>(Init))
41
Assuming 'IL' is null
42
Taking false branch
11527 DeduceInits = IL->inits();
11528 }
11529
11530 // Deduction only works if we have exactly one source expression.
11531 if (DeduceInits.empty()) {
43
Assuming the condition is true
44
Taking true branch
11532 // It isn't possible to write this directly, but it is possible to
11533 // end up in this situation with "auto x(some_pack...);"
11534 Diag(Init->getBeginLoc(), IsInitCapture
45
Called C++ object pointer is null
11535 ? diag::err_init_capture_no_expression
11536 : diag::err_auto_var_init_no_expression)
11537 << VN << Type << Range;
11538 return QualType();
11539 }
11540
11541 if (DeduceInits.size() > 1) {
11542 Diag(DeduceInits[1]->getBeginLoc(),
11543 IsInitCapture ? diag::err_init_capture_multiple_expressions
11544 : diag::err_auto_var_init_multiple_expressions)
11545 << VN << Type << Range;
11546 return QualType();
11547 }
11548
11549 Expr *DeduceInit = DeduceInits[0];
11550 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
11551 Diag(Init->getBeginLoc(), IsInitCapture
11552 ? diag::err_init_capture_paren_braces
11553 : diag::err_auto_var_init_paren_braces)
11554 << isa<InitListExpr>(Init) << VN << Type << Range;
11555 return QualType();
11556 }
11557
11558 // Expressions default to 'id' when we're in a debugger.
11559 bool DefaultedAnyToId = false;
11560 if (getLangOpts().DebuggerCastResultToId &&
11561 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
11562 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11563 if (Result.isInvalid()) {
11564 return QualType();
11565 }
11566 Init = Result.get();
11567 DefaultedAnyToId = true;
11568 }
11569
11570 // C++ [dcl.decomp]p1:
11571 // If the assignment-expression [...] has array type A and no ref-qualifier
11572 // is present, e has type cv A
11573 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11574 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11575 DeduceInit->getType()->isConstantArrayType())
11576 return Context.getQualifiedType(DeduceInit->getType(),
11577 Type.getQualifiers());
11578
11579 QualType DeducedType;
11580 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11581 if (!IsInitCapture)
11582 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11583 else if (isa<InitListExpr>(Init))
11584 Diag(Range.getBegin(),
11585 diag::err_init_capture_deduction_failure_from_init_list)
11586 << VN
11587 << (DeduceInit->getType().isNull() ? TSI->getType()
11588 : DeduceInit->getType())
11589 << DeduceInit->getSourceRange();
11590 else
11591 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11592 << VN << TSI->getType()
11593 << (DeduceInit->getType().isNull() ? TSI->getType()
11594 : DeduceInit->getType())
11595 << DeduceInit->getSourceRange();
11596 }
11597
11598 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11599 // 'id' instead of a specific object type prevents most of our usual
11600 // checks.
11601 // We only want to warn outside of template instantiations, though:
11602 // inside a template, the 'id' could have come from a parameter.
11603 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11604 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11605 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11606 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11607 }
11608
11609 return DeducedType;
11610}
11611
11612bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11613 Expr *Init) {
11614 assert(!Init || !Init->containsErrors())((!Init || !Init->containsErrors()) ? static_cast<void>
(0) : __assert_fail ("!Init || !Init->containsErrors()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11614, __PRETTY_FUNCTION__))
;
22
Assuming 'Init' is non-null
23
Assuming the condition is true
24
'?' condition is true
11615 QualType DeducedType = deduceVarTypeFromInitializer(
25
Calling 'Sema::deduceVarTypeFromInitializer'
11616 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11617 VDecl->getSourceRange(), DirectInit, Init);
11618 if (DeducedType.isNull()) {
11619 VDecl->setInvalidDecl();
11620 return true;
11621 }
11622
11623 VDecl->setType(DeducedType);
11624 assert(VDecl->isLinkageValid())((VDecl->isLinkageValid()) ? static_cast<void> (0) :
__assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11624, __PRETTY_FUNCTION__))
;
11625
11626 // In ARC, infer lifetime.
11627 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11628 VDecl->setInvalidDecl();
11629
11630 if (getLangOpts().OpenCL)
11631 deduceOpenCLAddressSpace(VDecl);
11632
11633 // If this is a redeclaration, check that the type we just deduced matches
11634 // the previously declared type.
11635 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11636 // We never need to merge the type, because we cannot form an incomplete
11637 // array of auto, nor deduce such a type.
11638 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11639 }
11640
11641 // Check the deduced type is valid for a variable declaration.
11642 CheckVariableDeclarationType(VDecl);
11643 return VDecl->isInvalidDecl();
11644}
11645
11646void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11647 SourceLocation Loc) {
11648 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11649 Init = EWC->getSubExpr();
11650
11651 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11652 Init = CE->getSubExpr();
11653
11654 QualType InitType = Init->getType();
11655 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11657, __PRETTY_FUNCTION__))
11656 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11657, __PRETTY_FUNCTION__))
11657 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11657, __PRETTY_FUNCTION__))
;
11658 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11659 for (auto I : ILE->inits()) {
11660 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11661 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11662 continue;
11663 SourceLocation SL = I->getExprLoc();
11664 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11665 }
11666 return;
11667 }
11668
11669 if (isa<ImplicitValueInitExpr>(Init)) {
11670 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11671 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11672 NTCUK_Init);
11673 } else {
11674 // Assume all other explicit initializers involving copying some existing
11675 // object.
11676 // TODO: ignore any explicit initializers where we can guarantee
11677 // copy-elision.
11678 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11679 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11680 }
11681}
11682
11683namespace {
11684
11685bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11686 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11687 // in the source code or implicitly by the compiler if it is in a union
11688 // defined in a system header and has non-trivial ObjC ownership
11689 // qualifications. We don't want those fields to participate in determining
11690 // whether the containing union is non-trivial.
11691 return FD->hasAttr<UnavailableAttr>();
11692}
11693
11694struct DiagNonTrivalCUnionDefaultInitializeVisitor
11695 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11696 void> {
11697 using Super =
11698 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11699 void>;
11700
11701 DiagNonTrivalCUnionDefaultInitializeVisitor(
11702 QualType OrigTy, SourceLocation OrigLoc,
11703 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11704 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11705
11706 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11707 const FieldDecl *FD, bool InNonTrivialUnion) {
11708 if (const auto *AT = S.Context.getAsArrayType(QT))
11709 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11710 InNonTrivialUnion);
11711 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11712 }
11713
11714 void visitARCStrong(QualType QT, const FieldDecl *FD,
11715 bool InNonTrivialUnion) {
11716 if (InNonTrivialUnion)
11717 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11718 << 1 << 0 << QT << FD->getName();
11719 }
11720
11721 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11722 if (InNonTrivialUnion)
11723 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11724 << 1 << 0 << QT << FD->getName();
11725 }
11726
11727 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11728 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11729 if (RD->isUnion()) {
11730 if (OrigLoc.isValid()) {
11731 bool IsUnion = false;
11732 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11733 IsUnion = OrigRD->isUnion();
11734 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11735 << 0 << OrigTy << IsUnion << UseContext;
11736 // Reset OrigLoc so that this diagnostic is emitted only once.
11737 OrigLoc = SourceLocation();
11738 }
11739 InNonTrivialUnion = true;
11740 }
11741
11742 if (InNonTrivialUnion)
11743 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11744 << 0 << 0 << QT.getUnqualifiedType() << "";
11745
11746 for (const FieldDecl *FD : RD->fields())
11747 if (!shouldIgnoreForRecordTriviality(FD))
11748 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11749 }
11750
11751 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11752
11753 // The non-trivial C union type or the struct/union type that contains a
11754 // non-trivial C union.
11755 QualType OrigTy;
11756 SourceLocation OrigLoc;
11757 Sema::NonTrivialCUnionContext UseContext;
11758 Sema &S;
11759};
11760
11761struct DiagNonTrivalCUnionDestructedTypeVisitor
11762 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11763 using Super =
11764 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11765
11766 DiagNonTrivalCUnionDestructedTypeVisitor(
11767 QualType OrigTy, SourceLocation OrigLoc,
11768 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11769 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11770
11771 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11772 const FieldDecl *FD, bool InNonTrivialUnion) {
11773 if (const auto *AT = S.Context.getAsArrayType(QT))
11774 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11775 InNonTrivialUnion);
11776 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
11777 }
11778
11779 void visitARCStrong(QualType QT, const FieldDecl *FD,
11780 bool InNonTrivialUnion) {
11781 if (InNonTrivialUnion)
11782 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11783 << 1 << 1 << QT << FD->getName();
11784 }
11785
11786 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11787 if (InNonTrivialUnion)
11788 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11789 << 1 << 1 << QT << FD->getName();
11790 }
11791
11792 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11793 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11794 if (RD->isUnion()) {
11795 if (OrigLoc.isValid()) {
11796 bool IsUnion = false;
11797 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11798 IsUnion = OrigRD->isUnion();
11799 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11800 << 1 << OrigTy << IsUnion << UseContext;
11801 // Reset OrigLoc so that this diagnostic is emitted only once.
11802 OrigLoc = SourceLocation();
11803 }
11804 InNonTrivialUnion = true;
11805 }
11806
11807 if (InNonTrivialUnion)
11808 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11809 << 0 << 1 << QT.getUnqualifiedType() << "";
11810
11811 for (const FieldDecl *FD : RD->fields())
11812 if (!shouldIgnoreForRecordTriviality(FD))
11813 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11814 }
11815
11816 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11817 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
11818 bool InNonTrivialUnion) {}
11819
11820 // The non-trivial C union type or the struct/union type that contains a
11821 // non-trivial C union.
11822 QualType OrigTy;
11823 SourceLocation OrigLoc;
11824 Sema::NonTrivialCUnionContext UseContext;
11825 Sema &S;
11826};
11827
11828struct DiagNonTrivalCUnionCopyVisitor
11829 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
11830 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
11831
11832 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
11833 Sema::NonTrivialCUnionContext UseContext,
11834 Sema &S)
11835 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11836
11837 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
11838 const FieldDecl *FD, bool InNonTrivialUnion) {
11839 if (const auto *AT = S.Context.getAsArrayType(QT))
11840 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11841 InNonTrivialUnion);
11842 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
11843 }
11844
11845 void visitARCStrong(QualType QT, const FieldDecl *FD,
11846 bool InNonTrivialUnion) {
11847 if (InNonTrivialUnion)
11848 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11849 << 1 << 2 << QT << FD->getName();
11850 }
11851
11852 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11853 if (InNonTrivialUnion)
11854 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11855 << 1 << 2 << QT << FD->getName();
11856 }
11857
11858 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11859 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11860 if (RD->isUnion()) {
11861 if (OrigLoc.isValid()) {
11862 bool IsUnion = false;
11863 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11864 IsUnion = OrigRD->isUnion();
11865 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11866 << 2 << OrigTy << IsUnion << UseContext;
11867 // Reset OrigLoc so that this diagnostic is emitted only once.
11868 OrigLoc = SourceLocation();
11869 }
11870 InNonTrivialUnion = true;
11871 }
11872
11873 if (InNonTrivialUnion)
11874 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11875 << 0 << 2 << QT.getUnqualifiedType() << "";
11876
11877 for (const FieldDecl *FD : RD->fields())
11878 if (!shouldIgnoreForRecordTriviality(FD))
11879 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11880 }
11881
11882 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
11883 const FieldDecl *FD, bool InNonTrivialUnion) {}
11884 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11885 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
11886 bool InNonTrivialUnion) {}
11887
11888 // The non-trivial C union type or the struct/union type that contains a
11889 // non-trivial C union.
11890 QualType OrigTy;
11891 SourceLocation OrigLoc;
11892 Sema::NonTrivialCUnionContext UseContext;
11893 Sema &S;
11894};
11895
11896} // namespace
11897
11898void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
11899 NonTrivialCUnionContext UseContext,
11900 unsigned NonTrivialKind) {
11901 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11904, __PRETTY_FUNCTION__))
11902 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11904, __PRETTY_FUNCTION__))
11903 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11904, __PRETTY_FUNCTION__))
11904 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11904, __PRETTY_FUNCTION__))
;
11905
11906 if ((NonTrivialKind & NTCUK_Init) &&
11907 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11908 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
11909 .visit(QT, nullptr, false);
11910 if ((NonTrivialKind & NTCUK_Destruct) &&
11911 QT.hasNonTrivialToPrimitiveDestructCUnion())
11912 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
11913 .visit(QT, nullptr, false);
11914 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
11915 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
11916 .visit(QT, nullptr, false);
11917}
11918
11919/// AddInitializerToDecl - Adds the initializer Init to the
11920/// declaration dcl. If DirectInit is true, this is C++ direct
11921/// initialization rather than copy initialization.
11922void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
11923 // If there is no declaration, there was an error parsing it. Just ignore
11924 // the initializer.
11925 if (!RealDecl || RealDecl->isInvalidDecl()) {
1
Assuming 'RealDecl' is non-null
2
Assuming the condition is false
3
Taking false branch
11926 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11927 return;
11928 }
11929
11930 if (CXXMethodDecl *Method
4.1
'Method' is null
4.1
'Method' is null
4.1
'Method' is null
= dyn_cast<CXXMethodDecl>(RealDecl)) {
4
Assuming 'RealDecl' is not a 'CXXMethodDecl'
5
Taking false branch
11931 // Pure-specifiers are handled in ActOnPureSpecifier.
11932 Diag(Method->getLocation(), diag::err_member_function_initialization)
11933 << Method->getDeclName() << Init->getSourceRange();
11934 Method->setInvalidDecl();
11935 return;
11936 }
11937
11938 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6
Assuming 'RealDecl' is a 'VarDecl'
11939 if (!VDecl
6.1
'VDecl' is non-null
6.1
'VDecl' is non-null
6.1
'VDecl' is non-null
) {
7
Taking false branch
11940 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 11940, __PRETTY_FUNCTION__))
;
11941 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11942 RealDecl->setInvalidDecl();
11943 return;
11944 }
11945
11946 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11947 if (VDecl->getType()->isUndeducedType()) {
8
Calling 'Type::isUndeducedType'
12
Returning from 'Type::isUndeducedType'
13
Taking true branch
11948 // Attempt typo correction early so that the type of the init expression can
11949 // be deduced based on the chosen correction if the original init contains a
11950 // TypoExpr.
11951 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11952 if (!Res.isUsable()) {
14
Calling 'ActionResult::isUsable'
17
Returning from 'ActionResult::isUsable'
18
Taking false branch
11953 // There are unresolved typos in Init, just drop them.
11954 // FIXME: improve the recovery strategy to preserve the Init.
11955 RealDecl->setInvalidDecl();
11956 return;
11957 }
11958 if (Res.get()->containsErrors()) {
19
Assuming the condition is false
20
Taking false branch
11959 // Invalidate the decl as we don't know the type for recovery-expr yet.
11960 RealDecl->setInvalidDecl();
11961 VDecl->setInit(Res.get());
11962 return;
11963 }
11964 Init = Res.get();
11965
11966 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
21
Calling 'Sema::DeduceVariableDeclarationType'
11967 return;
11968 }
11969
11970 // dllimport cannot be used on variable definitions.
11971 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11972 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11973 VDecl->setInvalidDecl();
11974 return;
11975 }
11976
11977 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11978 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11979 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11980 VDecl->setInvalidDecl();
11981 return;
11982 }
11983
11984 if (!VDecl->getType()->isDependentType()) {
11985 // A definition must end up with a complete type, which means it must be
11986 // complete with the restriction that an array type might be completed by
11987 // the initializer; note that later code assumes this restriction.
11988 QualType BaseDeclType = VDecl->getType();
11989 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11990 BaseDeclType = Array->getElementType();
11991 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11992 diag::err_typecheck_decl_incomplete_type)) {
11993 RealDecl->setInvalidDecl();
11994 return;
11995 }
11996
11997 // The variable can not have an abstract class type.
11998 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11999 diag::err_abstract_type_in_decl,
12000 AbstractVariableType))
12001 VDecl->setInvalidDecl();
12002 }
12003
12004 // If adding the initializer will turn this declaration into a definition,
12005 // and we already have a definition for this variable, diagnose or otherwise
12006 // handle the situation.
12007 VarDecl *Def;
12008 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
12009 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12010 !VDecl->isThisDeclarationADemotedDefinition() &&
12011 checkVarDeclRedefinition(Def, VDecl))
12012 return;
12013
12014 if (getLangOpts().CPlusPlus) {
12015 // C++ [class.static.data]p4
12016 // If a static data member is of const integral or const
12017 // enumeration type, its declaration in the class definition can
12018 // specify a constant-initializer which shall be an integral
12019 // constant expression (5.19). In that case, the member can appear
12020 // in integral constant expressions. The member shall still be
12021 // defined in a namespace scope if it is used in the program and the
12022 // namespace scope definition shall not contain an initializer.
12023 //
12024 // We already performed a redefinition check above, but for static
12025 // data members we also need to check whether there was an in-class
12026 // declaration with an initializer.
12027 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12028 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12029 << VDecl->getDeclName();
12030 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12031 diag::note_previous_initializer)
12032 << 0;
12033 return;
12034 }
12035
12036 if (VDecl->hasLocalStorage())
12037 setFunctionHasBranchProtectedScope();
12038
12039 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12040 VDecl->setInvalidDecl();
12041 return;
12042 }
12043 }
12044
12045 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12046 // a kernel function cannot be initialized."
12047 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12048 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12049 VDecl->setInvalidDecl();
12050 return;
12051 }
12052
12053 // The LoaderUninitialized attribute acts as a definition (of undef).
12054 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12055 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12056 VDecl->setInvalidDecl();
12057 return;
12058 }
12059
12060 // Get the decls type and save a reference for later, since
12061 // CheckInitializerTypes may change it.
12062 QualType DclT = VDecl->getType(), SavT = DclT;
12063
12064 // Expressions default to 'id' when we're in a debugger
12065 // and we are assigning it to a variable of Objective-C pointer type.
12066 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12067 Init->getType() == Context.UnknownAnyTy) {
12068 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12069 if (Result.isInvalid()) {
12070 VDecl->setInvalidDecl();
12071 return;
12072 }
12073 Init = Result.get();
12074 }
12075
12076 // Perform the initialization.
12077 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12078 if (!VDecl->isInvalidDecl()) {
12079 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12080 InitializationKind Kind = InitializationKind::CreateForInit(
12081 VDecl->getLocation(), DirectInit, Init);
12082
12083 MultiExprArg Args = Init;
12084 if (CXXDirectInit)
12085 Args = MultiExprArg(CXXDirectInit->getExprs(),
12086 CXXDirectInit->getNumExprs());
12087
12088 // Try to correct any TypoExprs in the initialization arguments.
12089 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12090 ExprResult Res = CorrectDelayedTyposInExpr(
12091 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12092 [this, Entity, Kind](Expr *E) {
12093 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12094 return Init.Failed() ? ExprError() : E;
12095 });
12096 if (Res.isInvalid()) {
12097 VDecl->setInvalidDecl();
12098 } else if (Res.get() != Args[Idx]) {
12099 Args[Idx] = Res.get();
12100 }
12101 }
12102 if (VDecl->isInvalidDecl())
12103 return;
12104
12105 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12106 /*TopLevelOfInitList=*/false,
12107 /*TreatUnavailableAsInvalid=*/false);
12108 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12109 if (Result.isInvalid()) {
12110 // If the provied initializer fails to initialize the var decl,
12111 // we attach a recovery expr for better recovery.
12112 auto RecoveryExpr =
12113 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12114 if (RecoveryExpr.get())
12115 VDecl->setInit(RecoveryExpr.get());
12116 return;
12117 }
12118
12119 Init = Result.getAs<Expr>();
12120 }
12121
12122 // Check for self-references within variable initializers.
12123 // Variables declared within a function/method body (except for references)
12124 // are handled by a dataflow analysis.
12125 // This is undefined behavior in C++, but valid in C.
12126 if (getLangOpts().CPlusPlus) {
12127 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12128 VDecl->getType()->isReferenceType()) {
12129 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12130 }
12131 }
12132
12133 // If the type changed, it means we had an incomplete type that was
12134 // completed by the initializer. For example:
12135 // int ary[] = { 1, 3, 5 };
12136 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12137 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12138 VDecl->setType(DclT);
12139
12140 if (!VDecl->isInvalidDecl()) {
12141 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12142
12143 if (VDecl->hasAttr<BlocksAttr>())
12144 checkRetainCycles(VDecl, Init);
12145
12146 // It is safe to assign a weak reference into a strong variable.
12147 // Although this code can still have problems:
12148 // id x = self.weakProp;
12149 // id y = self.weakProp;
12150 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12151 // paths through the function. This should be revisited if
12152 // -Wrepeated-use-of-weak is made flow-sensitive.
12153 if (FunctionScopeInfo *FSI = getCurFunction())
12154 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12155 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12156 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12157 Init->getBeginLoc()))
12158 FSI->markSafeWeakUse(Init);
12159 }
12160
12161 // The initialization is usually a full-expression.
12162 //
12163 // FIXME: If this is a braced initialization of an aggregate, it is not
12164 // an expression, and each individual field initializer is a separate
12165 // full-expression. For instance, in:
12166 //
12167 // struct Temp { ~Temp(); };
12168 // struct S { S(Temp); };
12169 // struct T { S a, b; } t = { Temp(), Temp() }
12170 //
12171 // we should destroy the first Temp before constructing the second.
12172 ExprResult Result =
12173 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12174 /*DiscardedValue*/ false, VDecl->isConstexpr());
12175 if (Result.isInvalid()) {
12176 VDecl->setInvalidDecl();
12177 return;
12178 }
12179 Init = Result.get();
12180
12181 // Attach the initializer to the decl.
12182 VDecl->setInit(Init);
12183
12184 if (VDecl->isLocalVarDecl()) {
12185 // Don't check the initializer if the declaration is malformed.
12186 if (VDecl->isInvalidDecl()) {
12187 // do nothing
12188
12189 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12190 // This is true even in C++ for OpenCL.
12191 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12192 CheckForConstantInitializer(Init, DclT);
12193
12194 // Otherwise, C++ does not restrict the initializer.
12195 } else if (getLangOpts().CPlusPlus) {
12196 // do nothing
12197
12198 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12199 // static storage duration shall be constant expressions or string literals.
12200 } else if (VDecl->getStorageClass() == SC_Static) {
12201 CheckForConstantInitializer(Init, DclT);
12202
12203 // C89 is stricter than C99 for aggregate initializers.
12204 // C89 6.5.7p3: All the expressions [...] in an initializer list
12205 // for an object that has aggregate or union type shall be
12206 // constant expressions.
12207 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12208 isa<InitListExpr>(Init)) {
12209 const Expr *Culprit;
12210 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12211 Diag(Culprit->getExprLoc(),
12212 diag::ext_aggregate_init_not_constant)
12213 << Culprit->getSourceRange();
12214 }
12215 }
12216
12217 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12218 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12219 if (VDecl->hasLocalStorage())
12220 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12221 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12222 VDecl->getLexicalDeclContext()->isRecord()) {
12223 // This is an in-class initialization for a static data member, e.g.,
12224 //
12225 // struct S {
12226 // static const int value = 17;
12227 // };
12228
12229 // C++ [class.mem]p4:
12230 // A member-declarator can contain a constant-initializer only
12231 // if it declares a static member (9.4) of const integral or
12232 // const enumeration type, see 9.4.2.
12233 //
12234 // C++11 [class.static.data]p3:
12235 // If a non-volatile non-inline const static data member is of integral
12236 // or enumeration type, its declaration in the class definition can
12237 // specify a brace-or-equal-initializer in which every initializer-clause
12238 // that is an assignment-expression is a constant expression. A static
12239 // data member of literal type can be declared in the class definition
12240 // with the constexpr specifier; if so, its declaration shall specify a
12241 // brace-or-equal-initializer in which every initializer-clause that is
12242 // an assignment-expression is a constant expression.
12243
12244 // Do nothing on dependent types.
12245 if (DclT->isDependentType()) {
12246
12247 // Allow any 'static constexpr' members, whether or not they are of literal
12248 // type. We separately check that every constexpr variable is of literal
12249 // type.
12250 } else if (VDecl->isConstexpr()) {
12251
12252 // Require constness.
12253 } else if (!DclT.isConstQualified()) {
12254 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12255 << Init->getSourceRange();
12256 VDecl->setInvalidDecl();
12257
12258 // We allow integer constant expressions in all cases.
12259 } else if (DclT->isIntegralOrEnumerationType()) {
12260 // Check whether the expression is a constant expression.
12261 SourceLocation Loc;
12262 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12263 // In C++11, a non-constexpr const static data member with an
12264 // in-class initializer cannot be volatile.
12265 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12266 else if (Init->isValueDependent())
12267 ; // Nothing to check.
12268 else if (Init->isIntegerConstantExpr(Context, &Loc))
12269 ; // Ok, it's an ICE!
12270 else if (Init->getType()->isScopedEnumeralType() &&
12271 Init->isCXX11ConstantExpr(Context))
12272 ; // Ok, it is a scoped-enum constant expression.
12273 else if (Init->isEvaluatable(Context)) {
12274 // If we can constant fold the initializer through heroics, accept it,
12275 // but report this as a use of an extension for -pedantic.
12276 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12277 << Init->getSourceRange();
12278 } else {
12279 // Otherwise, this is some crazy unknown case. Report the issue at the
12280 // location provided by the isIntegerConstantExpr failed check.
12281 Diag(Loc, diag::err_in_class_initializer_non_constant)
12282 << Init->getSourceRange();
12283 VDecl->setInvalidDecl();
12284 }
12285
12286 // We allow foldable floating-point constants as an extension.
12287 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12288 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12289 // it anyway and provide a fixit to add the 'constexpr'.
12290 if (getLangOpts().CPlusPlus11) {
12291 Diag(VDecl->getLocation(),
12292 diag::ext_in_class_initializer_float_type_cxx11)
12293 << DclT << Init->getSourceRange();
12294 Diag(VDecl->getBeginLoc(),
12295 diag::note_in_class_initializer_float_type_cxx11)
12296 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12297 } else {
12298 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12299 << DclT << Init->getSourceRange();
12300
12301 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12302 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12303 << Init->getSourceRange();
12304 VDecl->setInvalidDecl();
12305 }
12306 }
12307
12308 // Suggest adding 'constexpr' in C++11 for literal types.
12309 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12310 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12311 << DclT << Init->getSourceRange()
12312 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12313 VDecl->setConstexpr(true);
12314
12315 } else {
12316 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12317 << DclT << Init->getSourceRange();
12318 VDecl->setInvalidDecl();
12319 }
12320 } else if (VDecl->isFileVarDecl()) {
12321 // In C, extern is typically used to avoid tentative definitions when
12322 // declaring variables in headers, but adding an intializer makes it a
12323 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12324 // In C++, extern is often used to give implictly static const variables
12325 // external linkage, so don't warn in that case. If selectany is present,
12326 // this might be header code intended for C and C++ inclusion, so apply the
12327 // C++ rules.
12328 if (VDecl->getStorageClass() == SC_Extern &&
12329 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12330 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12331 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12332 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12333 Diag(VDecl->getLocation(), diag::warn_extern_init);
12334
12335 // In Microsoft C++ mode, a const variable defined in namespace scope has
12336 // external linkage by default if the variable is declared with
12337 // __declspec(dllexport).
12338 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12339 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12340 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12341 VDecl->setStorageClass(SC_Extern);
12342
12343 // C99 6.7.8p4. All file scoped initializers need to be constant.
12344 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12345 CheckForConstantInitializer(Init, DclT);
12346 }
12347
12348 QualType InitType = Init->getType();
12349 if (!InitType.isNull() &&
12350 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12351 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12352 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12353
12354 // We will represent direct-initialization similarly to copy-initialization:
12355 // int x(1); -as-> int x = 1;
12356 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12357 //
12358 // Clients that want to distinguish between the two forms, can check for
12359 // direct initializer using VarDecl::getInitStyle().
12360 // A major benefit is that clients that don't particularly care about which
12361 // exactly form was it (like the CodeGen) can handle both cases without
12362 // special case code.
12363
12364 // C++ 8.5p11:
12365 // The form of initialization (using parentheses or '=') is generally
12366 // insignificant, but does matter when the entity being initialized has a
12367 // class type.
12368 if (CXXDirectInit) {
12369 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 12369, __PRETTY_FUNCTION__))
;
12370 VDecl->setInitStyle(VarDecl::CallInit);
12371 } else if (DirectInit) {
12372 // This must be list-initialization. No other way is direct-initialization.
12373 VDecl->setInitStyle(VarDecl::ListInit);
12374 }
12375
12376 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12377 DeclsToCheckForDeferredDiags.push_back(VDecl);
12378 CheckCompleteVariableDeclaration(VDecl);
12379}
12380
12381/// ActOnInitializerError - Given that there was an error parsing an
12382/// initializer for the given declaration, try to return to some form
12383/// of sanity.
12384void Sema::ActOnInitializerError(Decl *D) {
12385 // Our main concern here is re-establishing invariants like "a
12386 // variable's type is either dependent or complete".
12387 if (!D || D->isInvalidDecl()) return;
12388
12389 VarDecl *VD = dyn_cast<VarDecl>(D);
12390 if (!VD) return;
12391
12392 // Bindings are not usable if we can't make sense of the initializer.
12393 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12394 for (auto *BD : DD->bindings())
12395 BD->setInvalidDecl();
12396
12397 // Auto types are meaningless if we can't make sense of the initializer.
12398 if (VD->getType()->isUndeducedType()) {
12399 D->setInvalidDecl();
12400 return;
12401 }
12402
12403 QualType Ty = VD->getType();
12404 if (Ty->isDependentType()) return;
12405
12406 // Require a complete type.
12407 if (RequireCompleteType(VD->getLocation(),
12408 Context.getBaseElementType(Ty),
12409 diag::err_typecheck_decl_incomplete_type)) {
12410 VD->setInvalidDecl();
12411 return;
12412 }
12413
12414 // Require a non-abstract type.
12415 if (RequireNonAbstractType(VD->getLocation(), Ty,
12416 diag::err_abstract_type_in_decl,
12417 AbstractVariableType)) {
12418 VD->setInvalidDecl();
12419 return;
12420 }
12421
12422 // Don't bother complaining about constructors or destructors,
12423 // though.
12424}
12425
12426void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12427 // If there is no declaration, there was an error parsing it. Just ignore it.
12428 if (!RealDecl)
12429 return;
12430
12431 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12432 QualType Type = Var->getType();
12433
12434 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12435 if (isa<DecompositionDecl>(RealDecl)) {
12436 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12437 Var->setInvalidDecl();
12438 return;
12439 }
12440
12441 if (Type->isUndeducedType() &&
12442 DeduceVariableDeclarationType(Var, false, nullptr))
12443 return;
12444
12445 // C++11 [class.static.data]p3: A static data member can be declared with
12446 // the constexpr specifier; if so, its declaration shall specify
12447 // a brace-or-equal-initializer.
12448 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12449 // the definition of a variable [...] or the declaration of a static data
12450 // member.
12451 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12452 !Var->isThisDeclarationADemotedDefinition()) {
12453 if (Var->isStaticDataMember()) {
12454 // C++1z removes the relevant rule; the in-class declaration is always
12455 // a definition there.
12456 if (!getLangOpts().CPlusPlus17 &&
12457 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12458 Diag(Var->getLocation(),
12459 diag::err_constexpr_static_mem_var_requires_init)
12460 << Var;
12461 Var->setInvalidDecl();
12462 return;
12463 }
12464 } else {
12465 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12466 Var->setInvalidDecl();
12467 return;
12468 }
12469 }
12470
12471 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12472 // be initialized.
12473 if (!Var->isInvalidDecl() &&
12474 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12475 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12476 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12477 Var->setInvalidDecl();
12478 return;
12479 }
12480
12481 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12482 if (Var->getStorageClass() == SC_Extern) {
12483 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12484 << Var;
12485 Var->setInvalidDecl();
12486 return;
12487 }
12488 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12489 diag::err_typecheck_decl_incomplete_type)) {
12490 Var->setInvalidDecl();
12491 return;
12492 }
12493 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12494 if (!RD->hasTrivialDefaultConstructor()) {
12495 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12496 Var->setInvalidDecl();
12497 return;
12498 }
12499 }
12500 }
12501
12502 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12503 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12504 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12505 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12506 NTCUC_DefaultInitializedObject, NTCUK_Init);
12507
12508
12509 switch (DefKind) {
12510 case VarDecl::Definition:
12511 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12512 break;
12513
12514 // We have an out-of-line definition of a static data member
12515 // that has an in-class initializer, so we type-check this like
12516 // a declaration.
12517 //
12518 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12519
12520 case VarDecl::DeclarationOnly:
12521 // It's only a declaration.
12522
12523 // Block scope. C99 6.7p7: If an identifier for an object is
12524 // declared with no linkage (C99 6.2.2p6), the type for the
12525 // object shall be complete.
12526 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12527 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12528 RequireCompleteType(Var->getLocation(), Type,
12529 diag::err_typecheck_decl_incomplete_type))
12530 Var->setInvalidDecl();
12531
12532 // Make sure that the type is not abstract.
12533 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12534 RequireNonAbstractType(Var->getLocation(), Type,
12535 diag::err_abstract_type_in_decl,
12536 AbstractVariableType))
12537 Var->setInvalidDecl();
12538 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12539 Var->getStorageClass() == SC_PrivateExtern) {
12540 Diag(Var->getLocation(), diag::warn_private_extern);
12541 Diag(Var->getLocation(), diag::note_private_extern);
12542 }
12543
12544 if (Context.getTargetInfo().allowDebugInfoForExternalVar() &&
12545 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12546 ExternalDeclarations.push_back(Var);
12547
12548 return;
12549
12550 case VarDecl::TentativeDefinition:
12551 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12552 // object that has file scope without an initializer, and without a
12553 // storage-class specifier or with the storage-class specifier "static",
12554 // constitutes a tentative definition. Note: A tentative definition with
12555 // external linkage is valid (C99 6.2.2p5).
12556 if (!Var->isInvalidDecl()) {
12557 if (const IncompleteArrayType *ArrayT
12558 = Context.getAsIncompleteArrayType(Type)) {
12559 if (RequireCompleteSizedType(
12560 Var->getLocation(), ArrayT->getElementType(),
12561 diag::err_array_incomplete_or_sizeless_type))
12562 Var->setInvalidDecl();
12563 } else if (Var->getStorageClass() == SC_Static) {
12564 // C99 6.9.2p3: If the declaration of an identifier for an object is
12565 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12566 // declared type shall not be an incomplete type.
12567 // NOTE: code such as the following
12568 // static struct s;
12569 // struct s { int a; };
12570 // is accepted by gcc. Hence here we issue a warning instead of
12571 // an error and we do not invalidate the static declaration.
12572 // NOTE: to avoid multiple warnings, only check the first declaration.
12573 if (Var->isFirstDecl())
12574 RequireCompleteType(Var->getLocation(), Type,
12575 diag::ext_typecheck_decl_incomplete_type);
12576 }
12577 }
12578
12579 // Record the tentative definition; we're done.
12580 if (!Var->isInvalidDecl())
12581 TentativeDefinitions.push_back(Var);
12582 return;
12583 }
12584
12585 // Provide a specific diagnostic for uninitialized variable
12586 // definitions with incomplete array type.
12587 if (Type->isIncompleteArrayType()) {
12588 Diag(Var->getLocation(),
12589 diag::err_typecheck_incomplete_array_needs_initializer);
12590 Var->setInvalidDecl();
12591 return;
12592 }
12593
12594 // Provide a specific diagnostic for uninitialized variable
12595 // definitions with reference type.
12596 if (Type->isReferenceType()) {
12597 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12598 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12599 Var->setInvalidDecl();
12600 return;
12601 }
12602
12603 // Do not attempt to type-check the default initializer for a
12604 // variable with dependent type.
12605 if (Type->isDependentType())
12606 return;
12607
12608 if (Var->isInvalidDecl())
12609 return;
12610
12611 if (!Var->hasAttr<AliasAttr>()) {
12612 if (RequireCompleteType(Var->getLocation(),
12613 Context.getBaseElementType(Type),
12614 diag::err_typecheck_decl_incomplete_type)) {
12615 Var->setInvalidDecl();
12616 return;
12617 }
12618 } else {
12619 return;
12620 }
12621
12622 // The variable can not have an abstract class type.
12623 if (RequireNonAbstractType(Var->getLocation(), Type,
12624 diag::err_abstract_type_in_decl,
12625 AbstractVariableType)) {
12626 Var->setInvalidDecl();
12627 return;
12628 }
12629
12630 // Check for jumps past the implicit initializer. C++0x
12631 // clarifies that this applies to a "variable with automatic
12632 // storage duration", not a "local variable".
12633 // C++11 [stmt.dcl]p3
12634 // A program that jumps from a point where a variable with automatic
12635 // storage duration is not in scope to a point where it is in scope is
12636 // ill-formed unless the variable has scalar type, class type with a
12637 // trivial default constructor and a trivial destructor, a cv-qualified
12638 // version of one of these types, or an array of one of the preceding
12639 // types and is declared without an initializer.
12640 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12641 if (const RecordType *Record
12642 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12643 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12644 // Mark the function (if we're in one) for further checking even if the
12645 // looser rules of C++11 do not require such checks, so that we can
12646 // diagnose incompatibilities with C++98.
12647 if (!CXXRecord->isPOD())
12648 setFunctionHasBranchProtectedScope();
12649 }
12650 }
12651 // In OpenCL, we can't initialize objects in the __local address space,
12652 // even implicitly, so don't synthesize an implicit initializer.
12653 if (getLangOpts().OpenCL &&
12654 Var->getType().getAddressSpace() == LangAS::opencl_local)
12655 return;
12656 // C++03 [dcl.init]p9:
12657 // If no initializer is specified for an object, and the
12658 // object is of (possibly cv-qualified) non-POD class type (or
12659 // array thereof), the object shall be default-initialized; if
12660 // the object is of const-qualified type, the underlying class
12661 // type shall have a user-declared default
12662 // constructor. Otherwise, if no initializer is specified for
12663 // a non- static object, the object and its subobjects, if
12664 // any, have an indeterminate initial value); if the object
12665 // or any of its subobjects are of const-qualified type, the
12666 // program is ill-formed.
12667 // C++0x [dcl.init]p11:
12668 // If no initializer is specified for an object, the object is
12669 // default-initialized; [...].
12670 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12671 InitializationKind Kind
12672 = InitializationKind::CreateDefault(Var->getLocation());
12673
12674 InitializationSequence InitSeq(*this, Entity, Kind, None);
12675 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12676
12677 if (Init.get()) {
12678 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12679 // This is important for template substitution.
12680 Var->setInitStyle(VarDecl::CallInit);
12681 } else if (Init.isInvalid()) {
12682 // If default-init fails, attach a recovery-expr initializer to track
12683 // that initialization was attempted and failed.
12684 auto RecoveryExpr =
12685 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12686 if (RecoveryExpr.get())
12687 Var->setInit(RecoveryExpr.get());
12688 }
12689
12690 CheckCompleteVariableDeclaration(Var);
12691 }
12692}
12693
12694void Sema::ActOnCXXForRangeDecl(Decl *D) {
12695 // If there is no declaration, there was an error parsing it. Ignore it.
12696 if (!D)
12697 return;
12698
12699 VarDecl *VD = dyn_cast<VarDecl>(D);
12700 if (!VD) {
12701 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12702 D->setInvalidDecl();
12703 return;
12704 }
12705
12706 VD->setCXXForRangeDecl(true);
12707
12708 // for-range-declaration cannot be given a storage class specifier.
12709 int Error = -1;
12710 switch (VD->getStorageClass()) {
12711 case SC_None:
12712 break;
12713 case SC_Extern:
12714 Error = 0;
12715 break;
12716 case SC_Static:
12717 Error = 1;
12718 break;
12719 case SC_PrivateExtern:
12720 Error = 2;
12721 break;
12722 case SC_Auto:
12723 Error = 3;
12724 break;
12725 case SC_Register:
12726 Error = 4;
12727 break;
12728 }
12729 if (Error != -1) {
12730 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12731 << VD << Error;
12732 D->setInvalidDecl();
12733 }
12734}
12735
12736StmtResult
12737Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12738 IdentifierInfo *Ident,
12739 ParsedAttributes &Attrs,
12740 SourceLocation AttrEnd) {
12741 // C++1y [stmt.iter]p1:
12742 // A range-based for statement of the form
12743 // for ( for-range-identifier : for-range-initializer ) statement
12744 // is equivalent to
12745 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12746 DeclSpec DS(Attrs.getPool().getFactory());
12747
12748 const char *PrevSpec;
12749 unsigned DiagID;
12750 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12751 getPrintingPolicy());
12752
12753 Declarator D(DS, DeclaratorContext::ForContext);
12754 D.SetIdentifier(Ident, IdentLoc);
12755 D.takeAttributes(Attrs, AttrEnd);
12756
12757 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
12758 IdentLoc);
12759 Decl *Var = ActOnDeclarator(S, D);
12760 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
12761 FinalizeDeclaration(Var);
12762 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
12763 AttrEnd.isValid() ? AttrEnd : IdentLoc);
12764}
12765
12766void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
12767 if (var->isInvalidDecl()) return;
12768
12769 if (getLangOpts().OpenCL) {
12770 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
12771 // initialiser
12772 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
12773 !var->hasInit()) {
12774 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
12775 << 1 /*Init*/;
12776 var->setInvalidDecl();
12777 return;
12778 }
12779 }
12780
12781 // In Objective-C, don't allow jumps past the implicit initialization of a
12782 // local retaining variable.
12783 if (getLangOpts().ObjC &&
12784 var->hasLocalStorage()) {
12785 switch (var->getType().getObjCLifetime()) {
12786 case Qualifiers::OCL_None:
12787 case Qualifiers::OCL_ExplicitNone:
12788 case Qualifiers::OCL_Autoreleasing:
12789 break;
12790
12791 case Qualifiers::OCL_Weak:
12792 case Qualifiers::OCL_Strong:
12793 setFunctionHasBranchProtectedScope();
12794 break;
12795 }
12796 }
12797
12798 if (var->hasLocalStorage() &&
12799 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
12800 setFunctionHasBranchProtectedScope();
12801
12802 // Warn about externally-visible variables being defined without a
12803 // prior declaration. We only want to do this for global
12804 // declarations, but we also specifically need to avoid doing it for
12805 // class members because the linkage of an anonymous class can
12806 // change if it's later given a typedef name.
12807 if (var->isThisDeclarationADefinition() &&
12808 var->getDeclContext()->getRedeclContext()->isFileContext() &&
12809 var->isExternallyVisible() && var->hasLinkage() &&
12810 !var->isInline() && !var->getDescribedVarTemplate() &&
12811 !isa<VarTemplatePartialSpecializationDecl>(var) &&
12812 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
12813 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
12814 var->getLocation())) {
12815 // Find a previous declaration that's not a definition.
12816 VarDecl *prev = var->getPreviousDecl();
12817 while (prev && prev->isThisDeclarationADefinition())
12818 prev = prev->getPreviousDecl();
12819
12820 if (!prev) {
12821 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
12822 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
12823 << /* variable */ 0;
12824 }
12825 }
12826
12827 // Cache the result of checking for constant initialization.
12828 Optional<bool> CacheHasConstInit;
12829 const Expr *CacheCulprit = nullptr;
12830 auto checkConstInit = [&]() mutable {
12831 if (!CacheHasConstInit)
12832 CacheHasConstInit = var->getInit()->isConstantInitializer(
12833 Context, var->getType()->isReferenceType(), &CacheCulprit);
12834 return *CacheHasConstInit;
12835 };
12836
12837 if (var->getTLSKind() == VarDecl::TLS_Static) {
12838 if (var->getType().isDestructedType()) {
12839 // GNU C++98 edits for __thread, [basic.start.term]p3:
12840 // The type of an object with thread storage duration shall not
12841 // have a non-trivial destructor.
12842 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
12843 if (getLangOpts().CPlusPlus11)
12844 Diag(var->getLocation(), diag::note_use_thread_local);
12845 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
12846 if (!checkConstInit()) {
12847 // GNU C++98 edits for __thread, [basic.start.init]p4:
12848 // An object of thread storage duration shall not require dynamic
12849 // initialization.
12850 // FIXME: Need strict checking here.
12851 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
12852 << CacheCulprit->getSourceRange();
12853 if (getLangOpts().CPlusPlus11)
12854 Diag(var->getLocation(), diag::note_use_thread_local);
12855 }
12856 }
12857 }
12858
12859 // Apply section attributes and pragmas to global variables.
12860 bool GlobalStorage = var->hasGlobalStorage();
12861 if (GlobalStorage && var->isThisDeclarationADefinition() &&
12862 !inTemplateInstantiation()) {
12863 PragmaStack<StringLiteral *> *Stack = nullptr;
12864 int SectionFlags = ASTContext::PSF_Read;
12865 if (var->getType().isConstQualified())
12866 Stack = &ConstSegStack;
12867 else if (!var->getInit()) {
12868 Stack = &BSSSegStack;
12869 SectionFlags |= ASTContext::PSF_Write;
12870 } else {
12871 Stack = &DataSegStack;
12872 SectionFlags |= ASTContext::PSF_Write;
12873 }
12874 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
12875 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
12876 SectionFlags |= ASTContext::PSF_Implicit;
12877 UnifySection(SA->getName(), SectionFlags, var);
12878 } else if (Stack->CurrentValue) {
12879 SectionFlags |= ASTContext::PSF_Implicit;
12880 auto SectionName = Stack->CurrentValue->getString();
12881 var->addAttr(SectionAttr::CreateImplicit(
12882 Context, SectionName, Stack->CurrentPragmaLocation,
12883 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
12884 if (UnifySection(SectionName, SectionFlags, var))
12885 var->dropAttr<SectionAttr>();
12886 }
12887
12888 // Apply the init_seg attribute if this has an initializer. If the
12889 // initializer turns out to not be dynamic, we'll end up ignoring this
12890 // attribute.
12891 if (CurInitSeg && var->getInit())
12892 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
12893 CurInitSegLoc,
12894 AttributeCommonInfo::AS_Pragma));
12895 }
12896
12897 if (!var->getType()->isStructureType() && var->hasInit() &&
12898 isa<InitListExpr>(var->getInit())) {
12899 const auto *ILE = cast<InitListExpr>(var->getInit());
12900 unsigned NumInits = ILE->getNumInits();
12901 if (NumInits > 2)
12902 for (unsigned I = 0; I < NumInits; ++I) {
12903 const auto *Init = ILE->getInit(I);
12904 if (!Init)
12905 break;
12906 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12907 if (!SL)
12908 break;
12909
12910 unsigned NumConcat = SL->getNumConcatenated();
12911 // Diagnose missing comma in string array initialization.
12912 // Do not warn when all the elements in the initializer are concatenated
12913 // together. Do not warn for macros too.
12914 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
12915 bool OnlyOneMissingComma = true;
12916 for (unsigned J = I + 1; J < NumInits; ++J) {
12917 const auto *Init = ILE->getInit(J);
12918 if (!Init)
12919 break;
12920 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
12921 if (!SLJ || SLJ->getNumConcatenated() > 1) {
12922 OnlyOneMissingComma = false;
12923 break;
12924 }
12925 }
12926
12927 if (OnlyOneMissingComma) {
12928 SmallVector<FixItHint, 1> Hints;
12929 for (unsigned i = 0; i < NumConcat - 1; ++i)
12930 Hints.push_back(FixItHint::CreateInsertion(
12931 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
12932
12933 Diag(SL->getStrTokenLoc(1),
12934 diag::warn_concatenated_literal_array_init)
12935 << Hints;
12936 Diag(SL->getBeginLoc(),
12937 diag::note_concatenated_string_literal_silence);
12938 }
12939 // In any case, stop now.
12940 break;
12941 }
12942 }
12943 }
12944
12945 // All the following checks are C++ only.
12946 if (!getLangOpts().CPlusPlus) {
12947 // If this variable must be emitted, add it as an initializer for the
12948 // current module.
12949 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12950 Context.addModuleInitializer(ModuleScopes.back().Module, var);
12951 return;
12952 }
12953
12954 if (auto *DD = dyn_cast<DecompositionDecl>(var))
12955 CheckCompleteDecompositionDeclaration(DD);
12956
12957 QualType type = var->getType();
12958 if (type->isDependentType()) return;
12959
12960 if (var->hasAttr<BlocksAttr>())
12961 getCurFunction()->addByrefBlockVar(var);
12962
12963 Expr *Init = var->getInit();
12964 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
12965 QualType baseType = Context.getBaseElementType(type);
12966
12967 if (Init && !Init->isValueDependent()) {
12968 if (var->isConstexpr()) {
12969 SmallVector<PartialDiagnosticAt, 8> Notes;
12970 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
12971 SourceLocation DiagLoc = var->getLocation();
12972 // If the note doesn't add any useful information other than a source
12973 // location, fold it into the primary diagnostic.
12974 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
12975 diag::note_invalid_subexpr_in_const_expr) {
12976 DiagLoc = Notes[0].first;
12977 Notes.clear();
12978 }
12979 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
12980 << var << Init->getSourceRange();
12981 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
12982 Diag(Notes[I].first, Notes[I].second);
12983 }
12984 } else if (var->mightBeUsableInConstantExpressions(Context)) {
12985 // Check whether the initializer of a const variable of integral or
12986 // enumeration type is an ICE now, since we can't tell whether it was
12987 // initialized by a constant expression if we check later.
12988 var->checkInitIsICE();
12989 }
12990
12991 // Don't emit further diagnostics about constexpr globals since they
12992 // were just diagnosed.
12993 if (!var->isConstexpr() && GlobalStorage && var->hasAttr<ConstInitAttr>()) {
12994 // FIXME: Need strict checking in C++03 here.
12995 bool DiagErr = getLangOpts().CPlusPlus11
12996 ? !var->checkInitIsICE() : !checkConstInit();
12997 if (DiagErr) {
12998 auto *Attr = var->getAttr<ConstInitAttr>();
12999 Diag(var->getLocation(), diag::err_require_constant_init_failed)
13000 << Init->getSourceRange();
13001 Diag(Attr->getLocation(),
13002 diag::note_declared_required_constant_init_here)
13003 << Attr->getRange() << Attr->isConstinit();
13004 if (getLangOpts().CPlusPlus11) {
13005 APValue Value;
13006 SmallVector<PartialDiagnosticAt, 8> Notes;
13007 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
13008 for (auto &it : Notes)
13009 Diag(it.first, it.second);
13010 } else {
13011 Diag(CacheCulprit->getExprLoc(),
13012 diag::note_invalid_subexpr_in_const_expr)
13013 << CacheCulprit->getSourceRange();
13014 }
13015 }
13016 }
13017 else if (!var->isConstexpr() && IsGlobal &&
13018 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13019 var->getLocation())) {
13020 // Warn about globals which don't have a constant initializer. Don't
13021 // warn about globals with a non-trivial destructor because we already
13022 // warned about them.
13023 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13024 if (!(RD && !RD->hasTrivialDestructor())) {
13025 if (!checkConstInit())
13026 Diag(var->getLocation(), diag::warn_global_constructor)
13027 << Init->getSourceRange();
13028 }
13029 }
13030 }
13031
13032 // Require the destructor.
13033 if (const RecordType *recordType = baseType->getAs<RecordType>())
13034 FinalizeVarWithDestructor(var, recordType);
13035
13036 // If this variable must be emitted, add it as an initializer for the current
13037 // module.
13038 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13039 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13040}
13041
13042/// Determines if a variable's alignment is dependent.
13043static bool hasDependentAlignment(VarDecl *VD) {
13044 if (VD->getType()->isDependentType())
13045 return true;
13046 for (auto *I : VD->specific_attrs<AlignedAttr>())
13047 if (I->isAlignmentDependent())
13048 return true;
13049 return false;
13050}
13051
13052/// Check if VD needs to be dllexport/dllimport due to being in a
13053/// dllexport/import function.
13054void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13055 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13055, __PRETTY_FUNCTION__))
;
13056
13057 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13058
13059 // Find outermost function when VD is in lambda function.
13060 while (FD && !getDLLAttr(FD) &&
13061 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13062 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13063 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13064 }
13065
13066 if (!FD)
13067 return;
13068
13069 // Static locals inherit dll attributes from their function.
13070 if (Attr *A = getDLLAttr(FD)) {
13071 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13072 NewAttr->setInherited(true);
13073 VD->addAttr(NewAttr);
13074 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13075 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13076 NewAttr->setInherited(true);
13077 VD->addAttr(NewAttr);
13078
13079 // Export this function to enforce exporting this static variable even
13080 // if it is not used in this compilation unit.
13081 if (!FD->hasAttr<DLLExportAttr>())
13082 FD->addAttr(NewAttr);
13083
13084 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13085 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13086 NewAttr->setInherited(true);
13087 VD->addAttr(NewAttr);
13088 }
13089}
13090
13091/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13092/// any semantic actions necessary after any initializer has been attached.
13093void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13094 // Note that we are no longer parsing the initializer for this declaration.
13095 ParsingInitForAutoVars.erase(ThisDecl);
13096
13097 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13098 if (!VD)
13099 return;
13100
13101 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13102 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13103 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13104 if (PragmaClangBSSSection.Valid)
13105 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13106 Context, PragmaClangBSSSection.SectionName,
13107 PragmaClangBSSSection.PragmaLocation,
13108 AttributeCommonInfo::AS_Pragma));
13109 if (PragmaClangDataSection.Valid)
13110 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13111 Context, PragmaClangDataSection.SectionName,
13112 PragmaClangDataSection.PragmaLocation,
13113 AttributeCommonInfo::AS_Pragma));
13114 if (PragmaClangRodataSection.Valid)
13115 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13116 Context, PragmaClangRodataSection.SectionName,
13117 PragmaClangRodataSection.PragmaLocation,
13118 AttributeCommonInfo::AS_Pragma));
13119 if (PragmaClangRelroSection.Valid)
13120 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13121 Context, PragmaClangRelroSection.SectionName,
13122 PragmaClangRelroSection.PragmaLocation,
13123 AttributeCommonInfo::AS_Pragma));
13124 }
13125
13126 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13127 for (auto *BD : DD->bindings()) {
13128 FinalizeDeclaration(BD);
13129 }
13130 }
13131
13132 checkAttributesAfterMerging(*this, *VD);
13133
13134 // Perform TLS alignment check here after attributes attached to the variable
13135 // which may affect the alignment have been processed. Only perform the check
13136 // if the target has a maximum TLS alignment (zero means no constraints).
13137 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13138 // Protect the check so that it's not performed on dependent types and
13139 // dependent alignments (we can't determine the alignment in that case).
13140 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
13141 !VD->isInvalidDecl()) {
13142 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13143 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13144 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13145 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13146 << (unsigned)MaxAlignChars.getQuantity();
13147 }
13148 }
13149 }
13150
13151 if (VD->isStaticLocal()) {
13152 CheckStaticLocalForDllExport(VD);
13153
13154 if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
13155 // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
13156 // function, only __shared__ variables or variables without any device
13157 // memory qualifiers may be declared with static storage class.
13158 // Note: It is unclear how a function-scope non-const static variable
13159 // without device memory qualifier is implemented, therefore only static
13160 // const variable without device memory qualifier is allowed.
13161 [&]() {
13162 if (!getLangOpts().CUDA)
13163 return;
13164 if (VD->hasAttr<CUDASharedAttr>())
13165 return;
13166 if (VD->getType().isConstQualified() &&
13167 !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
13168 return;
13169 if (CUDADiagIfDeviceCode(VD->getLocation(),
13170 diag::err_device_static_local_var)
13171 << CurrentCUDATarget())
13172 VD->setInvalidDecl();
13173 }();
13174 }
13175 }
13176
13177 // Perform check for initializers of device-side global variables.
13178 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13179 // 7.5). We must also apply the same checks to all __shared__
13180 // variables whether they are local or not. CUDA also allows
13181 // constant initializers for __constant__ and __device__ variables.
13182 if (getLangOpts().CUDA)
13183 checkAllowedCUDAInitializer(VD);
13184
13185 // Grab the dllimport or dllexport attribute off of the VarDecl.
13186 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13187
13188 // Imported static data members cannot be defined out-of-line.
13189 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13190 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13191 VD->isThisDeclarationADefinition()) {
13192 // We allow definitions of dllimport class template static data members
13193 // with a warning.
13194 CXXRecordDecl *Context =
13195 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13196 bool IsClassTemplateMember =
13197 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13198 Context->getDescribedClassTemplate();
13199
13200 Diag(VD->getLocation(),
13201 IsClassTemplateMember
13202 ? diag::warn_attribute_dllimport_static_field_definition
13203 : diag::err_attribute_dllimport_static_field_definition);
13204 Diag(IA->getLocation(), diag::note_attribute);
13205 if (!IsClassTemplateMember)
13206 VD->setInvalidDecl();
13207 }
13208 }
13209
13210 // dllimport/dllexport variables cannot be thread local, their TLS index
13211 // isn't exported with the variable.
13212 if (DLLAttr && VD->getTLSKind()) {
13213 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13214 if (F && getDLLAttr(F)) {
13215 assert(VD->isStaticLocal())((VD->isStaticLocal()) ? static_cast<void> (0) : __assert_fail
("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13215, __PRETTY_FUNCTION__))
;
13216 // But if this is a static local in a dlimport/dllexport function, the
13217 // function will never be inlined, which means the var would never be
13218 // imported, so having it marked import/export is safe.
13219 } else {
13220 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13221 << DLLAttr;
13222 VD->setInvalidDecl();
13223 }
13224 }
13225
13226 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13227 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13228 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
13229 VD->dropAttr<UsedAttr>();
13230 }
13231 }
13232
13233 const DeclContext *DC = VD->getDeclContext();
13234 // If there's a #pragma GCC visibility in scope, and this isn't a class
13235 // member, set the visibility of this variable.
13236 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13237 AddPushedVisibilityAttribute(VD);
13238
13239 // FIXME: Warn on unused var template partial specializations.
13240 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13241 MarkUnusedFileScopedDecl(VD);
13242
13243 // Now we have parsed the initializer and can update the table of magic
13244 // tag values.
13245 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13246 !VD->getType()->isIntegralOrEnumerationType())
13247 return;
13248
13249 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13250 const Expr *MagicValueExpr = VD->getInit();
13251 if (!MagicValueExpr) {
13252 continue;
13253 }
13254 Optional<llvm::APSInt> MagicValueInt;
13255 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13256 Diag(I->getRange().getBegin(),
13257 diag::err_type_tag_for_datatype_not_ice)
13258 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13259 continue;
13260 }
13261 if (MagicValueInt->getActiveBits() > 64) {
13262 Diag(I->getRange().getBegin(),
13263 diag::err_type_tag_for_datatype_too_large)
13264 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13265 continue;
13266 }
13267 uint64_t MagicValue = MagicValueInt->getZExtValue();
13268 RegisterTypeTagForDatatype(I->getArgumentKind(),
13269 MagicValue,
13270 I->getMatchingCType(),
13271 I->getLayoutCompatible(),
13272 I->getMustBeNull());
13273 }
13274}
13275
13276static bool hasDeducedAuto(DeclaratorDecl *DD) {
13277 auto *VD = dyn_cast<VarDecl>(DD);
13278 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13279}
13280
13281Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13282 ArrayRef<Decl *> Group) {
13283 SmallVector<Decl*, 8> Decls;
13284
13285 if (DS.isTypeSpecOwned())
13286 Decls.push_back(DS.getRepAsDecl());
13287
13288 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13289 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13290 bool DiagnosedMultipleDecomps = false;
13291 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13292 bool DiagnosedNonDeducedAuto = false;
13293
13294 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13295 if (Decl *D = Group[i]) {
13296 // For declarators, there are some additional syntactic-ish checks we need
13297 // to perform.
13298 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13299 if (!FirstDeclaratorInGroup)
13300 FirstDeclaratorInGroup = DD;
13301 if (!FirstDecompDeclaratorInGroup)
13302 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13303 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13304 !hasDeducedAuto(DD))
13305 FirstNonDeducedAutoInGroup = DD;
13306
13307 if (FirstDeclaratorInGroup != DD) {
13308 // A decomposition declaration cannot be combined with any other
13309 // declaration in the same group.
13310 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13311 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13312 diag::err_decomp_decl_not_alone)
13313 << FirstDeclaratorInGroup->getSourceRange()
13314 << DD->getSourceRange();
13315 DiagnosedMultipleDecomps = true;
13316 }
13317
13318 // A declarator that uses 'auto' in any way other than to declare a
13319 // variable with a deduced type cannot be combined with any other
13320 // declarator in the same group.
13321 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13322 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13323 diag::err_auto_non_deduced_not_alone)
13324 << FirstNonDeducedAutoInGroup->getType()
13325 ->hasAutoForTrailingReturnType()
13326 << FirstDeclaratorInGroup->getSourceRange()
13327 << DD->getSourceRange();
13328 DiagnosedNonDeducedAuto = true;
13329 }
13330 }
13331 }
13332
13333 Decls.push_back(D);
13334 }
13335 }
13336
13337 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13338 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13339 handleTagNumbering(Tag, S);
13340 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13341 getLangOpts().CPlusPlus)
13342 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13343 }
13344 }
13345
13346 return BuildDeclaratorGroup(Decls);
13347}
13348
13349/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13350/// group, performing any necessary semantic checking.
13351Sema::DeclGroupPtrTy
13352Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13353 // C++14 [dcl.spec.auto]p7: (DR1347)
13354 // If the type that replaces the placeholder type is not the same in each
13355 // deduction, the program is ill-formed.
13356 if (Group.size() > 1) {
13357 QualType Deduced;
13358 VarDecl *DeducedDecl = nullptr;
13359 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13360 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13361 if (!D || D->isInvalidDecl())
13362 break;
13363 DeducedType *DT = D->getType()->getContainedDeducedType();
13364 if (!DT || DT->getDeducedType().isNull())
13365 continue;
13366 if (Deduced.isNull()) {
13367 Deduced = DT->getDeducedType();
13368 DeducedDecl = D;
13369 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13370 auto *AT = dyn_cast<AutoType>(DT);
13371 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13372 diag::err_auto_different_deductions)
13373 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13374 << DeducedDecl->getDeclName() << DT->getDeducedType()
13375 << D->getDeclName();
13376 if (DeducedDecl->hasInit())
13377 Dia << DeducedDecl->getInit()->getSourceRange();
13378 if (D->getInit())
13379 Dia << D->getInit()->getSourceRange();
13380 D->setInvalidDecl();
13381 break;
13382 }
13383 }
13384 }
13385
13386 ActOnDocumentableDecls(Group);
13387
13388 return DeclGroupPtrTy::make(
13389 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13390}
13391
13392void Sema::ActOnDocumentableDecl(Decl *D) {
13393 ActOnDocumentableDecls(D);
13394}
13395
13396void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13397 // Don't parse the comment if Doxygen diagnostics are ignored.
13398 if (Group.empty() || !Group[0])
13399 return;
13400
13401 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13402 Group[0]->getLocation()) &&
13403 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13404 Group[0]->getLocation()))
13405 return;
13406
13407 if (Group.size() >= 2) {
13408 // This is a decl group. Normally it will contain only declarations
13409 // produced from declarator list. But in case we have any definitions or
13410 // additional declaration references:
13411 // 'typedef struct S {} S;'
13412 // 'typedef struct S *S;'
13413 // 'struct S *pS;'
13414 // FinalizeDeclaratorGroup adds these as separate declarations.
13415 Decl *MaybeTagDecl = Group[0];
13416 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13417 Group = Group.slice(1);
13418 }
13419 }
13420
13421 // FIMXE: We assume every Decl in the group is in the same file.
13422 // This is false when preprocessor constructs the group from decls in
13423 // different files (e. g. macros or #include).
13424 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13425}
13426
13427/// Common checks for a parameter-declaration that should apply to both function
13428/// parameters and non-type template parameters.
13429void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13430 // Check that there are no default arguments inside the type of this
13431 // parameter.
13432 if (getLangOpts().CPlusPlus)
13433 CheckExtraCXXDefaultArguments(D);
13434
13435 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13436 if (D.getCXXScopeSpec().isSet()) {
13437 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13438 << D.getCXXScopeSpec().getRange();
13439 }
13440
13441 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13442 // simple identifier except [...irrelevant cases...].
13443 switch (D.getName().getKind()) {
13444 case UnqualifiedIdKind::IK_Identifier:
13445 break;
13446
13447 case UnqualifiedIdKind::IK_OperatorFunctionId:
13448 case UnqualifiedIdKind::IK_ConversionFunctionId:
13449 case UnqualifiedIdKind::IK_LiteralOperatorId:
13450 case UnqualifiedIdKind::IK_ConstructorName:
13451 case UnqualifiedIdKind::IK_DestructorName:
13452 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13453 case UnqualifiedIdKind::IK_DeductionGuideName:
13454 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13455 << GetNameForDeclarator(D).getName();
13456 break;
13457
13458 case UnqualifiedIdKind::IK_TemplateId:
13459 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13460 // GetNameForDeclarator would not produce a useful name in this case.
13461 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13462 break;
13463 }
13464}
13465
13466/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13467/// to introduce parameters into function prototype scope.
13468Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13469 const DeclSpec &DS = D.getDeclSpec();
13470
13471 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13472
13473 // C++03 [dcl.stc]p2 also permits 'auto'.
13474 StorageClass SC = SC_None;
13475 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13476 SC = SC_Register;
13477 // In C++11, the 'register' storage class specifier is deprecated.
13478 // In C++17, it is not allowed, but we tolerate it as an extension.
13479 if (getLangOpts().CPlusPlus11) {
13480 Diag(DS.getStorageClassSpecLoc(),
13481 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13482 : diag::warn_deprecated_register)
13483 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13484 }
13485 } else if (getLangOpts().CPlusPlus &&
13486 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13487 SC = SC_Auto;
13488 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13489 Diag(DS.getStorageClassSpecLoc(),
13490 diag::err_invalid_storage_class_in_func_decl);
13491 D.getMutableDeclSpec().ClearStorageClassSpecs();
13492 }
13493
13494 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13495 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13496 << DeclSpec::getSpecifierName(TSCS);
13497 if (DS.isInlineSpecified())
13498 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13499 << getLangOpts().CPlusPlus17;
13500 if (DS.hasConstexprSpecifier())
13501 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13502 << 0 << D.getDeclSpec().getConstexprSpecifier();
13503
13504 DiagnoseFunctionSpecifiers(DS);
13505
13506 CheckFunctionOrTemplateParamDeclarator(S, D);
13507
13508 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13509 QualType parmDeclType = TInfo->getType();
13510
13511 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13512 IdentifierInfo *II = D.getIdentifier();
13513 if (II) {
13514 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13515 ForVisibleRedeclaration);
13516 LookupName(R, S);
13517 if (R.isSingleResult()) {
13518 NamedDecl *PrevDecl = R.getFoundDecl();
13519 if (PrevDecl->isTemplateParameter()) {
13520 // Maybe we will complain about the shadowed template parameter.
13521 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13522 // Just pretend that we didn't see the previous declaration.
13523 PrevDecl = nullptr;
13524 } else if (S->isDeclScope(PrevDecl)) {
13525 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13526 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13527
13528 // Recover by removing the name
13529 II = nullptr;
13530 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13531 D.setInvalidType(true);
13532 }
13533 }
13534 }
13535
13536 // Temporarily put parameter variables in the translation unit, not
13537 // the enclosing context. This prevents them from accidentally
13538 // looking like class members in C++.
13539 ParmVarDecl *New =
13540 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13541 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13542
13543 if (D.isInvalidType())
13544 New->setInvalidDecl();
13545
13546 assert(S->isFunctionPrototypeScope())((S->isFunctionPrototypeScope()) ? static_cast<void>
(0) : __assert_fail ("S->isFunctionPrototypeScope()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13546, __PRETTY_FUNCTION__))
;
13547 assert(S->getFunctionPrototypeDepth() >= 1)((S->getFunctionPrototypeDepth() >= 1) ? static_cast<
void> (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13547, __PRETTY_FUNCTION__))
;
13548 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13549 S->getNextFunctionPrototypeIndex());
13550
13551 // Add the parameter declaration into this scope.
13552 S->AddDecl(New);
13553 if (II)
13554 IdResolver.AddDecl(New);
13555
13556 ProcessDeclAttributes(S, New, D);
13557
13558 if (D.getDeclSpec().isModulePrivateSpecified())
13559 Diag(New->getLocation(), diag::err_module_private_local)
13560 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13561 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13562
13563 if (New->hasAttr<BlocksAttr>()) {
13564 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13565 }
13566
13567 if (getLangOpts().OpenCL)
13568 deduceOpenCLAddressSpace(New);
13569
13570 return New;
13571}
13572
13573/// Synthesizes a variable for a parameter arising from a
13574/// typedef.
13575ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13576 SourceLocation Loc,
13577 QualType T) {
13578 /* FIXME: setting StartLoc == Loc.
13579 Would it be worth to modify callers so as to provide proper source
13580 location for the unnamed parameters, embedding the parameter's type? */
13581 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13582 T, Context.getTrivialTypeSourceInfo(T, Loc),
13583 SC_None, nullptr);
13584 Param->setImplicit();
13585 return Param;
13586}
13587
13588void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13589 // Don't diagnose unused-parameter errors in template instantiations; we
13590 // will already have done so in the template itself.
13591 if (inTemplateInstantiation())
13592 return;
13593
13594 for (const ParmVarDecl *Parameter : Parameters) {
13595 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13596 !Parameter->hasAttr<UnusedAttr>()) {
13597 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13598 << Parameter->getDeclName();
13599 }
13600 }
13601}
13602
13603void Sema::DiagnoseSizeOfParametersAndReturnValue(
13604 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13605 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13606 return;
13607
13608 // Warn if the return value is pass-by-value and larger than the specified
13609 // threshold.
13610 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13611 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13612 if (Size > LangOpts.NumLargeByValueCopy)
13613 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13614 }
13615
13616 // Warn if any parameter is pass-by-value and larger than the specified
13617 // threshold.
13618 for (const ParmVarDecl *Parameter : Parameters) {
13619 QualType T = Parameter->getType();
13620 if (T->isDependentType() || !T.isPODType(Context))
13621 continue;
13622 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13623 if (Size > LangOpts.NumLargeByValueCopy)
13624 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13625 << Parameter << Size;
13626 }
13627}
13628
13629ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13630 SourceLocation NameLoc, IdentifierInfo *Name,
13631 QualType T, TypeSourceInfo *TSInfo,
13632 StorageClass SC) {
13633 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13634 if (getLangOpts().ObjCAutoRefCount &&
13635 T.getObjCLifetime() == Qualifiers::OCL_None &&
13636 T->isObjCLifetimeType()) {
13637
13638 Qualifiers::ObjCLifetime lifetime;
13639
13640 // Special cases for arrays:
13641 // - if it's const, use __unsafe_unretained
13642 // - otherwise, it's an error
13643 if (T->isArrayType()) {
13644 if (!T.isConstQualified()) {
13645 if (DelayedDiagnostics.shouldDelayDiagnostics())
13646 DelayedDiagnostics.add(
13647 sema::DelayedDiagnostic::makeForbiddenType(
13648 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13649 else
13650 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13651 << TSInfo->getTypeLoc().getSourceRange();
13652 }
13653 lifetime = Qualifiers::OCL_ExplicitNone;
13654 } else {
13655 lifetime = T->getObjCARCImplicitLifetime();
13656 }
13657 T = Context.getLifetimeQualifiedType(T, lifetime);
13658 }
13659
13660 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13661 Context.getAdjustedParameterType(T),
13662 TSInfo, SC, nullptr);
13663
13664 // Make a note if we created a new pack in the scope of a lambda, so that
13665 // we know that references to that pack must also be expanded within the
13666 // lambda scope.
13667 if (New->isParameterPack())
13668 if (auto *LSI = getEnclosingLambda())
13669 LSI->LocalPacks.push_back(New);
13670
13671 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13672 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13673 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13674 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13675
13676 // Parameters can not be abstract class types.
13677 // For record types, this is done by the AbstractClassUsageDiagnoser once
13678 // the class has been completely parsed.
13679 if (!CurContext->isRecord() &&
13680 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13681 AbstractParamType))
13682 New->setInvalidDecl();
13683
13684 // Parameter declarators cannot be interface types. All ObjC objects are
13685 // passed by reference.
13686 if (T->isObjCObjectType()) {
13687 SourceLocation TypeEndLoc =
13688 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13689 Diag(NameLoc,
13690 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13691 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13692 T = Context.getObjCObjectPointerType(T);
13693 New->setType(T);
13694 }
13695
13696 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13697 // duration shall not be qualified by an address-space qualifier."
13698 // Since all parameters have automatic store duration, they can not have
13699 // an address space.
13700 if (T.getAddressSpace() != LangAS::Default &&
13701 // OpenCL allows function arguments declared to be an array of a type
13702 // to be qualified with an address space.
13703 !(getLangOpts().OpenCL &&
13704 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13705 Diag(NameLoc, diag::err_arg_with_address_space);
13706 New->setInvalidDecl();
13707 }
13708
13709 return New;
13710}
13711
13712void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13713 SourceLocation LocAfterDecls) {
13714 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13715
13716 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13717 // for a K&R function.
13718 if (!FTI.hasPrototype) {
13719 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13720 --i;
13721 if (FTI.Params[i].Param == nullptr) {
13722 SmallString<256> Code;
13723 llvm::raw_svector_ostream(Code)
13724 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13725 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13726 << FTI.Params[i].Ident
13727 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13728
13729 // Implicitly declare the argument as type 'int' for lack of a better
13730 // type.
13731 AttributeFactory attrs;
13732 DeclSpec DS(attrs);
13733 const char* PrevSpec; // unused
13734 unsigned DiagID; // unused
13735 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13736 DiagID, Context.getPrintingPolicy());
13737 // Use the identifier location for the type source range.
13738 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13739 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13740 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
13741 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13742 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13743 }
13744 }
13745 }
13746}
13747
13748Decl *
13749Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13750 MultiTemplateParamsArg TemplateParameterLists,
13751 SkipBodyInfo *SkipBody) {
13752 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13752, __PRETTY_FUNCTION__))
;
13753 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13753, __PRETTY_FUNCTION__))
;
13754 Scope *ParentScope = FnBodyScope->getParent();
13755
13756 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
13757 // we define a non-templated function definition, we will create a declaration
13758 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
13759 // The base function declaration will have the equivalent of an `omp declare
13760 // variant` annotation which specifies the mangled definition as a
13761 // specialization function under the OpenMP context defined as part of the
13762 // `omp begin declare variant`.
13763 SmallVector<FunctionDecl *, 4> Bases;
13764 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
13765 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
13766 ParentScope, D, TemplateParameterLists, Bases);
13767
13768 D.setFunctionDefinitionKind(FDK_Definition);
13769 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
13770 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
13771
13772 if (!Bases.empty())
13773 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
13774
13775 return Dcl;
13776}
13777
13778void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
13779 Consumer.HandleInlineFunctionDefinition(D);
13780}
13781
13782static bool
13783ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
13784 const FunctionDecl *&PossiblePrototype) {
13785 // Don't warn about invalid declarations.
13786 if (FD->isInvalidDecl())
13787 return false;
13788
13789 // Or declarations that aren't global.
13790 if (!FD->isGlobal())
13791 return false;
13792
13793 // Don't warn about C++ member functions.
13794 if (isa<CXXMethodDecl>(FD))
13795 return false;
13796
13797 // Don't warn about 'main'.
13798 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
13799 if (IdentifierInfo *II = FD->getIdentifier())
13800 if (II->isStr("main"))
13801 return false;
13802
13803 // Don't warn about inline functions.
13804 if (FD->isInlined())
13805 return false;
13806
13807 // Don't warn about function templates.
13808 if (FD->getDescribedFunctionTemplate())
13809 return false;
13810
13811 // Don't warn about function template specializations.
13812 if (FD->isFunctionTemplateSpecialization())
13813 return false;
13814
13815 // Don't warn for OpenCL kernels.
13816 if (FD->hasAttr<OpenCLKernelAttr>())
13817 return false;
13818
13819 // Don't warn on explicitly deleted functions.
13820 if (FD->isDeleted())
13821 return false;
13822
13823 for (const FunctionDecl *Prev = FD->getPreviousDecl();
13824 Prev; Prev = Prev->getPreviousDecl()) {
13825 // Ignore any declarations that occur in function or method
13826 // scope, because they aren't visible from the header.
13827 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
13828 continue;
13829
13830 PossiblePrototype = Prev;
13831 return Prev->getType()->isFunctionNoProtoType();
13832 }
13833
13834 return true;
13835}
13836
13837void
13838Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
13839 const FunctionDecl *EffectiveDefinition,
13840 SkipBodyInfo *SkipBody) {
13841 const FunctionDecl *Definition = EffectiveDefinition;
13842 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
13843 // If this is a friend function defined in a class template, it does not
13844 // have a body until it is used, nevertheless it is a definition, see
13845 // [temp.inst]p2:
13846 //
13847 // ... for the purpose of determining whether an instantiated redeclaration
13848 // is valid according to [basic.def.odr] and [class.mem], a declaration that
13849 // corresponds to a definition in the template is considered to be a
13850 // definition.
13851 //
13852 // The following code must produce redefinition error:
13853 //
13854 // template<typename T> struct C20 { friend void func_20() {} };
13855 // C20<int> c20i;
13856 // void func_20() {}
13857 //
13858 for (auto I : FD->redecls()) {
13859 if (I != FD && !I->isInvalidDecl() &&
13860 I->getFriendObjectKind() != Decl::FOK_None) {
13861 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
13862 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
13863 // A merged copy of the same function, instantiated as a member of
13864 // the same class, is OK.
13865 if (declaresSameEntity(OrigFD, Original) &&
13866 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
13867 cast<Decl>(FD->getLexicalDeclContext())))
13868 continue;
13869 }
13870
13871 if (Original->isThisDeclarationADefinition()) {
13872 Definition = I;
13873 break;
13874 }
13875 }
13876 }
13877 }
13878 }
13879
13880 if (!Definition)
13881 // Similar to friend functions a friend function template may be a
13882 // definition and do not have a body if it is instantiated in a class
13883 // template.
13884 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
13885 for (auto I : FTD->redecls()) {
13886 auto D = cast<FunctionTemplateDecl>(I);
13887 if (D != FTD) {
13888 assert(!D->isThisDeclarationADefinition() &&((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13889, __PRETTY_FUNCTION__))
13889 "More than one definition in redeclaration chain")((!D->isThisDeclarationADefinition() && "More than one definition in redeclaration chain"
) ? static_cast<void> (0) : __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 13889, __PRETTY_FUNCTION__))
;
13890 if (D->getFriendObjectKind() != Decl::FOK_None)
13891 if (FunctionTemplateDecl *FT =
13892 D->getInstantiatedFromMemberTemplate()) {
13893 if (FT->isThisDeclarationADefinition()) {
13894 Definition = D->getTemplatedDecl();
13895 break;
13896 }
13897 }
13898 }
13899 }
13900 }
13901
13902 if (!Definition)
13903 return;
13904
13905 if (canRedefineFunction(Definition, getLangOpts()))
13906 return;
13907
13908 // Don't emit an error when this is redefinition of a typo-corrected
13909 // definition.
13910 if (TypoCorrectedFunctionDefinitions.count(Definition))
13911 return;
13912
13913 // If we don't have a visible definition of the function, and it's inline or
13914 // a template, skip the new definition.
13915 if (SkipBody && !hasVisibleDefinition(Definition) &&
13916 (Definition->getFormalLinkage() == InternalLinkage ||
13917 Definition->isInlined() ||
13918 Definition->getDescribedFunctionTemplate() ||
13919 Definition->getNumTemplateParameterLists())) {
13920 SkipBody->ShouldSkip = true;
13921 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
13922 if (auto *TD = Definition->getDescribedFunctionTemplate())
13923 makeMergedDefinitionVisible(TD);
13924 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
13925 return;
13926 }
13927
13928 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
13929 Definition->getStorageClass() == SC_Extern)
13930 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
13931 << FD << getLangOpts().CPlusPlus;
13932 else
13933 Diag(FD->getLocation(), diag::err_redefinition) << FD;
13934
13935 Diag(Definition->getLocation(), diag::note_previous_definition);
13936 FD->setInvalidDecl();
13937}
13938
13939static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
13940 Sema &S) {
13941 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
13942
13943 LambdaScopeInfo *LSI = S.PushLambdaScope();
13944 LSI->CallOperator = CallOperator;
13945 LSI->Lambda = LambdaClass;
13946 LSI->ReturnType = CallOperator->getReturnType();
13947 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
13948
13949 if (LCD == LCD_None)
13950 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
13951 else if (LCD == LCD_ByCopy)
13952 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
13953 else if (LCD == LCD_ByRef)
13954 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
13955 DeclarationNameInfo DNI = CallOperator->getNameInfo();
13956
13957 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
13958 LSI->Mutable = !CallOperator->isConst();
13959
13960 // Add the captures to the LSI so they can be noted as already
13961 // captured within tryCaptureVar.
13962 auto I = LambdaClass->field_begin();
13963 for (const auto &C : LambdaClass->captures()) {
13964 if (C.capturesVariable()) {
13965 VarDecl *VD = C.getCapturedVar();
13966 if (VD->isInitCapture())
13967 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
13968 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
13969 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
13970 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
13971 /*EllipsisLoc*/C.isPackExpansion()
13972 ? C.getEllipsisLoc() : SourceLocation(),
13973 I->getType(), /*Invalid*/false);
13974
13975 } else if (C.capturesThis()) {
13976 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
13977 C.getCaptureKind() == LCK_StarThis);
13978 } else {
13979 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
13980 I->getType());
13981 }
13982 ++I;
13983 }
13984}
13985
13986Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
13987 SkipBodyInfo *SkipBody) {
13988 if (!D) {
13989 // Parsing the function declaration failed in some way. Push on a fake scope
13990 // anyway so we can try to parse the function body.
13991 PushFunctionScope();
13992 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
13993 return D;
13994 }
13995
13996 FunctionDecl *FD = nullptr;
13997
13998 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
13999 FD = FunTmpl->getTemplatedDecl();
14000 else
14001 FD = cast<FunctionDecl>(D);
14002
14003 // Do not push if it is a lambda because one is already pushed when building
14004 // the lambda in ActOnStartOfLambdaDefinition().
14005 if (!isLambdaCallOperator(FD))
14006 PushExpressionEvaluationContext(
14007 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14008 : ExprEvalContexts.back().Context);
14009
14010 // Check for defining attributes before the check for redefinition.
14011 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14012 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14013 FD->dropAttr<AliasAttr>();
14014 FD->setInvalidDecl();
14015 }
14016 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14017 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14018 FD->dropAttr<IFuncAttr>();
14019 FD->setInvalidDecl();
14020 }
14021
14022 // See if this is a redefinition. If 'will have body' is already set, then
14023 // these checks were already performed when it was set.
14024 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
14025 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14026
14027 // If we're skipping the body, we're done. Don't enter the scope.
14028 if (SkipBody && SkipBody->ShouldSkip)
14029 return D;
14030 }
14031
14032 // Mark this function as "will have a body eventually". This lets users to
14033 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14034 // this function.
14035 FD->setWillHaveBody();
14036
14037 // If we are instantiating a generic lambda call operator, push
14038 // a LambdaScopeInfo onto the function stack. But use the information
14039 // that's already been calculated (ActOnLambdaExpr) to prime the current
14040 // LambdaScopeInfo.
14041 // When the template operator is being specialized, the LambdaScopeInfo,
14042 // has to be properly restored so that tryCaptureVariable doesn't try
14043 // and capture any new variables. In addition when calculating potential
14044 // captures during transformation of nested lambdas, it is necessary to
14045 // have the LSI properly restored.
14046 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14047 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14049, __PRETTY_FUNCTION__))
14048 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14049, __PRETTY_FUNCTION__))
14049 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14049, __PRETTY_FUNCTION__))
;
14050 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14051 } else {
14052 // Enter a new function scope
14053 PushFunctionScope();
14054 }
14055
14056 // Builtin functions cannot be defined.
14057 if (unsigned BuiltinID = FD->getBuiltinID()) {
14058 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14059 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14060 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14061 FD->setInvalidDecl();
14062 }
14063 }
14064
14065 // The return type of a function definition must be complete
14066 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14067 QualType ResultType = FD->getReturnType();
14068 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14069 !FD->isInvalidDecl() &&
14070 RequireCompleteType(FD->getLocation(), ResultType,
14071 diag::err_func_def_incomplete_result))
14072 FD->setInvalidDecl();
14073
14074 if (FnBodyScope)
14075 PushDeclContext(FnBodyScope, FD);
14076
14077 // Check the validity of our function parameters
14078 CheckParmsForFunctionDef(FD->parameters(),
14079 /*CheckParameterNames=*/true);
14080
14081 // Add non-parameter declarations already in the function to the current
14082 // scope.
14083 if (FnBodyScope) {
14084 for (Decl *NPD : FD->decls()) {
14085 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14086 if (!NonParmDecl)
14087 continue;
14088 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14089, __PRETTY_FUNCTION__))
14089 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14089, __PRETTY_FUNCTION__))
;
14090
14091 // If the decl has a name, make it accessible in the current scope.
14092 if (NonParmDecl->getDeclName())
14093 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14094
14095 // Similarly, dive into enums and fish their constants out, making them
14096 // accessible in this scope.
14097 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14098 for (auto *EI : ED->enumerators())
14099 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14100 }
14101 }
14102 }
14103
14104 // Introduce our parameters into the function scope
14105 for (auto Param : FD->parameters()) {
14106 Param->setOwningFunction(FD);
14107
14108 // If this has an identifier, add it to the scope stack.
14109 if (Param->getIdentifier() && FnBodyScope) {
14110 CheckShadow(FnBodyScope, Param);
14111
14112 PushOnScopeChains(Param, FnBodyScope);
14113 }
14114 }
14115
14116 // Ensure that the function's exception specification is instantiated.
14117 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14118 ResolveExceptionSpec(D->getLocation(), FPT);
14119
14120 // dllimport cannot be applied to non-inline function definitions.
14121 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14122 !FD->isTemplateInstantiation()) {
14123 assert(!FD->hasAttr<DLLExportAttr>())((!FD->hasAttr<DLLExportAttr>()) ? static_cast<void
> (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14123, __PRETTY_FUNCTION__))
;
14124 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14125 FD->setInvalidDecl();
14126 return D;
14127 }
14128 // We want to attach documentation to original Decl (which might be
14129 // a function template).
14130 ActOnDocumentableDecl(D);
14131 if (getCurLexicalContext()->isObjCContainer() &&
14132 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14133 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14134 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14135
14136 return D;
14137}
14138
14139/// Given the set of return statements within a function body,
14140/// compute the variables that are subject to the named return value
14141/// optimization.
14142///
14143/// Each of the variables that is subject to the named return value
14144/// optimization will be marked as NRVO variables in the AST, and any
14145/// return statement that has a marked NRVO variable as its NRVO candidate can
14146/// use the named return value optimization.
14147///
14148/// This function applies a very simplistic algorithm for NRVO: if every return
14149/// statement in the scope of a variable has the same NRVO candidate, that
14150/// candidate is an NRVO variable.
14151void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14152 ReturnStmt **Returns = Scope->Returns.data();
14153
14154 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14155 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14156 if (!NRVOCandidate->isNRVOVariable())
14157 Returns[I]->setNRVOCandidate(nullptr);
14158 }
14159 }
14160}
14161
14162bool Sema::canDelayFunctionBody(const Declarator &D) {
14163 // We can't delay parsing the body of a constexpr function template (yet).
14164 if (D.getDeclSpec().hasConstexprSpecifier())
14165 return false;
14166
14167 // We can't delay parsing the body of a function template with a deduced
14168 // return type (yet).
14169 if (D.getDeclSpec().hasAutoTypeSpec()) {
14170 // If the placeholder introduces a non-deduced trailing return type,
14171 // we can still delay parsing it.
14172 if (D.getNumTypeObjects()) {
14173 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14174 if (Outer.Kind == DeclaratorChunk::Function &&
14175 Outer.Fun.hasTrailingReturnType()) {
14176 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14177 return Ty.isNull() || !Ty->isUndeducedType();
14178 }
14179 }
14180 return false;
14181 }
14182
14183 return true;
14184}
14185
14186bool Sema::canSkipFunctionBody(Decl *D) {
14187 // We cannot skip the body of a function (or function template) which is
14188 // constexpr, since we may need to evaluate its body in order to parse the
14189 // rest of the file.
14190 // We cannot skip the body of a function with an undeduced return type,
14191 // because any callers of that function need to know the type.
14192 if (const FunctionDecl *FD = D->getAsFunction()) {
14193 if (FD->isConstexpr())
14194 return false;
14195 // We can't simply call Type::isUndeducedType here, because inside template
14196 // auto can be deduced to a dependent type, which is not considered
14197 // "undeduced".
14198 if (FD->getReturnType()->getContainedDeducedType())
14199 return false;
14200 }
14201 return Consumer.shouldSkipFunctionBody(D);
14202}
14203
14204Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14205 if (!Decl)
14206 return nullptr;
14207 if (FunctionDecl *FD = Decl->getAsFunction())
14208 FD->setHasSkippedBody();
14209 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14210 MD->setHasSkippedBody();
14211 return Decl;
14212}
14213
14214Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14215 return ActOnFinishFunctionBody(D, BodyArg, false);
14216}
14217
14218/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14219/// body.
14220class ExitFunctionBodyRAII {
14221public:
14222 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14223 ~ExitFunctionBodyRAII() {
14224 if (!IsLambda)
14225 S.PopExpressionEvaluationContext();
14226 }
14227
14228private:
14229 Sema &S;
14230 bool IsLambda = false;
14231};
14232
14233static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14234 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14235
14236 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14237 if (EscapeInfo.count(BD))
14238 return EscapeInfo[BD];
14239
14240 bool R = false;
14241 const BlockDecl *CurBD = BD;
14242
14243 do {
14244 R = !CurBD->doesNotEscape();
14245 if (R)
14246 break;
14247 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14248 } while (CurBD);
14249
14250 return EscapeInfo[BD] = R;
14251 };
14252
14253 // If the location where 'self' is implicitly retained is inside a escaping
14254 // block, emit a diagnostic.
14255 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14256 S.ImplicitlyRetainedSelfLocs)
14257 if (IsOrNestedInEscapingBlock(P.second))
14258 S.Diag(P.first, diag::warn_implicitly_retains_self)
14259 << FixItHint::CreateInsertion(P.first, "self->");
14260}
14261
14262Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14263 bool IsInstantiation) {
14264 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14265
14266 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14267 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14268
14269 if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
14270 CheckCompletedCoroutineBody(FD, Body);
14271
14272 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14273 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14274 // meant to pop the context added in ActOnStartOfFunctionDef().
14275 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14276
14277 if (FD) {
14278 FD->setBody(Body);
14279 FD->setWillHaveBody(false);
14280
14281 if (getLangOpts().CPlusPlus14) {
14282 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14283 FD->getReturnType()->isUndeducedType()) {
14284 // If the function has a deduced result type but contains no 'return'
14285 // statements, the result type as written must be exactly 'auto', and
14286 // the deduced result type is 'void'.
14287 if (!FD->getReturnType()->getAs<AutoType>()) {
14288 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14289 << FD->getReturnType();
14290 FD->setInvalidDecl();
14291 } else {
14292 // Substitute 'void' for the 'auto' in the type.
14293 TypeLoc ResultType = getReturnTypeLoc(FD);
14294 Context.adjustDeducedFunctionResultType(
14295 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14296 }
14297 }
14298 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14299 // In C++11, we don't use 'auto' deduction rules for lambda call
14300 // operators because we don't support return type deduction.
14301 auto *LSI = getCurLambda();
14302 if (LSI->HasImplicitReturnType) {
14303 deduceClosureReturnType(*LSI);
14304
14305 // C++11 [expr.prim.lambda]p4:
14306 // [...] if there are no return statements in the compound-statement
14307 // [the deduced type is] the type void
14308 QualType RetType =
14309 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14310
14311 // Update the return type to the deduced type.
14312 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14313 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14314 Proto->getExtProtoInfo()));
14315 }
14316 }
14317
14318 // If the function implicitly returns zero (like 'main') or is naked,
14319 // don't complain about missing return statements.
14320 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14321 WP.disableCheckFallThrough();
14322
14323 // MSVC permits the use of pure specifier (=0) on function definition,
14324 // defined at class scope, warn about this non-standard construct.
14325 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14326 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14327
14328 if (!FD->isInvalidDecl()) {
14329 // Don't diagnose unused parameters of defaulted or deleted functions.
14330 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14331 DiagnoseUnusedParameters(FD->parameters());
14332 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14333 FD->getReturnType(), FD);
14334
14335 // If this is a structor, we need a vtable.
14336 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14337 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14338 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14339 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14340
14341 // Try to apply the named return value optimization. We have to check
14342 // if we can do this here because lambdas keep return statements around
14343 // to deduce an implicit return type.
14344 if (FD->getReturnType()->isRecordType() &&
14345 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14346 computeNRVO(Body, getCurFunction());
14347 }
14348
14349 // GNU warning -Wmissing-prototypes:
14350 // Warn if a global function is defined without a previous
14351 // prototype declaration. This warning is issued even if the
14352 // definition itself provides a prototype. The aim is to detect
14353 // global functions that fail to be declared in header files.
14354 const FunctionDecl *PossiblePrototype = nullptr;
14355 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14356 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14357
14358 if (PossiblePrototype) {
14359 // We found a declaration that is not a prototype,
14360 // but that could be a zero-parameter prototype
14361 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14362 TypeLoc TL = TI->getTypeLoc();
14363 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14364 Diag(PossiblePrototype->getLocation(),
14365 diag::note_declaration_not_a_prototype)
14366 << (FD->getNumParams() != 0)
14367 << (FD->getNumParams() == 0
14368 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14369 : FixItHint{});
14370 }
14371 } else {
14372 // Returns true if the token beginning at this Loc is `const`.
14373 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14374 const LangOptions &LangOpts) {
14375 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14376 if (LocInfo.first.isInvalid())
14377 return false;
14378
14379 bool Invalid = false;
14380 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14381 if (Invalid)
14382 return false;
14383
14384 if (LocInfo.second > Buffer.size())
14385 return false;
14386
14387 const char *LexStart = Buffer.data() + LocInfo.second;
14388 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14389
14390 return StartTok.consume_front("const") &&
14391 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14392 StartTok.startswith("/*") || StartTok.startswith("//"));
14393 };
14394
14395 auto findBeginLoc = [&]() {
14396 // If the return type has `const` qualifier, we want to insert
14397 // `static` before `const` (and not before the typename).
14398 if ((FD->getReturnType()->isAnyPointerType() &&
14399 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14400 FD->getReturnType().isConstQualified()) {
14401 // But only do this if we can determine where the `const` is.
14402
14403 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14404 getLangOpts()))
14405
14406 return FD->getBeginLoc();
14407 }
14408 return FD->getTypeSpecStartLoc();
14409 };
14410 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14411 << /* function */ 1
14412 << (FD->getStorageClass() == SC_None
14413 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14414 : FixItHint{});
14415 }
14416
14417 // GNU warning -Wstrict-prototypes
14418 // Warn if K&R function is defined without a previous declaration.
14419 // This warning is issued only if the definition itself does not provide
14420 // a prototype. Only K&R definitions do not provide a prototype.
14421 if (!FD->hasWrittenPrototype()) {
14422 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14423 TypeLoc TL = TI->getTypeLoc();
14424 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14425 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14426 }
14427 }
14428
14429 // Warn on CPUDispatch with an actual body.
14430 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14431 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14432 if (!CmpndBody->body_empty())
14433 Diag(CmpndBody->body_front()->getBeginLoc(),
14434 diag::warn_dispatch_body_ignored);
14435
14436 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14437 const CXXMethodDecl *KeyFunction;
14438 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14439 MD->isVirtual() &&
14440 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14441 MD == KeyFunction->getCanonicalDecl()) {
14442 // Update the key-function state if necessary for this ABI.
14443 if (FD->isInlined() &&
14444 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14445 Context.setNonKeyFunction(MD);
14446
14447 // If the newly-chosen key function is already defined, then we
14448 // need to mark the vtable as used retroactively.
14449 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14450 const FunctionDecl *Definition;
14451 if (KeyFunction && KeyFunction->isDefined(Definition))
14452 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14453 } else {
14454 // We just defined they key function; mark the vtable as used.
14455 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14456 }
14457 }
14458 }
14459
14460 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14461, __PRETTY_FUNCTION__))
14461 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14461, __PRETTY_FUNCTION__))
;
14462 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14463 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14463, __PRETTY_FUNCTION__))
;
14464 MD->setBody(Body);
14465 if (!MD->isInvalidDecl()) {
14466 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14467 MD->getReturnType(), MD);
14468
14469 if (Body)
14470 computeNRVO(Body, getCurFunction());
14471 }
14472 if (getCurFunction()->ObjCShouldCallSuper) {
14473 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14474 << MD->getSelector().getAsString();
14475 getCurFunction()->ObjCShouldCallSuper = false;
14476 }
14477 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
14478 const ObjCMethodDecl *InitMethod = nullptr;
14479 bool isDesignated =
14480 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14481 assert(isDesignated && InitMethod)((isDesignated && InitMethod) ? static_cast<void>
(0) : __assert_fail ("isDesignated && InitMethod", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14481, __PRETTY_FUNCTION__))
;
14482 (void)isDesignated;
14483
14484 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14485 auto IFace = MD->getClassInterface();
14486 if (!IFace)
14487 return false;
14488 auto SuperD = IFace->getSuperClass();
14489 if (!SuperD)
14490 return false;
14491 return SuperD->getIdentifier() ==
14492 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14493 };
14494 // Don't issue this warning for unavailable inits or direct subclasses
14495 // of NSObject.
14496 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14497 Diag(MD->getLocation(),
14498 diag::warn_objc_designated_init_missing_super_call);
14499 Diag(InitMethod->getLocation(),
14500 diag::note_objc_designated_init_marked_here);
14501 }
14502 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
14503 }
14504 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
14505 // Don't issue this warning for unavaialable inits.
14506 if (!MD->isUnavailable())
14507 Diag(MD->getLocation(),
14508 diag::warn_objc_secondary_init_missing_init_call);
14509 getCurFunction()->ObjCWarnForNoInitDelegation = false;
14510 }
14511
14512 diagnoseImplicitlyRetainedSelf(*this);
14513 } else {
14514 // Parsing the function declaration failed in some way. Pop the fake scope
14515 // we pushed on.
14516 PopFunctionScopeInfo(ActivePolicy, dcl);
14517 return nullptr;
14518 }
14519
14520 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
14521 DiagnoseUnguardedAvailabilityViolations(dcl);
14522
14523 assert(!getCurFunction()->ObjCShouldCallSuper &&((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14525, __PRETTY_FUNCTION__))
14524 "This should only be set for ObjC methods, which should have been "((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14525, __PRETTY_FUNCTION__))
14525 "handled in the block above.")((!getCurFunction()->ObjCShouldCallSuper && "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? static_cast<void> (0)
: __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14525, __PRETTY_FUNCTION__))
;
14526
14527 // Verify and clean out per-function state.
14528 if (Body && (!FD || !FD->isDefaulted())) {
14529 // C++ constructors that have function-try-blocks can't have return
14530 // statements in the handlers of that block. (C++ [except.handle]p14)
14531 // Verify this.
14532 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14533 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14534
14535 // Verify that gotos and switch cases don't jump into scopes illegally.
14536 if (getCurFunction()->NeedsScopeChecking() &&
14537 !PP.isCodeCompletionEnabled())
14538 DiagnoseInvalidJumps(Body);
14539
14540 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14541 if (!Destructor->getParent()->isDependentType())
14542 CheckDestructor(Destructor);
14543
14544 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14545 Destructor->getParent());
14546 }
14547
14548 // If any errors have occurred, clear out any temporaries that may have
14549 // been leftover. This ensures that these temporaries won't be picked up for
14550 // deletion in some later function.
14551 if (getDiagnostics().hasUncompilableErrorOccurred() ||
14552 getDiagnostics().getSuppressAllDiagnostics()) {
14553 DiscardCleanupsInEvaluationContext();
14554 }
14555 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
14556 !isa<FunctionTemplateDecl>(dcl)) {
14557 // Since the body is valid, issue any analysis-based warnings that are
14558 // enabled.
14559 ActivePolicy = &WP;
14560 }
14561
14562 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14563 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14564 FD->setInvalidDecl();
14565
14566 if (FD && FD->hasAttr<NakedAttr>()) {
14567 for (const Stmt *S : Body->children()) {
14568 // Allow local register variables without initializer as they don't
14569 // require prologue.
14570 bool RegisterVariables = false;
14571 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14572 for (const auto *Decl : DS->decls()) {
14573 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14574 RegisterVariables =
14575 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14576 if (!RegisterVariables)
14577 break;
14578 }
14579 }
14580 }
14581 if (RegisterVariables)
14582 continue;
14583 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14584 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14585 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14586 FD->setInvalidDecl();
14587 break;
14588 }
14589 }
14590 }
14591
14592 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14594, __PRETTY_FUNCTION__))
14593 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14594, __PRETTY_FUNCTION__))
14594 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14594, __PRETTY_FUNCTION__))
;
14595 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14595, __PRETTY_FUNCTION__))
;
14596 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14597, __PRETTY_FUNCTION__))
14597 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14597, __PRETTY_FUNCTION__))
;
14598 }
14599
14600 if (!IsInstantiation)
14601 PopDeclContext();
14602
14603 PopFunctionScopeInfo(ActivePolicy, dcl);
14604 // If any errors have occurred, clear out any temporaries that may have
14605 // been leftover. This ensures that these temporaries won't be picked up for
14606 // deletion in some later function.
14607 if (getDiagnostics().hasUncompilableErrorOccurred()) {
14608 DiscardCleanupsInEvaluationContext();
14609 }
14610
14611 if (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice) {
14612 auto ES = getEmissionStatus(FD);
14613 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14614 ES == Sema::FunctionEmissionStatus::Unknown)
14615 DeclsToCheckForDeferredDiags.push_back(FD);
14616 }
14617
14618 return dcl;
14619}
14620
14621/// When we finish delayed parsing of an attribute, we must attach it to the
14622/// relevant Decl.
14623void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14624 ParsedAttributes &Attrs) {
14625 // Always attach attributes to the underlying decl.
14626 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14627 D = TD->getTemplatedDecl();
14628 ProcessDeclAttributeList(S, D, Attrs);
14629
14630 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14631 if (Method->isStatic())
14632 checkThisInStaticMemberFunctionAttributes(Method);
14633}
14634
14635/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14636/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14637NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14638 IdentifierInfo &II, Scope *S) {
14639 // Find the scope in which the identifier is injected and the corresponding
14640 // DeclContext.
14641 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14642 // In that case, we inject the declaration into the translation unit scope
14643 // instead.
14644 Scope *BlockScope = S;
14645 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14646 BlockScope = BlockScope->getParent();
14647
14648 Scope *ContextScope = BlockScope;
14649 while (!ContextScope->getEntity())
14650 ContextScope = ContextScope->getParent();
14651 ContextRAII SavedContext(*this, ContextScope->getEntity());
14652
14653 // Before we produce a declaration for an implicitly defined
14654 // function, see whether there was a locally-scoped declaration of
14655 // this name as a function or variable. If so, use that
14656 // (non-visible) declaration, and complain about it.
14657 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14658 if (ExternCPrev) {
14659 // We still need to inject the function into the enclosing block scope so
14660 // that later (non-call) uses can see it.
14661 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14662
14663 // C89 footnote 38:
14664 // If in fact it is not defined as having type "function returning int",
14665 // the behavior is undefined.
14666 if (!isa<FunctionDecl>(ExternCPrev) ||
14667 !Context.typesAreCompatible(
14668 cast<FunctionDecl>(ExternCPrev)->getType(),
14669 Context.getFunctionNoProtoType(Context.IntTy))) {
14670 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14671 << ExternCPrev << !getLangOpts().C99;
14672 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14673 return ExternCPrev;
14674 }
14675 }
14676
14677 // Extension in C99. Legal in C90, but warn about it.
14678 unsigned diag_id;
14679 if (II.getName().startswith("__builtin_"))
14680 diag_id = diag::warn_builtin_unknown;
14681 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14682 else if (getLangOpts().OpenCL)
14683 diag_id = diag::err_opencl_implicit_function_decl;
14684 else if (getLangOpts().C99)
14685 diag_id = diag::ext_implicit_function_decl;
14686 else
14687 diag_id = diag::warn_implicit_function_decl;
14688 Diag(Loc, diag_id) << &II;
14689
14690 // If we found a prior declaration of this function, don't bother building
14691 // another one. We've already pushed that one into scope, so there's nothing
14692 // more to do.
14693 if (ExternCPrev)
14694 return ExternCPrev;
14695
14696 // Because typo correction is expensive, only do it if the implicit
14697 // function declaration is going to be treated as an error.
14698 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14699 TypoCorrection Corrected;
14700 DeclFilterCCC<FunctionDecl> CCC{};
14701 if (S && (Corrected =
14702 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14703 S, nullptr, CCC, CTK_NonError)))
14704 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14705 /*ErrorRecovery*/false);
14706 }
14707
14708 // Set a Declarator for the implicit definition: int foo();
14709 const char *Dummy;
14710 AttributeFactory attrFactory;
14711 DeclSpec DS(attrFactory);
14712 unsigned DiagID;
14713 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14714 Context.getPrintingPolicy());
14715 (void)Error; // Silence warning.
14716 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14716, __PRETTY_FUNCTION__))
;
14717 SourceLocation NoLoc;
14718 Declarator D(DS, DeclaratorContext::BlockContext);
14719 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14720 /*IsAmbiguous=*/false,
14721 /*LParenLoc=*/NoLoc,
14722 /*Params=*/nullptr,
14723 /*NumParams=*/0,
14724 /*EllipsisLoc=*/NoLoc,
14725 /*RParenLoc=*/NoLoc,
14726 /*RefQualifierIsLvalueRef=*/true,
14727 /*RefQualifierLoc=*/NoLoc,
14728 /*MutableLoc=*/NoLoc, EST_None,
14729 /*ESpecRange=*/SourceRange(),
14730 /*Exceptions=*/nullptr,
14731 /*ExceptionRanges=*/nullptr,
14732 /*NumExceptions=*/0,
14733 /*NoexceptExpr=*/nullptr,
14734 /*ExceptionSpecTokens=*/nullptr,
14735 /*DeclsInPrototype=*/None, Loc,
14736 Loc, D),
14737 std::move(DS.getAttributes()), SourceLocation());
14738 D.SetIdentifier(&II, Loc);
14739
14740 // Insert this function into the enclosing block scope.
14741 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14742 FD->setImplicit();
14743
14744 AddKnownFunctionAttributes(FD);
14745
14746 return FD;
14747}
14748
14749/// If this function is a C++ replaceable global allocation function
14750/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14751/// adds any function attributes that we know a priori based on the standard.
14752///
14753/// We need to check for duplicate attributes both here and where user-written
14754/// attributes are applied to declarations.
14755void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14756 FunctionDecl *FD) {
14757 if (FD->isInvalidDecl())
14758 return;
14759
14760 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14761 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14762 return;
14763
14764 Optional<unsigned> AlignmentParam;
14765 bool IsNothrow = false;
14766 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14767 return;
14768
14769 // C++2a [basic.stc.dynamic.allocation]p4:
14770 // An allocation function that has a non-throwing exception specification
14771 // indicates failure by returning a null pointer value. Any other allocation
14772 // function never returns a null pointer value and indicates failure only by
14773 // throwing an exception [...]
14774 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14775 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14776
14777 // C++2a [basic.stc.dynamic.allocation]p2:
14778 // An allocation function attempts to allocate the requested amount of
14779 // storage. [...] If the request succeeds, the value returned by a
14780 // replaceable allocation function is a [...] pointer value p0 different
14781 // from any previously returned value p1 [...]
14782 //
14783 // However, this particular information is being added in codegen,
14784 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
14785
14786 // C++2a [basic.stc.dynamic.allocation]p2:
14787 // An allocation function attempts to allocate the requested amount of
14788 // storage. If it is successful, it returns the address of the start of a
14789 // block of storage whose length in bytes is at least as large as the
14790 // requested size.
14791 if (!FD->hasAttr<AllocSizeAttr>()) {
14792 FD->addAttr(AllocSizeAttr::CreateImplicit(
14793 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
14794 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
14795 }
14796
14797 // C++2a [basic.stc.dynamic.allocation]p3:
14798 // For an allocation function [...], the pointer returned on a successful
14799 // call shall represent the address of storage that is aligned as follows:
14800 // (3.1) If the allocation function takes an argument of type
14801 // std​::​align_­val_­t, the storage will have the alignment
14802 // specified by the value of this argument.
14803 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
14804 FD->addAttr(AllocAlignAttr::CreateImplicit(
14805 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
14806 }
14807
14808 // FIXME:
14809 // C++2a [basic.stc.dynamic.allocation]p3:
14810 // For an allocation function [...], the pointer returned on a successful
14811 // call shall represent the address of storage that is aligned as follows:
14812 // (3.2) Otherwise, if the allocation function is named operator new[],
14813 // the storage is aligned for any object that does not have
14814 // new-extended alignment ([basic.align]) and is no larger than the
14815 // requested size.
14816 // (3.3) Otherwise, the storage is aligned for any object that does not
14817 // have new-extended alignment and is of the requested size.
14818}
14819
14820/// Adds any function attributes that we know a priori based on
14821/// the declaration of this function.
14822///
14823/// These attributes can apply both to implicitly-declared builtins
14824/// (like __builtin___printf_chk) or to library-declared functions
14825/// like NSLog or printf.
14826///
14827/// We need to check for duplicate attributes both here and where user-written
14828/// attributes are applied to declarations.
14829void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
14830 if (FD->isInvalidDecl())
14831 return;
14832
14833 // If this is a built-in function, map its builtin attributes to
14834 // actual attributes.
14835 if (unsigned BuiltinID = FD->getBuiltinID()) {
14836 // Handle printf-formatting attributes.
14837 unsigned FormatIdx;
14838 bool HasVAListArg;
14839 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
14840 if (!FD->hasAttr<FormatAttr>()) {
14841 const char *fmt = "printf";
14842 unsigned int NumParams = FD->getNumParams();
14843 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
14844 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
14845 fmt = "NSString";
14846 FD->addAttr(FormatAttr::CreateImplicit(Context,
14847 &Context.Idents.get(fmt),
14848 FormatIdx+1,
14849 HasVAListArg ? 0 : FormatIdx+2,
14850 FD->getLocation()));
14851 }
14852 }
14853 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
14854 HasVAListArg)) {
14855 if (!FD->hasAttr<FormatAttr>())
14856 FD->addAttr(FormatAttr::CreateImplicit(Context,
14857 &Context.Idents.get("scanf"),
14858 FormatIdx+1,
14859 HasVAListArg ? 0 : FormatIdx+2,
14860 FD->getLocation()));
14861 }
14862
14863 // Handle automatically recognized callbacks.
14864 SmallVector<int, 4> Encoding;
14865 if (!FD->hasAttr<CallbackAttr>() &&
14866 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
14867 FD->addAttr(CallbackAttr::CreateImplicit(
14868 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
14869
14870 // Mark const if we don't care about errno and that is the only thing
14871 // preventing the function from being const. This allows IRgen to use LLVM
14872 // intrinsics for such functions.
14873 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
14874 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
14875 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14876
14877 // We make "fma" on some platforms const because we know it does not set
14878 // errno in those environments even though it could set errno based on the
14879 // C standard.
14880 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
14881 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
14882 !FD->hasAttr<ConstAttr>()) {
14883 switch (BuiltinID) {
14884 case Builtin::BI__builtin_fma:
14885 case Builtin::BI__builtin_fmaf:
14886 case Builtin::BI__builtin_fmal:
14887 case Builtin::BIfma:
14888 case Builtin::BIfmaf:
14889 case Builtin::BIfmal:
14890 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14891 break;
14892 default:
14893 break;
14894 }
14895 }
14896
14897 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
14898 !FD->hasAttr<ReturnsTwiceAttr>())
14899 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
14900 FD->getLocation()));
14901 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
14902 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14903 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
14904 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
14905 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
14906 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
14907 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
14908 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
14909 // Add the appropriate attribute, depending on the CUDA compilation mode
14910 // and which target the builtin belongs to. For example, during host
14911 // compilation, aux builtins are __device__, while the rest are __host__.
14912 if (getLangOpts().CUDAIsDevice !=
14913 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
14914 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
14915 else
14916 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
14917 }
14918 }
14919
14920 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
14921
14922 // If C++ exceptions are enabled but we are told extern "C" functions cannot
14923 // throw, add an implicit nothrow attribute to any extern "C" function we come
14924 // across.
14925 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
14926 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
14927 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
14928 if (!FPT || FPT->getExceptionSpecType() == EST_None)
14929 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
14930 }
14931
14932 IdentifierInfo *Name = FD->getIdentifier();
14933 if (!Name)
14934 return;
14935 if ((!getLangOpts().CPlusPlus &&
14936 FD->getDeclContext()->isTranslationUnit()) ||
14937 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
14938 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
14939 LinkageSpecDecl::lang_c)) {
14940 // Okay: this could be a libc/libm/Objective-C function we know
14941 // about.
14942 } else
14943 return;
14944
14945 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
14946 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
14947 // target-specific builtins, perhaps?
14948 if (!FD->hasAttr<FormatAttr>())
14949 FD->addAttr(FormatAttr::CreateImplicit(Context,
14950 &Context.Idents.get("printf"), 2,
14951 Name->isStr("vasprintf") ? 0 : 3,
14952 FD->getLocation()));
14953 }
14954
14955 if (Name->isStr("__CFStringMakeConstantString")) {
14956 // We already have a __builtin___CFStringMakeConstantString,
14957 // but builds that use -fno-constant-cfstrings don't go through that.
14958 if (!FD->hasAttr<FormatArgAttr>())
14959 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
14960 FD->getLocation()));
14961 }
14962}
14963
14964TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
14965 TypeSourceInfo *TInfo) {
14966 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14966, __PRETTY_FUNCTION__))
;
14967 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14967, __PRETTY_FUNCTION__))
;
14968
14969 if (!TInfo) {
14970 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 14970, __PRETTY_FUNCTION__))
;
14971 TInfo = Context.getTrivialTypeSourceInfo(T);
14972 }
14973
14974 // Scope manipulation handled by caller.
14975 TypedefDecl *NewTD =
14976 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
14977 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
14978
14979 // Bail out immediately if we have an invalid declaration.
14980 if (D.isInvalidType()) {
14981 NewTD->setInvalidDecl();
14982 return NewTD;
14983 }
14984
14985 if (D.getDeclSpec().isModulePrivateSpecified()) {
14986 if (CurContext->isFunctionOrMethod())
14987 Diag(NewTD->getLocation(), diag::err_module_private_local)
14988 << 2 << NewTD
14989 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14990 << FixItHint::CreateRemoval(
14991 D.getDeclSpec().getModulePrivateSpecLoc());
14992 else
14993 NewTD->setModulePrivate();
14994 }
14995
14996 // C++ [dcl.typedef]p8:
14997 // If the typedef declaration defines an unnamed class (or
14998 // enum), the first typedef-name declared by the declaration
14999 // to be that class type (or enum type) is used to denote the
15000 // class type (or enum type) for linkage purposes only.
15001 // We need to check whether the type was declared in the declaration.
15002 switch (D.getDeclSpec().getTypeSpecType()) {
15003 case TST_enum:
15004 case TST_struct:
15005 case TST_interface:
15006 case TST_union:
15007 case TST_class: {
15008 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15009 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15010 break;
15011 }
15012
15013 default:
15014 break;
15015 }
15016
15017 return NewTD;
15018}
15019
15020/// Check that this is a valid underlying type for an enum declaration.
15021bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15022 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15023 QualType T = TI->getType();
15024
15025 if (T->isDependentType())
15026 return false;
15027
15028 // This doesn't use 'isIntegralType' despite the error message mentioning
15029 // integral type because isIntegralType would also allow enum types in C.
15030 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15031 if (BT->isInteger())
15032 return false;
15033
15034 if (T->isExtIntType())
15035 return false;
15036
15037 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15038}
15039
15040/// Check whether this is a valid redeclaration of a previous enumeration.
15041/// \return true if the redeclaration was invalid.
15042bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15043 QualType EnumUnderlyingTy, bool IsFixed,
15044 const EnumDecl *Prev) {
15045 if (IsScoped != Prev->isScoped()) {
15046 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15047 << Prev->isScoped();
15048 Diag(Prev->getLocation(), diag::note_previous_declaration);
15049 return true;
15050 }
15051
15052 if (IsFixed && Prev->isFixed()) {
15053 if (!EnumUnderlyingTy->isDependentType() &&
15054 !Prev->getIntegerType()->isDependentType() &&
15055 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15056 Prev->getIntegerType())) {
15057 // TODO: Highlight the underlying type of the redeclaration.
15058 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15059 << EnumUnderlyingTy << Prev->getIntegerType();
15060 Diag(Prev->getLocation(), diag::note_previous_declaration)
15061 << Prev->getIntegerTypeRange();
15062 return true;
15063 }
15064 } else if (IsFixed != Prev->isFixed()) {
15065 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15066 << Prev->isFixed();
15067 Diag(Prev->getLocation(), diag::note_previous_declaration);
15068 return true;
15069 }
15070
15071 return false;
15072}
15073
15074/// Get diagnostic %select index for tag kind for
15075/// redeclaration diagnostic message.
15076/// WARNING: Indexes apply to particular diagnostics only!
15077///
15078/// \returns diagnostic %select index.
15079static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15080 switch (Tag) {
15081 case TTK_Struct: return 0;
15082 case TTK_Interface: return 1;
15083 case TTK_Class: return 2;
15084 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15084)
;
15085 }
15086}
15087
15088/// Determine if tag kind is a class-key compatible with
15089/// class for redeclaration (class, struct, or __interface).
15090///
15091/// \returns true iff the tag kind is compatible.
15092static bool isClassCompatTagKind(TagTypeKind Tag)
15093{
15094 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15095}
15096
15097Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15098 TagTypeKind TTK) {
15099 if (isa<TypedefDecl>(PrevDecl))
15100 return NTK_Typedef;
15101 else if (isa<TypeAliasDecl>(PrevDecl))
15102 return NTK_TypeAlias;
15103 else if (isa<ClassTemplateDecl>(PrevDecl))
15104 return NTK_Template;
15105 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15106 return NTK_TypeAliasTemplate;
15107 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15108 return NTK_TemplateTemplateArgument;
15109 switch (TTK) {
15110 case TTK_Struct:
15111 case TTK_Interface:
15112 case TTK_Class:
15113 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15114 case TTK_Union:
15115 return NTK_NonUnion;
15116 case TTK_Enum:
15117 return NTK_NonEnum;
15118 }
15119 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15119)
;
15120}
15121
15122/// Determine whether a tag with a given kind is acceptable
15123/// as a redeclaration of the given tag declaration.
15124///
15125/// \returns true if the new tag kind is acceptable, false otherwise.
15126bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15127 TagTypeKind NewTag, bool isDefinition,
15128 SourceLocation NewTagLoc,
15129 const IdentifierInfo *Name) {
15130 // C++ [dcl.type.elab]p3:
15131 // The class-key or enum keyword present in the
15132 // elaborated-type-specifier shall agree in kind with the
15133 // declaration to which the name in the elaborated-type-specifier
15134 // refers. This rule also applies to the form of
15135 // elaborated-type-specifier that declares a class-name or
15136 // friend class since it can be construed as referring to the
15137 // definition of the class. Thus, in any
15138 // elaborated-type-specifier, the enum keyword shall be used to
15139 // refer to an enumeration (7.2), the union class-key shall be
15140 // used to refer to a union (clause 9), and either the class or
15141 // struct class-key shall be used to refer to a class (clause 9)
15142 // declared using the class or struct class-key.
15143 TagTypeKind OldTag = Previous->getTagKind();
15144 if (OldTag != NewTag &&
15145 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15146 return false;
15147
15148 // Tags are compatible, but we might still want to warn on mismatched tags.
15149 // Non-class tags can't be mismatched at this point.
15150 if (!isClassCompatTagKind(NewTag))
15151 return true;
15152
15153 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15154 // by our warning analysis. We don't want to warn about mismatches with (eg)
15155 // declarations in system headers that are designed to be specialized, but if
15156 // a user asks us to warn, we should warn if their code contains mismatched
15157 // declarations.
15158 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15159 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15160 Loc);
15161 };
15162 if (IsIgnoredLoc(NewTagLoc))
15163 return true;
15164
15165 auto IsIgnored = [&](const TagDecl *Tag) {
15166 return IsIgnoredLoc(Tag->getLocation());
15167 };
15168 while (IsIgnored(Previous)) {
15169 Previous = Previous->getPreviousDecl();
15170 if (!Previous)
15171 return true;
15172 OldTag = Previous->getTagKind();
15173 }
15174
15175 bool isTemplate = false;
15176 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15177 isTemplate = Record->getDescribedClassTemplate();
15178
15179 if (inTemplateInstantiation()) {
15180 if (OldTag != NewTag) {
15181 // In a template instantiation, do not offer fix-its for tag mismatches
15182 // since they usually mess up the template instead of fixing the problem.
15183 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15184 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15185 << getRedeclDiagFromTagKind(OldTag);
15186 // FIXME: Note previous location?
15187 }
15188 return true;
15189 }
15190
15191 if (isDefinition) {
15192 // On definitions, check all previous tags and issue a fix-it for each
15193 // one that doesn't match the current tag.
15194 if (Previous->getDefinition()) {
15195 // Don't suggest fix-its for redefinitions.
15196 return true;
15197 }
15198
15199 bool previousMismatch = false;
15200 for (const TagDecl *I : Previous->redecls()) {
15201 if (I->getTagKind() != NewTag) {
15202 // Ignore previous declarations for which the warning was disabled.
15203 if (IsIgnored(I))
15204 continue;
15205
15206 if (!previousMismatch) {
15207 previousMismatch = true;
15208 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15209 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15210 << getRedeclDiagFromTagKind(I->getTagKind());
15211 }
15212 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15213 << getRedeclDiagFromTagKind(NewTag)
15214 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15215 TypeWithKeyword::getTagTypeKindName(NewTag));
15216 }
15217 }
15218 return true;
15219 }
15220
15221 // Identify the prevailing tag kind: this is the kind of the definition (if
15222 // there is a non-ignored definition), or otherwise the kind of the prior
15223 // (non-ignored) declaration.
15224 const TagDecl *PrevDef = Previous->getDefinition();
15225 if (PrevDef && IsIgnored(PrevDef))
15226 PrevDef = nullptr;
15227 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15228 if (Redecl->getTagKind() != NewTag) {
15229 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15230 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15231 << getRedeclDiagFromTagKind(OldTag);
15232 Diag(Redecl->getLocation(), diag::note_previous_use);
15233
15234 // If there is a previous definition, suggest a fix-it.
15235 if (PrevDef) {
15236 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15237 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15238 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15239 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15240 }
15241 }
15242
15243 return true;
15244}
15245
15246/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15247/// from an outer enclosing namespace or file scope inside a friend declaration.
15248/// This should provide the commented out code in the following snippet:
15249/// namespace N {
15250/// struct X;
15251/// namespace M {
15252/// struct Y { friend struct /*N::*/ X; };
15253/// }
15254/// }
15255static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15256 SourceLocation NameLoc) {
15257 // While the decl is in a namespace, do repeated lookup of that name and see
15258 // if we get the same namespace back. If we do not, continue until
15259 // translation unit scope, at which point we have a fully qualified NNS.
15260 SmallVector<IdentifierInfo *, 4> Namespaces;
15261 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15262 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15263 // This tag should be declared in a namespace, which can only be enclosed by
15264 // other namespaces. Bail if there's an anonymous namespace in the chain.
15265 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15266 if (!Namespace || Namespace->isAnonymousNamespace())
15267 return FixItHint();
15268 IdentifierInfo *II = Namespace->getIdentifier();
15269 Namespaces.push_back(II);
15270 NamedDecl *Lookup = SemaRef.LookupSingleName(
15271 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15272 if (Lookup == Namespace)
15273 break;
15274 }
15275
15276 // Once we have all the namespaces, reverse them to go outermost first, and
15277 // build an NNS.
15278 SmallString<64> Insertion;
15279 llvm::raw_svector_ostream OS(Insertion);
15280 if (DC->isTranslationUnit())
15281 OS << "::";
15282 std::reverse(Namespaces.begin(), Namespaces.end());
15283 for (auto *II : Namespaces)
15284 OS << II->getName() << "::";
15285 return FixItHint::CreateInsertion(NameLoc, Insertion);
15286}
15287
15288/// Determine whether a tag originally declared in context \p OldDC can
15289/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15290/// found a declaration in \p OldDC as a previous decl, perhaps through a
15291/// using-declaration).
15292static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15293 DeclContext *NewDC) {
15294 OldDC = OldDC->getRedeclContext();
15295 NewDC = NewDC->getRedeclContext();
15296
15297 if (OldDC->Equals(NewDC))
15298 return true;
15299
15300 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15301 // encloses the other).
15302 if (S.getLangOpts().MSVCCompat &&
15303 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15304 return true;
15305
15306 return false;
15307}
15308
15309/// This is invoked when we see 'struct foo' or 'struct {'. In the
15310/// former case, Name will be non-null. In the later case, Name will be null.
15311/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15312/// reference/declaration/definition of a tag.
15313///
15314/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15315/// trailing-type-specifier) other than one in an alias-declaration.
15316///
15317/// \param SkipBody If non-null, will be set to indicate if the caller should
15318/// skip the definition of this tag and treat it as if it were a declaration.
15319Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15320 SourceLocation KWLoc, CXXScopeSpec &SS,
15321 IdentifierInfo *Name, SourceLocation NameLoc,
15322 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15323 SourceLocation ModulePrivateLoc,
15324 MultiTemplateParamsArg TemplateParameterLists,
15325 bool &OwnedDecl, bool &IsDependent,
15326 SourceLocation ScopedEnumKWLoc,
15327 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15328 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15329 SkipBodyInfo *SkipBody) {
15330 // If this is not a definition, it must have a name.
15331 IdentifierInfo *OrigName = Name;
15332 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15333, __PRETTY_FUNCTION__))
15333 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15333, __PRETTY_FUNCTION__))
;
15334 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15334, __PRETTY_FUNCTION__))
;
15335
15336 OwnedDecl = false;
15337 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15338 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15339
15340 // FIXME: Check member specializations more carefully.
15341 bool isMemberSpecialization = false;
15342 bool Invalid = false;
15343
15344 // We only need to do this matching if we have template parameters
15345 // or a scope specifier, which also conveniently avoids this work
15346 // for non-C++ cases.
15347 if (TemplateParameterLists.size() > 0 ||
15348 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15349 if (TemplateParameterList *TemplateParams =
15350 MatchTemplateParametersToScopeSpecifier(
15351 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15352 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15353 if (Kind == TTK_Enum) {
15354 Diag(KWLoc, diag::err_enum_template);
15355 return nullptr;
15356 }
15357
15358 if (TemplateParams->size() > 0) {
15359 // This is a declaration or definition of a class template (which may
15360 // be a member of another template).
15361
15362 if (Invalid)
15363 return nullptr;
15364
15365 OwnedDecl = false;
15366 DeclResult Result = CheckClassTemplate(
15367 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15368 AS, ModulePrivateLoc,
15369 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15370 TemplateParameterLists.data(), SkipBody);
15371 return Result.get();
15372 } else {
15373 // The "template<>" header is extraneous.
15374 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15375 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15376 isMemberSpecialization = true;
15377 }
15378 }
15379
15380 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15381 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15382 return nullptr;
15383 }
15384
15385 // Figure out the underlying type if this a enum declaration. We need to do
15386 // this early, because it's needed to detect if this is an incompatible
15387 // redeclaration.
15388 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15389 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15390
15391 if (Kind == TTK_Enum) {
15392 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15393 // No underlying type explicitly specified, or we failed to parse the
15394 // type, default to int.
15395 EnumUnderlying = Context.IntTy.getTypePtr();
15396 } else if (UnderlyingType.get()) {
15397 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15398 // integral type; any cv-qualification is ignored.
15399 TypeSourceInfo *TI = nullptr;
15400 GetTypeFromParser(UnderlyingType.get(), &TI);
15401 EnumUnderlying = TI;
15402
15403 if (CheckEnumUnderlyingType(TI))
15404 // Recover by falling back to int.
15405 EnumUnderlying = Context.IntTy.getTypePtr();
15406
15407 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15408 UPPC_FixedUnderlyingType))
15409 EnumUnderlying = Context.IntTy.getTypePtr();
15410
15411 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15412 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15413 // of 'int'. However, if this is an unfixed forward declaration, don't set
15414 // the underlying type unless the user enables -fms-compatibility. This
15415 // makes unfixed forward declared enums incomplete and is more conforming.
15416 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15417 EnumUnderlying = Context.IntTy.getTypePtr();
15418 }
15419 }
15420
15421 DeclContext *SearchDC = CurContext;
15422 DeclContext *DC = CurContext;
15423 bool isStdBadAlloc = false;
15424 bool isStdAlignValT = false;
15425
15426 RedeclarationKind Redecl = forRedeclarationInCurContext();
15427 if (TUK == TUK_Friend || TUK == TUK_Reference)
15428 Redecl = NotForRedeclaration;
15429
15430 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15431 /// implemented asks for structural equivalence checking, the returned decl
15432 /// here is passed back to the parser, allowing the tag body to be parsed.
15433 auto createTagFromNewDecl = [&]() -> TagDecl * {
15434 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15434, __PRETTY_FUNCTION__))
;
15435 // If there is an identifier, use the location of the identifier as the
15436 // location of the decl, otherwise use the location of the struct/union
15437 // keyword.
15438 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15439 TagDecl *New = nullptr;
15440
15441 if (Kind == TTK_Enum) {
15442 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15443 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15444 // If this is an undefined enum, bail.
15445 if (TUK != TUK_Definition && !Invalid)
15446 return nullptr;
15447 if (EnumUnderlying) {
15448 EnumDecl *ED = cast<EnumDecl>(New);
15449 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15450 ED->setIntegerTypeSourceInfo(TI);
15451 else
15452 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15453 ED->setPromotionType(ED->getIntegerType());
15454 }
15455 } else { // struct/union
15456 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15457 nullptr);
15458 }
15459
15460 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15461 // Add alignment attributes if necessary; these attributes are checked
15462 // when the ASTContext lays out the structure.
15463 //
15464 // It is important for implementing the correct semantics that this
15465 // happen here (in ActOnTag). The #pragma pack stack is
15466 // maintained as a result of parser callbacks which can occur at
15467 // many points during the parsing of a struct declaration (because
15468 // the #pragma tokens are effectively skipped over during the
15469 // parsing of the struct).
15470 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15471 AddAlignmentAttributesForRecord(RD);
15472 AddMsStructLayoutForRecord(RD);
15473 }
15474 }
15475 New->setLexicalDeclContext(CurContext);
15476 return New;
15477 };
15478
15479 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15480 if (Name && SS.isNotEmpty()) {
15481 // We have a nested-name tag ('struct foo::bar').
15482
15483 // Check for invalid 'foo::'.
15484 if (SS.isInvalid()) {
15485 Name = nullptr;
15486 goto CreateNewDecl;
15487 }
15488
15489 // If this is a friend or a reference to a class in a dependent
15490 // context, don't try to make a decl for it.
15491 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15492 DC = computeDeclContext(SS, false);
15493 if (!DC) {
15494 IsDependent = true;
15495 return nullptr;
15496 }
15497 } else {
15498 DC = computeDeclContext(SS, true);
15499 if (!DC) {
15500 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15501 << SS.getRange();
15502 return nullptr;
15503 }
15504 }
15505
15506 if (RequireCompleteDeclContext(SS, DC))
15507 return nullptr;
15508
15509 SearchDC = DC;
15510 // Look-up name inside 'foo::'.
15511 LookupQualifiedName(Previous, DC);
15512
15513 if (Previous.isAmbiguous())
15514 return nullptr;
15515
15516 if (Previous.empty()) {
15517 // Name lookup did not find anything. However, if the
15518 // nested-name-specifier refers to the current instantiation,
15519 // and that current instantiation has any dependent base
15520 // classes, we might find something at instantiation time: treat
15521 // this as a dependent elaborated-type-specifier.
15522 // But this only makes any sense for reference-like lookups.
15523 if (Previous.wasNotFoundInCurrentInstantiation() &&
15524 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15525 IsDependent = true;
15526 return nullptr;
15527 }
15528
15529 // A tag 'foo::bar' must already exist.
15530 Diag(NameLoc, diag::err_not_tag_in_scope)
15531 << Kind << Name << DC << SS.getRange();
15532 Name = nullptr;
15533 Invalid = true;
15534 goto CreateNewDecl;
15535 }
15536 } else if (Name) {
15537 // C++14 [class.mem]p14:
15538 // If T is the name of a class, then each of the following shall have a
15539 // name different from T:
15540 // -- every member of class T that is itself a type
15541 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15542 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15543 return nullptr;
15544
15545 // If this is a named struct, check to see if there was a previous forward
15546 // declaration or definition.
15547 // FIXME: We're looking into outer scopes here, even when we
15548 // shouldn't be. Doing so can result in ambiguities that we
15549 // shouldn't be diagnosing.
15550 LookupName(Previous, S);
15551
15552 // When declaring or defining a tag, ignore ambiguities introduced
15553 // by types using'ed into this scope.
15554 if (Previous.isAmbiguous() &&
15555 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15556 LookupResult::Filter F = Previous.makeFilter();
15557 while (F.hasNext()) {
15558 NamedDecl *ND = F.next();
15559 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15560 SearchDC->getRedeclContext()))
15561 F.erase();
15562 }
15563 F.done();
15564 }
15565
15566 // C++11 [namespace.memdef]p3:
15567 // If the name in a friend declaration is neither qualified nor
15568 // a template-id and the declaration is a function or an
15569 // elaborated-type-specifier, the lookup to determine whether
15570 // the entity has been previously declared shall not consider
15571 // any scopes outside the innermost enclosing namespace.
15572 //
15573 // MSVC doesn't implement the above rule for types, so a friend tag
15574 // declaration may be a redeclaration of a type declared in an enclosing
15575 // scope. They do implement this rule for friend functions.
15576 //
15577 // Does it matter that this should be by scope instead of by
15578 // semantic context?
15579 if (!Previous.empty() && TUK == TUK_Friend) {
15580 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15581 LookupResult::Filter F = Previous.makeFilter();
15582 bool FriendSawTagOutsideEnclosingNamespace = false;
15583 while (F.hasNext()) {
15584 NamedDecl *ND = F.next();
15585 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15586 if (DC->isFileContext() &&
15587 !EnclosingNS->Encloses(ND->getDeclContext())) {
15588 if (getLangOpts().MSVCCompat)
15589 FriendSawTagOutsideEnclosingNamespace = true;
15590 else
15591 F.erase();
15592 }
15593 }
15594 F.done();
15595
15596 // Diagnose this MSVC extension in the easy case where lookup would have
15597 // unambiguously found something outside the enclosing namespace.
15598 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15599 NamedDecl *ND = Previous.getFoundDecl();
15600 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15601 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15602 }
15603 }
15604
15605 // Note: there used to be some attempt at recovery here.
15606 if (Previous.isAmbiguous())
15607 return nullptr;
15608
15609 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15610 // FIXME: This makes sure that we ignore the contexts associated
15611 // with C structs, unions, and enums when looking for a matching
15612 // tag declaration or definition. See the similar lookup tweak
15613 // in Sema::LookupName; is there a better way to deal with this?
15614 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15615 SearchDC = SearchDC->getParent();
15616 }
15617 }
15618
15619 if (Previous.isSingleResult() &&
15620 Previous.getFoundDecl()->isTemplateParameter()) {
15621 // Maybe we will complain about the shadowed template parameter.
15622 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15623 // Just pretend that we didn't see the previous declaration.
15624 Previous.clear();
15625 }
15626
15627 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15628 DC->Equals(getStdNamespace())) {
15629 if (Name->isStr("bad_alloc")) {
15630 // This is a declaration of or a reference to "std::bad_alloc".
15631 isStdBadAlloc = true;
15632
15633 // If std::bad_alloc has been implicitly declared (but made invisible to
15634 // name lookup), fill in this implicit declaration as the previous
15635 // declaration, so that the declarations get chained appropriately.
15636 if (Previous.empty() && StdBadAlloc)
15637 Previous.addDecl(getStdBadAlloc());
15638 } else if (Name->isStr("align_val_t")) {
15639 isStdAlignValT = true;
15640 if (Previous.empty() && StdAlignValT)
15641 Previous.addDecl(getStdAlignValT());
15642 }
15643 }
15644
15645 // If we didn't find a previous declaration, and this is a reference
15646 // (or friend reference), move to the correct scope. In C++, we
15647 // also need to do a redeclaration lookup there, just in case
15648 // there's a shadow friend decl.
15649 if (Name && Previous.empty() &&
15650 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15651 if (Invalid) goto CreateNewDecl;
15652 assert(SS.isEmpty())((SS.isEmpty()) ? static_cast<void> (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15652, __PRETTY_FUNCTION__))
;
15653
15654 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15655 // C++ [basic.scope.pdecl]p5:
15656 // -- for an elaborated-type-specifier of the form
15657 //
15658 // class-key identifier
15659 //
15660 // if the elaborated-type-specifier is used in the
15661 // decl-specifier-seq or parameter-declaration-clause of a
15662 // function defined in namespace scope, the identifier is
15663 // declared as a class-name in the namespace that contains
15664 // the declaration; otherwise, except as a friend
15665 // declaration, the identifier is declared in the smallest
15666 // non-class, non-function-prototype scope that contains the
15667 // declaration.
15668 //
15669 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15670 // C structs and unions.
15671 //
15672 // It is an error in C++ to declare (rather than define) an enum
15673 // type, including via an elaborated type specifier. We'll
15674 // diagnose that later; for now, declare the enum in the same
15675 // scope as we would have picked for any other tag type.
15676 //
15677 // GNU C also supports this behavior as part of its incomplete
15678 // enum types extension, while GNU C++ does not.
15679 //
15680 // Find the context where we'll be declaring the tag.
15681 // FIXME: We would like to maintain the current DeclContext as the
15682 // lexical context,
15683 SearchDC = getTagInjectionContext(SearchDC);
15684
15685 // Find the scope where we'll be declaring the tag.
15686 S = getTagInjectionScope(S, getLangOpts());
15687 } else {
15688 assert(TUK == TUK_Friend)((TUK == TUK_Friend) ? static_cast<void> (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 15688, __PRETTY_FUNCTION__))
;
15689 // C++ [namespace.memdef]p3:
15690 // If a friend declaration in a non-local class first declares a
15691 // class or function, the friend class or function is a member of
15692 // the innermost enclosing namespace.
15693 SearchDC = SearchDC->getEnclosingNamespaceContext();
15694 }
15695
15696 // In C++, we need to do a redeclaration lookup to properly
15697 // diagnose some problems.
15698 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15699 // hidden declaration so that we don't get ambiguity errors when using a
15700 // type declared by an elaborated-type-specifier. In C that is not correct
15701 // and we should instead merge compatible types found by lookup.
15702 if (getLangOpts().CPlusPlus) {
15703 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15704 LookupQualifiedName(Previous, SearchDC);
15705 } else {
15706 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15707 LookupName(Previous, S);
15708 }
15709 }
15710
15711 // If we have a known previous declaration to use, then use it.
15712 if (Previous.empty() && SkipBody && SkipBody->Previous)
15713 Previous.addDecl(SkipBody->Previous);
15714
15715 if (!Previous.empty()) {
15716 NamedDecl *PrevDecl = Previous.getFoundDecl();
15717 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15718
15719 // It's okay to have a tag decl in the same scope as a typedef
15720 // which hides a tag decl in the same scope. Finding this
15721 // insanity with a redeclaration lookup can only actually happen
15722 // in C++.
15723 //
15724 // This is also okay for elaborated-type-specifiers, which is
15725 // technically forbidden by the current standard but which is
15726 // okay according to the likely resolution of an open issue;
15727 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15728 if (getLangOpts().CPlusPlus) {
15729 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15730 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15731 TagDecl *Tag = TT->getDecl();
15732 if (Tag->getDeclName() == Name &&
15733 Tag->getDeclContext()->getRedeclContext()
15734 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15735 PrevDecl = Tag;
15736 Previous.clear();
15737 Previous.addDecl(Tag);
15738 Previous.resolveKind();
15739 }
15740 }
15741 }
15742 }
15743
15744 // If this is a redeclaration of a using shadow declaration, it must
15745 // declare a tag in the same context. In MSVC mode, we allow a
15746 // redefinition if either context is within the other.
15747 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15748 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15749 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15750 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15751 !(OldTag && isAcceptableTagRedeclContext(
15752 *this, OldTag->getDeclContext(), SearchDC))) {
15753 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15754 Diag(Shadow->getTargetDecl()->getLocation(),
15755 diag::note_using_decl_target);
15756 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
15757 << 0;
15758 // Recover by ignoring the old declaration.
15759 Previous.clear();
15760 goto CreateNewDecl;
15761 }
15762 }
15763
15764 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15765 // If this is a use of a previous tag, or if the tag is already declared
15766 // in the same scope (so that the definition/declaration completes or
15767 // rementions the tag), reuse the decl.
15768 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15769 isDeclInScope(DirectPrevDecl, SearchDC, S,
15770 SS.isNotEmpty() || isMemberSpecialization)) {
15771 // Make sure that this wasn't declared as an enum and now used as a
15772 // struct or something similar.
15773 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15774 TUK == TUK_Definition, KWLoc,
15775 Name)) {
15776 bool SafeToContinue
15777 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15778 Kind != TTK_Enum);
15779 if (SafeToContinue)
15780 Diag(KWLoc, diag::err_use_with_wrong_tag)
15781 << Name
15782 << FixItHint::CreateReplacement(SourceRange(KWLoc),
15783 PrevTagDecl->getKindName());
15784 else
15785 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
15786 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
15787
15788 if (SafeToContinue)
15789 Kind = PrevTagDecl->getTagKind();
15790 else {
15791 // Recover by making this an anonymous redefinition.
15792 Name = nullptr;
15793 Previous.clear();
15794 Invalid = true;
15795 }
15796 }
15797
15798 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
15799 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
15800 if (TUK == TUK_Reference || TUK == TUK_Friend)
15801 return PrevTagDecl;
15802
15803 QualType EnumUnderlyingTy;
15804 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
15805 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
15806 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
15807 EnumUnderlyingTy = QualType(T, 0);
15808
15809 // All conflicts with previous declarations are recovered by
15810 // returning the previous declaration, unless this is a definition,
15811 // in which case we want the caller to bail out.
15812 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
15813 ScopedEnum, EnumUnderlyingTy,
15814 IsFixed, PrevEnum))
15815 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
15816 }
15817
15818 // C++11 [class.mem]p1:
15819 // A member shall not be declared twice in the member-specification,
15820 // except that a nested class or member class template can be declared
15821 // and then later defined.
15822 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
15823 S->isDeclScope(PrevDecl)) {
15824 Diag(NameLoc, diag::ext_member_redeclared);
15825 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
15826 }
15827
15828 if (!Invalid) {
15829 // If this is a use, just return the declaration we found, unless
15830 // we have attributes.
15831 if (TUK == TUK_Reference || TUK == TUK_Friend) {
15832 if (!Attrs.empty()) {
15833 // FIXME: Diagnose these attributes. For now, we create a new
15834 // declaration to hold them.
15835 } else if (TUK == TUK_Reference &&
15836 (PrevTagDecl->getFriendObjectKind() ==
15837 Decl::FOK_Undeclared ||
15838 PrevDecl->getOwningModule() != getCurrentModule()) &&
15839 SS.isEmpty()) {
15840 // This declaration is a reference to an existing entity, but
15841 // has different visibility from that entity: it either makes
15842 // a friend visible or it makes a type visible in a new module.
15843 // In either case, create a new declaration. We only do this if
15844 // the declaration would have meant the same thing if no prior
15845 // declaration were found, that is, if it was found in the same
15846 // scope where we would have injected a declaration.
15847 if (!getTagInjectionContext(CurContext)->getRedeclContext()
15848 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
15849 return PrevTagDecl;
15850 // This is in the injected scope, create a new declaration in
15851 // that scope.
15852 S = getTagInjectionScope(S, getLangOpts());
15853 } else {
15854 return PrevTagDecl;
15855 }
15856 }
15857
15858 // Diagnose attempts to redefine a tag.
15859 if (TUK == TUK_Definition) {
15860 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
15861 // If we're defining a specialization and the previous definition
15862 // is from an implicit instantiation, don't emit an error
15863 // here; we'll catch this in the general case below.
15864 bool IsExplicitSpecializationAfterInstantiation = false;
15865 if (isMemberSpecialization) {
15866 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
15867 IsExplicitSpecializationAfterInstantiation =
15868 RD->getTemplateSpecializationKind() !=
15869 TSK_ExplicitSpecialization;
15870 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
15871 IsExplicitSpecializationAfterInstantiation =
15872 ED->getTemplateSpecializationKind() !=
15873 TSK_ExplicitSpecialization;
15874 }
15875
15876 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
15877 // not keep more that one definition around (merge them). However,
15878 // ensure the decl passes the structural compatibility check in
15879 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
15880 NamedDecl *Hidden = nullptr;
15881 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
15882 // There is a definition of this tag, but it is not visible. We
15883 // explicitly make use of C++'s one definition rule here, and
15884 // assume that this definition is identical to the hidden one
15885 // we already have. Make the existing definition visible and
15886 // use it in place of this one.
15887 if (!getLangOpts().CPlusPlus) {
15888 // Postpone making the old definition visible until after we
15889 // complete parsing the new one and do the structural
15890 // comparison.
15891 SkipBody->CheckSameAsPrevious = true;
15892 SkipBody->New = createTagFromNewDecl();
15893 SkipBody->Previous = Def;
15894 return Def;
15895 } else {
15896 SkipBody->ShouldSkip = true;
15897 SkipBody->Previous = Def;
15898 makeMergedDefinitionVisible(Hidden);
15899 // Carry on and handle it like a normal definition. We'll
15900 // skip starting the definitiion later.
15901 }
15902 } else if (!IsExplicitSpecializationAfterInstantiation) {
15903 // A redeclaration in function prototype scope in C isn't
15904 // visible elsewhere, so merely issue a warning.
15905 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
15906 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
15907 else
15908 Diag(NameLoc, diag::err_redefinition) << Name;
15909 notePreviousDefinition(Def,
15910 NameLoc.isValid() ? NameLoc : KWLoc);
15911 // If this is a redefinition, recover by making this
15912 // struct be anonymous, which will make any later
15913 // references get the previous definition.
15914 Name = nullptr;
15915 Previous.clear();
15916 Invalid = true;
15917 }
15918 } else {
15919 // If the type is currently being defined, complain
15920 // about a nested redefinition.
15921 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
15922 if (TD->isBeingDefined()) {
15923 Diag(NameLoc, diag::err_nested_redefinition) << Name;
15924 Diag(PrevTagDecl->getLocation(),
15925 diag::note_previous_definition);
15926 Name = nullptr;
15927 Previous.clear();
15928 Invalid = true;
15929 }
15930 }
15931
15932 // Okay, this is definition of a previously declared or referenced
15933 // tag. We're going to create a new Decl for it.
15934 }
15935
15936 // Okay, we're going to make a redeclaration. If this is some kind
15937 // of reference, make sure we build the redeclaration in the same DC
15938 // as the original, and ignore the current access specifier.
15939 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15940 SearchDC = PrevTagDecl->getDeclContext();
15941 AS = AS_none;
15942 }
15943 }
15944 // If we get here we have (another) forward declaration or we
15945 // have a definition. Just create a new decl.
15946
15947 } else {
15948 // If we get here, this is a definition of a new tag type in a nested
15949 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
15950 // new decl/type. We set PrevDecl to NULL so that the entities
15951 // have distinct types.
15952 Previous.clear();
15953 }
15954 // If we get here, we're going to create a new Decl. If PrevDecl
15955 // is non-NULL, it's a definition of the tag declared by
15956 // PrevDecl. If it's NULL, we have a new definition.
15957
15958 // Otherwise, PrevDecl is not a tag, but was found with tag
15959 // lookup. This is only actually possible in C++, where a few
15960 // things like templates still live in the tag namespace.
15961 } else {
15962 // Use a better diagnostic if an elaborated-type-specifier
15963 // found the wrong kind of type on the first
15964 // (non-redeclaration) lookup.
15965 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
15966 !Previous.isForRedeclaration()) {
15967 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15968 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
15969 << Kind;
15970 Diag(PrevDecl->getLocation(), diag::note_declared_at);
15971 Invalid = true;
15972
15973 // Otherwise, only diagnose if the declaration is in scope.
15974 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
15975 SS.isNotEmpty() || isMemberSpecialization)) {
15976 // do nothing
15977
15978 // Diagnose implicit declarations introduced by elaborated types.
15979 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
15980 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
15981 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
15982 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15983 Invalid = true;
15984
15985 // Otherwise it's a declaration. Call out a particularly common
15986 // case here.
15987 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15988 unsigned Kind = 0;
15989 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
15990 Diag(NameLoc, diag::err_tag_definition_of_typedef)
15991 << Name << Kind << TND->getUnderlyingType();
15992 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
15993 Invalid = true;
15994
15995 // Otherwise, diagnose.
15996 } else {
15997 // The tag name clashes with something else in the target scope,
15998 // issue an error and recover by making this tag be anonymous.
15999 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16000 notePreviousDefinition(PrevDecl, NameLoc);
16001 Name = nullptr;
16002 Invalid = true;
16003 }
16004
16005 // The existing declaration isn't relevant to us; we're in a
16006 // new scope, so clear out the previous declaration.
16007 Previous.clear();
16008 }
16009 }
16010
16011CreateNewDecl:
16012
16013 TagDecl *PrevDecl = nullptr;
16014 if (Previous.isSingleResult())
16015 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16016
16017 // If there is an identifier, use the location of the identifier as the
16018 // location of the decl, otherwise use the location of the struct/union
16019 // keyword.
16020 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16021
16022 // Otherwise, create a new declaration. If there is a previous
16023 // declaration of the same entity, the two will be linked via
16024 // PrevDecl.
16025 TagDecl *New;
16026
16027 if (Kind == TTK_Enum) {
16028 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16029 // enum X { A, B, C } D; D should chain to X.
16030 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16031 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16032 ScopedEnumUsesClassTag, IsFixed);
16033
16034 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16035 StdAlignValT = cast<EnumDecl>(New);
16036
16037 // If this is an undefined enum, warn.
16038 if (TUK != TUK_Definition && !Invalid) {
16039 TagDecl *Def;
16040 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16041 // C++0x: 7.2p2: opaque-enum-declaration.
16042 // Conflicts are diagnosed above. Do nothing.
16043 }
16044 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16045 Diag(Loc, diag::ext_forward_ref_enum_def)
16046 << New;
16047 Diag(Def->getLocation(), diag::note_previous_definition);
16048 } else {
16049 unsigned DiagID = diag::ext_forward_ref_enum;
16050 if (getLangOpts().MSVCCompat)
16051 DiagID = diag::ext_ms_forward_ref_enum;
16052 else if (getLangOpts().CPlusPlus)
16053 DiagID = diag::err_forward_ref_enum;
16054 Diag(Loc, DiagID);
16055 }
16056 }
16057
16058 if (EnumUnderlying) {
16059 EnumDecl *ED = cast<EnumDecl>(New);
16060 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16061 ED->setIntegerTypeSourceInfo(TI);
16062 else
16063 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16064 ED->setPromotionType(ED->getIntegerType());
16065 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16065, __PRETTY_FUNCTION__))
;
16066 }
16067 } else {
16068 // struct/union/class
16069
16070 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16071 // struct X { int A; } D; D should chain to X.
16072 if (getLangOpts().CPlusPlus) {
16073 // FIXME: Look for a way to use RecordDecl for simple structs.
16074 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16075 cast_or_null<CXXRecordDecl>(PrevDecl));
16076
16077 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16078 StdBadAlloc = cast<CXXRecordDecl>(New);
16079 } else
16080 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16081 cast_or_null<RecordDecl>(PrevDecl));
16082 }
16083
16084 // C++11 [dcl.type]p3:
16085 // A type-specifier-seq shall not define a class or enumeration [...].
16086 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16087 TUK == TUK_Definition) {
16088 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16089 << Context.getTagDeclType(New);
16090 Invalid = true;
16091 }
16092
16093 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16094 DC->getDeclKind() == Decl::Enum) {
16095 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16096 << Context.getTagDeclType(New);
16097 Invalid = true;
16098 }
16099
16100 // Maybe add qualifier info.
16101 if (SS.isNotEmpty()) {
16102 if (SS.isSet()) {
16103 // If this is either a declaration or a definition, check the
16104 // nested-name-specifier against the current context.
16105 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16106 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16107 isMemberSpecialization))
16108 Invalid = true;
16109
16110 New->setQualifierInfo(SS.getWithLocInContext(Context));
16111 if (TemplateParameterLists.size() > 0) {
16112 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16113 }
16114 }
16115 else
16116 Invalid = true;
16117 }
16118
16119 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16120 // Add alignment attributes if necessary; these attributes are checked when
16121 // the ASTContext lays out the structure.
16122 //
16123 // It is important for implementing the correct semantics that this
16124 // happen here (in ActOnTag). The #pragma pack stack is
16125 // maintained as a result of parser callbacks which can occur at
16126 // many points during the parsing of a struct declaration (because
16127 // the #pragma tokens are effectively skipped over during the
16128 // parsing of the struct).
16129 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16130 AddAlignmentAttributesForRecord(RD);
16131 AddMsStructLayoutForRecord(RD);
16132 }
16133 }
16134
16135 if (ModulePrivateLoc.isValid()) {
16136 if (isMemberSpecialization)
16137 Diag(New->getLocation(), diag::err_module_private_specialization)
16138 << 2
16139 << FixItHint::CreateRemoval(ModulePrivateLoc);
16140 // __module_private__ does not apply to local classes. However, we only
16141 // diagnose this as an error when the declaration specifiers are
16142 // freestanding. Here, we just ignore the __module_private__.
16143 else if (!SearchDC->isFunctionOrMethod())
16144 New->setModulePrivate();
16145 }
16146
16147 // If this is a specialization of a member class (of a class template),
16148 // check the specialization.
16149 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16150 Invalid = true;
16151
16152 // If we're declaring or defining a tag in function prototype scope in C,
16153 // note that this type can only be used within the function and add it to
16154 // the list of decls to inject into the function definition scope.
16155 if ((Name || Kind == TTK_Enum) &&
16156 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16157 if (getLangOpts().CPlusPlus) {
16158 // C++ [dcl.fct]p6:
16159 // Types shall not be defined in return or parameter types.
16160 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16161 Diag(Loc, diag::err_type_defined_in_param_type)
16162 << Name;
16163 Invalid = true;
16164 }
16165 } else if (!PrevDecl) {
16166 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16167 }
16168 }
16169
16170 if (Invalid)
16171 New->setInvalidDecl();
16172
16173 // Set the lexical context. If the tag has a C++ scope specifier, the
16174 // lexical context will be different from the semantic context.
16175 New->setLexicalDeclContext(CurContext);
16176
16177 // Mark this as a friend decl if applicable.
16178 // In Microsoft mode, a friend declaration also acts as a forward
16179 // declaration so we always pass true to setObjectOfFriendDecl to make
16180 // the tag name visible.
16181 if (TUK == TUK_Friend)
16182 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16183
16184 // Set the access specifier.
16185 if (!Invalid && SearchDC->isRecord())
16186 SetMemberAccessSpecifier(New, PrevDecl, AS);
16187
16188 if (PrevDecl)
16189 CheckRedeclarationModuleOwnership(New, PrevDecl);
16190
16191 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16192 New->startDefinition();
16193
16194 ProcessDeclAttributeList(S, New, Attrs);
16195 AddPragmaAttributes(S, New);
16196
16197 // If this has an identifier, add it to the scope stack.
16198 if (TUK == TUK_Friend) {
16199 // We might be replacing an existing declaration in the lookup tables;
16200 // if so, borrow its access specifier.
16201 if (PrevDecl)
16202 New->setAccess(PrevDecl->getAccess());
16203
16204 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16205 DC->makeDeclVisibleInContext(New);
16206 if (Name) // can be null along some error paths
16207 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16208 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16209 } else if (Name) {
16210 S = getNonFieldDeclScope(S);
16211 PushOnScopeChains(New, S, true);
16212 } else {
16213 CurContext->addDecl(New);
16214 }
16215
16216 // If this is the C FILE type, notify the AST context.
16217 if (IdentifierInfo *II = New->getIdentifier())
16218 if (!New->isInvalidDecl() &&
16219 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16220 II->isStr("FILE"))
16221 Context.setFILEDecl(New);
16222
16223 if (PrevDecl)
16224 mergeDeclAttributes(New, PrevDecl);
16225
16226 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16227 inferGslOwnerPointerAttribute(CXXRD);
16228
16229 // If there's a #pragma GCC visibility in scope, set the visibility of this
16230 // record.
16231 AddPushedVisibilityAttribute(New);
16232
16233 if (isMemberSpecialization && !New->isInvalidDecl())
16234 CompleteMemberSpecialization(New, Previous);
16235
16236 OwnedDecl = true;
16237 // In C++, don't return an invalid declaration. We can't recover well from
16238 // the cases where we make the type anonymous.
16239 if (Invalid && getLangOpts().CPlusPlus) {
16240 if (New->isBeingDefined())
16241 if (auto RD = dyn_cast<RecordDecl>(New))
16242 RD->completeDefinition();
16243 return nullptr;
16244 } else if (SkipBody && SkipBody->ShouldSkip) {
16245 return SkipBody->Previous;
16246 } else {
16247 return New;
16248 }
16249}
16250
16251void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16252 AdjustDeclIfTemplate(TagD);
16253 TagDecl *Tag = cast<TagDecl>(TagD);
16254
16255 // Enter the tag context.
16256 PushDeclContext(S, Tag);
16257
16258 ActOnDocumentableDecl(TagD);
16259
16260 // If there's a #pragma GCC visibility in scope, set the visibility of this
16261 // record.
16262 AddPushedVisibilityAttribute(Tag);
16263}
16264
16265bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16266 SkipBodyInfo &SkipBody) {
16267 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16268 return false;
16269
16270 // Make the previous decl visible.
16271 makeMergedDefinitionVisible(SkipBody.Previous);
16272 return true;
16273}
16274
16275Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16276 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16277, __PRETTY_FUNCTION__))
16277 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16277, __PRETTY_FUNCTION__))
;
16278 DeclContext *OCD = cast<DeclContext>(IDecl);
16279 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16280, __PRETTY_FUNCTION__))
16280 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16280, __PRETTY_FUNCTION__))
;
16281 CurContext = OCD;
16282 return IDecl;
16283}
16284
16285void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16286 SourceLocation FinalLoc,
16287 bool IsFinalSpelledSealed,
16288 SourceLocation LBraceLoc) {
16289 AdjustDeclIfTemplate(TagD);
16290 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16291
16292 FieldCollector->StartClass();
16293
16294 if (!Record->getIdentifier())
16295 return;
16296
16297 if (FinalLoc.isValid())
16298 Record->addAttr(FinalAttr::Create(
16299 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16300 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16301
16302 // C++ [class]p2:
16303 // [...] The class-name is also inserted into the scope of the
16304 // class itself; this is known as the injected-class-name. For
16305 // purposes of access checking, the injected-class-name is treated
16306 // as if it were a public member name.
16307 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16308 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16309 Record->getLocation(), Record->getIdentifier(),
16310 /*PrevDecl=*/nullptr,
16311 /*DelayTypeCreation=*/true);
16312 Context.getTypeDeclType(InjectedClassName, Record);
16313 InjectedClassName->setImplicit();
16314 InjectedClassName->setAccess(AS_public);
16315 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16316 InjectedClassName->setDescribedClassTemplate(Template);
16317 PushOnScopeChains(InjectedClassName, S);
16318 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16319, __PRETTY_FUNCTION__))
16319 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16319, __PRETTY_FUNCTION__))
;
16320}
16321
16322void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16323 SourceRange BraceRange) {
16324 AdjustDeclIfTemplate(TagD);
16325 TagDecl *Tag = cast<TagDecl>(TagD);
16326 Tag->setBraceRange(BraceRange);
16327
16328 // Make sure we "complete" the definition even it is invalid.
16329 if (Tag->isBeingDefined()) {
16330 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16330, __PRETTY_FUNCTION__))
;
16331 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16332 RD->completeDefinition();
16333 }
16334
16335 if (isa<CXXRecordDecl>(Tag)) {
16336 FieldCollector->FinishClass();
16337 }
16338
16339 // Exit this scope of this tag's definition.
16340 PopDeclContext();
16341
16342 if (getCurLexicalContext()->isObjCContainer() &&
16343 Tag->getDeclContext()->isFileContext())
16344 Tag->setTopLevelDeclInObjCContainer();
16345
16346 // Notify the consumer that we've defined a tag.
16347 if (!Tag->isInvalidDecl())
16348 Consumer.HandleTagDeclDefinition(Tag);
16349}
16350
16351void Sema::ActOnObjCContainerFinishDefinition() {
16352 // Exit this scope of this interface definition.
16353 PopDeclContext();
16354}
16355
16356void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16357 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16357, __PRETTY_FUNCTION__))
;
16358 OriginalLexicalContext = DC;
16359 ActOnObjCContainerFinishDefinition();
16360}
16361
16362void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16363 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16364 OriginalLexicalContext = nullptr;
16365}
16366
16367void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16368 AdjustDeclIfTemplate(TagD);
16369 TagDecl *Tag = cast<TagDecl>(TagD);
16370 Tag->setInvalidDecl();
16371
16372 // Make sure we "complete" the definition even it is invalid.
16373 if (Tag->isBeingDefined()) {
16374 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16375 RD->completeDefinition();
16376 }
16377
16378 // We're undoing ActOnTagStartDefinition here, not
16379 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16380 // the FieldCollector.
16381
16382 PopDeclContext();
16383}
16384
16385// Note that FieldName may be null for anonymous bitfields.
16386ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16387 IdentifierInfo *FieldName,
16388 QualType FieldTy, bool IsMsStruct,
16389 Expr *BitWidth, bool *ZeroWidth) {
16390 assert(BitWidth)((BitWidth) ? static_cast<void> (0) : __assert_fail ("BitWidth"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16390, __PRETTY_FUNCTION__))
;
16391 if (BitWidth->containsErrors())
16392 return ExprError();
16393
16394 // Default to true; that shouldn't confuse checks for emptiness
16395 if (ZeroWidth)
16396 *ZeroWidth = true;
16397
16398 // C99 6.7.2.1p4 - verify the field type.
16399 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16400 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16401 // Handle incomplete and sizeless types with a specific error.
16402 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16403 diag::err_field_incomplete_or_sizeless))
16404 return ExprError();
16405 if (FieldName)
16406 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16407 << FieldName << FieldTy << BitWidth->getSourceRange();
16408 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16409 << FieldTy << BitWidth->getSourceRange();
16410 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16411 UPPC_BitFieldWidth))
16412 return ExprError();
16413
16414 // If the bit-width is type- or value-dependent, don't try to check
16415 // it now.
16416 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16417 return BitWidth;
16418
16419 llvm::APSInt Value;
16420 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
16421 if (ICE.isInvalid())
16422 return ICE;
16423 BitWidth = ICE.get();
16424
16425 if (Value != 0 && ZeroWidth)
16426 *ZeroWidth = false;
16427
16428 // Zero-width bitfield is ok for anonymous field.
16429 if (Value == 0 && FieldName)
16430 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16431
16432 if (Value.isSigned() && Value.isNegative()) {
16433 if (FieldName)
16434 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16435 << FieldName << Value.toString(10);
16436 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16437 << Value.toString(10);
16438 }
16439
16440 if (!FieldTy->isDependentType()) {
16441 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16442 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16443 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16444
16445 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16446 // ABI.
16447 bool CStdConstraintViolation =
16448 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16449 bool MSBitfieldViolation =
16450 Value.ugt(TypeStorageSize) &&
16451 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16452 if (CStdConstraintViolation || MSBitfieldViolation) {
16453 unsigned DiagWidth =
16454 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16455 if (FieldName)
16456 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16457 << FieldName << (unsigned)Value.getZExtValue()
16458 << !CStdConstraintViolation << DiagWidth;
16459
16460 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
16461 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
16462 << DiagWidth;
16463 }
16464
16465 // Warn on types where the user might conceivably expect to get all
16466 // specified bits as value bits: that's all integral types other than
16467 // 'bool'.
16468 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
16469 if (FieldName)
16470 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16471 << FieldName << (unsigned)Value.getZExtValue()
16472 << (unsigned)TypeWidth;
16473 else
16474 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
16475 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
16476 }
16477 }
16478
16479 return BitWidth;
16480}
16481
16482/// ActOnField - Each field of a C struct/union is passed into this in order
16483/// to create a FieldDecl object for it.
16484Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16485 Declarator &D, Expr *BitfieldWidth) {
16486 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16487 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16488 /*InitStyle=*/ICIS_NoInit, AS_public);
16489 return Res;
16490}
16491
16492/// HandleField - Analyze a field of a C struct or a C++ data member.
16493///
16494FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16495 SourceLocation DeclStart,
16496 Declarator &D, Expr *BitWidth,
16497 InClassInitStyle InitStyle,
16498 AccessSpecifier AS) {
16499 if (D.isDecompositionDeclarator()) {
16500 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16501 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16502 << Decomp.getSourceRange();
16503 return nullptr;
16504 }
16505
16506 IdentifierInfo *II = D.getIdentifier();
16507 SourceLocation Loc = DeclStart;
16508 if (II) Loc = D.getIdentifierLoc();
16509
16510 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16511 QualType T = TInfo->getType();
16512 if (getLangOpts().CPlusPlus) {
16513 CheckExtraCXXDefaultArguments(D);
16514
16515 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16516 UPPC_DataMemberType)) {
16517 D.setInvalidType();
16518 T = Context.IntTy;
16519 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16520 }
16521 }
16522
16523 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16524
16525 if (D.getDeclSpec().isInlineSpecified())
16526 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16527 << getLangOpts().CPlusPlus17;
16528 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16529 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16530 diag::err_invalid_thread)
16531 << DeclSpec::getSpecifierName(TSCS);
16532
16533 // Check to see if this name was declared as a member previously
16534 NamedDecl *PrevDecl = nullptr;
16535 LookupResult Previous(*this, II, Loc, LookupMemberName,
16536 ForVisibleRedeclaration);
16537 LookupName(Previous, S);
16538 switch (Previous.getResultKind()) {
16539 case LookupResult::Found:
16540 case LookupResult::FoundUnresolvedValue:
16541 PrevDecl = Previous.getAsSingle<NamedDecl>();
16542 break;
16543
16544 case LookupResult::FoundOverloaded:
16545 PrevDecl = Previous.getRepresentativeDecl();
16546 break;
16547
16548 case LookupResult::NotFound:
16549 case LookupResult::NotFoundInCurrentInstantiation:
16550 case LookupResult::Ambiguous:
16551 break;
16552 }
16553 Previous.suppressDiagnostics();
16554
16555 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16556 // Maybe we will complain about the shadowed template parameter.
16557 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16558 // Just pretend that we didn't see the previous declaration.
16559 PrevDecl = nullptr;
16560 }
16561
16562 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16563 PrevDecl = nullptr;
16564
16565 bool Mutable
16566 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16567 SourceLocation TSSL = D.getBeginLoc();
16568 FieldDecl *NewFD
16569 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16570 TSSL, AS, PrevDecl, &D);
16571
16572 if (NewFD->isInvalidDecl())
16573 Record->setInvalidDecl();
16574
16575 if (D.getDeclSpec().isModulePrivateSpecified())
16576 NewFD->setModulePrivate();
16577
16578 if (NewFD->isInvalidDecl() && PrevDecl) {
16579 // Don't introduce NewFD into scope; there's already something
16580 // with the same name in the same scope.
16581 } else if (II) {
16582 PushOnScopeChains(NewFD, S);
16583 } else
16584 Record->addDecl(NewFD);
16585
16586 return NewFD;
16587}
16588
16589/// Build a new FieldDecl and check its well-formedness.
16590///
16591/// This routine builds a new FieldDecl given the fields name, type,
16592/// record, etc. \p PrevDecl should refer to any previous declaration
16593/// with the same name and in the same scope as the field to be
16594/// created.
16595///
16596/// \returns a new FieldDecl.
16597///
16598/// \todo The Declarator argument is a hack. It will be removed once
16599FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16600 TypeSourceInfo *TInfo,
16601 RecordDecl *Record, SourceLocation Loc,
16602 bool Mutable, Expr *BitWidth,
16603 InClassInitStyle InitStyle,
16604 SourceLocation TSSL,
16605 AccessSpecifier AS, NamedDecl *PrevDecl,
16606 Declarator *D) {
16607 IdentifierInfo *II = Name.getAsIdentifierInfo();
16608 bool InvalidDecl = false;
16609 if (D) InvalidDecl = D->isInvalidType();
16610
16611 // If we receive a broken type, recover by assuming 'int' and
16612 // marking this declaration as invalid.
16613 if (T.isNull() || T->containsErrors()) {
16614 InvalidDecl = true;
16615 T = Context.IntTy;
16616 }
16617
16618 QualType EltTy = Context.getBaseElementType(T);
16619 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16620 if (RequireCompleteSizedType(Loc, EltTy,
16621 diag::err_field_incomplete_or_sizeless)) {
16622 // Fields of incomplete type force their record to be invalid.
16623 Record->setInvalidDecl();
16624 InvalidDecl = true;
16625 } else {
16626 NamedDecl *Def;
16627 EltTy->isIncompleteType(&Def);
16628 if (Def && Def->isInvalidDecl()) {
16629 Record->setInvalidDecl();
16630 InvalidDecl = true;
16631 }
16632 }
16633 }
16634
16635 // TR 18037 does not allow fields to be declared with address space
16636 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16637 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16638 Diag(Loc, diag::err_field_with_address_space);
16639 Record->setInvalidDecl();
16640 InvalidDecl = true;
16641 }
16642
16643 if (LangOpts.OpenCL) {
16644 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16645 // used as structure or union field: image, sampler, event or block types.
16646 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16647 T->isBlockPointerType()) {
16648 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16649 Record->setInvalidDecl();
16650 InvalidDecl = true;
16651 }
16652 // OpenCL v1.2 s6.9.c: bitfields are not supported.
16653 if (BitWidth) {
16654 Diag(Loc, diag::err_opencl_bitfields);
16655 InvalidDecl = true;
16656 }
16657 }
16658
16659 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16660 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16661 T.hasQualifiers()) {
16662 InvalidDecl = true;
16663 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16664 }
16665
16666 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16667 // than a variably modified type.
16668 if (!InvalidDecl && T->isVariablyModifiedType()) {
16669 bool SizeIsNegative;
16670 llvm::APSInt Oversized;
16671
16672 TypeSourceInfo *FixedTInfo =
16673 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
16674 SizeIsNegative,
16675 Oversized);
16676 if (FixedTInfo) {
16677 Diag(Loc, diag::warn_illegal_constant_array_size);
16678 TInfo = FixedTInfo;
16679 T = FixedTInfo->getType();
16680 } else {
16681 if (SizeIsNegative)
16682 Diag(Loc, diag::err_typecheck_negative_array_size);
16683 else if (Oversized.getBoolValue())
16684 Diag(Loc, diag::err_array_too_large)
16685 << Oversized.toString(10);
16686 else
16687 Diag(Loc, diag::err_typecheck_field_variable_size);
16688 InvalidDecl = true;
16689 }
16690 }
16691
16692 // Fields can not have abstract class types
16693 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16694 diag::err_abstract_type_in_decl,
16695 AbstractFieldType))
16696 InvalidDecl = true;
16697
16698 bool ZeroWidth = false;
16699 if (InvalidDecl)
16700 BitWidth = nullptr;
16701 // If this is declared as a bit-field, check the bit-field.
16702 if (BitWidth) {
16703 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16704 &ZeroWidth).get();
16705 if (!BitWidth) {
16706 InvalidDecl = true;
16707 BitWidth = nullptr;
16708 ZeroWidth = false;
16709 }
16710
16711 // Only data members can have in-class initializers.
16712 if (BitWidth && !II && InitStyle) {
16713 Diag(Loc, diag::err_anon_bitfield_init);
16714 InvalidDecl = true;
16715 BitWidth = nullptr;
16716 ZeroWidth = false;
16717 }
16718 }
16719
16720 // Check that 'mutable' is consistent with the type of the declaration.
16721 if (!InvalidDecl && Mutable) {
16722 unsigned DiagID = 0;
16723 if (T->isReferenceType())
16724 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16725 : diag::err_mutable_reference;
16726 else if (T.isConstQualified())
16727 DiagID = diag::err_mutable_const;
16728
16729 if (DiagID) {
16730 SourceLocation ErrLoc = Loc;
16731 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16732 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16733 Diag(ErrLoc, DiagID);
16734 if (DiagID != diag::ext_mutable_reference) {
16735 Mutable = false;
16736 InvalidDecl = true;
16737 }
16738 }
16739 }
16740
16741 // C++11 [class.union]p8 (DR1460):
16742 // At most one variant member of a union may have a
16743 // brace-or-equal-initializer.
16744 if (InitStyle != ICIS_NoInit)
16745 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16746
16747 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16748 BitWidth, Mutable, InitStyle);
16749 if (InvalidDecl)
16750 NewFD->setInvalidDecl();
16751
16752 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16753 Diag(Loc, diag::err_duplicate_member) << II;
16754 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16755 NewFD->setInvalidDecl();
16756 }
16757
16758 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16759 if (Record->isUnion()) {
16760 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16761 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16762 if (RDecl->getDefinition()) {
16763 // C++ [class.union]p1: An object of a class with a non-trivial
16764 // constructor, a non-trivial copy constructor, a non-trivial
16765 // destructor, or a non-trivial copy assignment operator
16766 // cannot be a member of a union, nor can an array of such
16767 // objects.
16768 if (CheckNontrivialField(NewFD))
16769 NewFD->setInvalidDecl();
16770 }
16771 }
16772
16773 // C++ [class.union]p1: If a union contains a member of reference type,
16774 // the program is ill-formed, except when compiling with MSVC extensions
16775 // enabled.
16776 if (EltTy->isReferenceType()) {
16777 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16778 diag::ext_union_member_of_reference_type :
16779 diag::err_union_member_of_reference_type)
16780 << NewFD->getDeclName() << EltTy;
16781 if (!getLangOpts().MicrosoftExt)
16782 NewFD->setInvalidDecl();
16783 }
16784 }
16785 }
16786
16787 // FIXME: We need to pass in the attributes given an AST
16788 // representation, not a parser representation.
16789 if (D) {
16790 // FIXME: The current scope is almost... but not entirely... correct here.
16791 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16792
16793 if (NewFD->hasAttrs())
16794 CheckAlignasUnderalignment(NewFD);
16795 }
16796
16797 // In auto-retain/release, infer strong retension for fields of
16798 // retainable type.
16799 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16800 NewFD->setInvalidDecl();
16801
16802 if (T.isObjCGCWeak())
16803 Diag(Loc, diag::warn_attribute_weak_on_field);
16804
16805 NewFD->setAccess(AS);
16806 return NewFD;
16807}
16808
16809bool Sema::CheckNontrivialField(FieldDecl *FD) {
16810 assert(FD)((FD) ? static_cast<void> (0) : __assert_fail ("FD", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16810, __PRETTY_FUNCTION__))
;
16811 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16811, __PRETTY_FUNCTION__))
;
16812
16813 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
16814 return false;
16815
16816 QualType EltTy = Context.getBaseElementType(FD->getType());
16817 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16818 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
16819 if (RDecl->getDefinition()) {
16820 // We check for copy constructors before constructors
16821 // because otherwise we'll never get complaints about
16822 // copy constructors.
16823
16824 CXXSpecialMember member = CXXInvalid;
16825 // We're required to check for any non-trivial constructors. Since the
16826 // implicit default constructor is suppressed if there are any
16827 // user-declared constructors, we just need to check that there is a
16828 // trivial default constructor and a trivial copy constructor. (We don't
16829 // worry about move constructors here, since this is a C++98 check.)
16830 if (RDecl->hasNonTrivialCopyConstructor())
16831 member = CXXCopyConstructor;
16832 else if (!RDecl->hasTrivialDefaultConstructor())
16833 member = CXXDefaultConstructor;
16834 else if (RDecl->hasNonTrivialCopyAssignment())
16835 member = CXXCopyAssignment;
16836 else if (RDecl->hasNonTrivialDestructor())
16837 member = CXXDestructor;
16838
16839 if (member != CXXInvalid) {
16840 if (!getLangOpts().CPlusPlus11 &&
16841 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
16842 // Objective-C++ ARC: it is an error to have a non-trivial field of
16843 // a union. However, system headers in Objective-C programs
16844 // occasionally have Objective-C lifetime objects within unions,
16845 // and rather than cause the program to fail, we make those
16846 // members unavailable.
16847 SourceLocation Loc = FD->getLocation();
16848 if (getSourceManager().isInSystemHeader(Loc)) {
16849 if (!FD->hasAttr<UnavailableAttr>())
16850 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
16851 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
16852 return false;
16853 }
16854 }
16855
16856 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
16857 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
16858 diag::err_illegal_union_or_anon_struct_member)
16859 << FD->getParent()->isUnion() << FD->getDeclName() << member;
16860 DiagnoseNontrivial(RDecl, member);
16861 return !getLangOpts().CPlusPlus11;
16862 }
16863 }
16864 }
16865
16866 return false;
16867}
16868
16869/// TranslateIvarVisibility - Translate visibility from a token ID to an
16870/// AST enum value.
16871static ObjCIvarDecl::AccessControl
16872TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
16873 switch (ivarVisibility) {
16874 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16874)
;
16875 case tok::objc_private: return ObjCIvarDecl::Private;
16876 case tok::objc_public: return ObjCIvarDecl::Public;
16877 case tok::objc_protected: return ObjCIvarDecl::Protected;
16878 case tok::objc_package: return ObjCIvarDecl::Package;
16879 }
16880}
16881
16882/// ActOnIvar - Each ivar field of an objective-c class is passed into this
16883/// in order to create an IvarDecl object for it.
16884Decl *Sema::ActOnIvar(Scope *S,
16885 SourceLocation DeclStart,
16886 Declarator &D, Expr *BitfieldWidth,
16887 tok::ObjCKeywordKind Visibility) {
16888
16889 IdentifierInfo *II = D.getIdentifier();
16890 Expr *BitWidth = (Expr*)BitfieldWidth;
16891 SourceLocation Loc = DeclStart;
16892 if (II) Loc = D.getIdentifierLoc();
16893
16894 // FIXME: Unnamed fields can be handled in various different ways, for
16895 // example, unnamed unions inject all members into the struct namespace!
16896
16897 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16898 QualType T = TInfo->getType();
16899
16900 if (BitWidth) {
16901 // 6.7.2.1p3, 6.7.2.1p4
16902 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
16903 if (!BitWidth)
16904 D.setInvalidType();
16905 } else {
16906 // Not a bitfield.
16907
16908 // validate II.
16909
16910 }
16911 if (T->isReferenceType()) {
16912 Diag(Loc, diag::err_ivar_reference_type);
16913 D.setInvalidType();
16914 }
16915 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16916 // than a variably modified type.
16917 else if (T->isVariablyModifiedType()) {
16918 Diag(Loc, diag::err_typecheck_ivar_variable_size);
16919 D.setInvalidType();
16920 }
16921
16922 // Get the visibility (access control) for this ivar.
16923 ObjCIvarDecl::AccessControl ac =
16924 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
16925 : ObjCIvarDecl::None;
16926 // Must set ivar's DeclContext to its enclosing interface.
16927 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
16928 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
16929 return nullptr;
16930 ObjCContainerDecl *EnclosingContext;
16931 if (ObjCImplementationDecl *IMPDecl =
16932 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16933 if (LangOpts.ObjCRuntime.isFragile()) {
16934 // Case of ivar declared in an implementation. Context is that of its class.
16935 EnclosingContext = IMPDecl->getClassInterface();
16936 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 16936, __PRETTY_FUNCTION__))
;
16937 }
16938 else
16939 EnclosingContext = EnclosingDecl;
16940 } else {
16941 if (ObjCCategoryDecl *CDecl =
16942 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16943 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
16944 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
16945 return nullptr;
16946 }
16947 }
16948 EnclosingContext = EnclosingDecl;
16949 }
16950
16951 // Construct the decl.
16952 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
16953 DeclStart, Loc, II, T,
16954 TInfo, ac, (Expr *)BitfieldWidth);
16955
16956 if (II) {
16957 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
16958 ForVisibleRedeclaration);
16959 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
16960 && !isa<TagDecl>(PrevDecl)) {
16961 Diag(Loc, diag::err_duplicate_member) << II;
16962 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16963 NewID->setInvalidDecl();
16964 }
16965 }
16966
16967 // Process attributes attached to the ivar.
16968 ProcessDeclAttributes(S, NewID, D);
16969
16970 if (D.isInvalidType())
16971 NewID->setInvalidDecl();
16972
16973 // In ARC, infer 'retaining' for ivars of retainable type.
16974 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
16975 NewID->setInvalidDecl();
16976
16977 if (D.getDeclSpec().isModulePrivateSpecified())
16978 NewID->setModulePrivate();
16979
16980 if (II) {
16981 // FIXME: When interfaces are DeclContexts, we'll need to add
16982 // these to the interface.
16983 S->AddDecl(NewID);
16984 IdResolver.AddDecl(NewID);
16985 }
16986
16987 if (LangOpts.ObjCRuntime.isNonFragile() &&
16988 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
16989 Diag(Loc, diag::warn_ivars_in_interface);
16990
16991 return NewID;
16992}
16993
16994/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
16995/// class and class extensions. For every class \@interface and class
16996/// extension \@interface, if the last ivar is a bitfield of any type,
16997/// then add an implicit `char :0` ivar to the end of that interface.
16998void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
16999 SmallVectorImpl<Decl *> &AllIvarDecls) {
17000 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17001 return;
17002
17003 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17004 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17005
17006 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17007 return;
17008 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17009 if (!ID) {
17010 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17011 if (!CD->IsClassExtension())
17012 return;
17013 }
17014 // No need to add this to end of @implementation.
17015 else
17016 return;
17017 }
17018 // All conditions are met. Add a new bitfield to the tail end of ivars.
17019 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17020 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17021
17022 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17023 DeclLoc, DeclLoc, nullptr,
17024 Context.CharTy,
17025 Context.getTrivialTypeSourceInfo(Context.CharTy,
17026 DeclLoc),
17027 ObjCIvarDecl::Private, BW,
17028 true);
17029 AllIvarDecls.push_back(Ivar);
17030}
17031
17032void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17033 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17034 SourceLocation RBrac,
17035 const ParsedAttributesView &Attrs) {
17036 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17036, __PRETTY_FUNCTION__))
;
17037
17038 // If this is an Objective-C @implementation or category and we have
17039 // new fields here we should reset the layout of the interface since
17040 // it will now change.
17041 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17042 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17043 switch (DC->getKind()) {
17044 default: break;
17045 case Decl::ObjCCategory:
17046 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17047 break;
17048 case Decl::ObjCImplementation:
17049 Context.
17050 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17051 break;
17052 }
17053 }
17054
17055 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17056 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17057
17058 // Start counting up the number of named members; make sure to include
17059 // members of anonymous structs and unions in the total.
17060 unsigned NumNamedMembers = 0;
17061 if (Record) {
17062 for (const auto *I : Record->decls()) {
17063 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17064 if (IFD->getDeclName())
17065 ++NumNamedMembers;
17066 }
17067 }
17068
17069 // Verify that all the fields are okay.
17070 SmallVector<FieldDecl*, 32> RecFields;
17071
17072 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17073 i != end; ++i) {
17074 FieldDecl *FD = cast<FieldDecl>(*i);
17075
17076 // Get the type for the field.
17077 const Type *FDTy = FD->getType().getTypePtr();
17078
17079 if (!FD->isAnonymousStructOrUnion()) {
17080 // Remember all fields written by the user.
17081 RecFields.push_back(FD);
17082 }
17083
17084 // If the field is already invalid for some reason, don't emit more
17085 // diagnostics about it.
17086 if (FD->isInvalidDecl()) {
17087 EnclosingDecl->setInvalidDecl();
17088 continue;
17089 }
17090
17091 // C99 6.7.2.1p2:
17092 // A structure or union shall not contain a member with
17093 // incomplete or function type (hence, a structure shall not
17094 // contain an instance of itself, but may contain a pointer to
17095 // an instance of itself), except that the last member of a
17096 // structure with more than one named member may have incomplete
17097 // array type; such a structure (and any union containing,
17098 // possibly recursively, a member that is such a structure)
17099 // shall not be a member of a structure or an element of an
17100 // array.
17101 bool IsLastField = (i + 1 == Fields.end());
17102 if (FDTy->isFunctionType()) {
17103 // Field declared as a function.
17104 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17105 << FD->getDeclName();
17106 FD->setInvalidDecl();
17107 EnclosingDecl->setInvalidDecl();
17108 continue;
17109 } else if (FDTy->isIncompleteArrayType() &&
17110 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17111 if (Record) {
17112 // Flexible array member.
17113 // Microsoft and g++ is more permissive regarding flexible array.
17114 // It will accept flexible array in union and also
17115 // as the sole element of a struct/class.
17116 unsigned DiagID = 0;
17117 if (!Record->isUnion() && !IsLastField) {
17118 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17119 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17120 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17121 FD->setInvalidDecl();
17122 EnclosingDecl->setInvalidDecl();
17123 continue;
17124 } else if (Record->isUnion())
17125 DiagID = getLangOpts().MicrosoftExt
17126 ? diag::ext_flexible_array_union_ms
17127 : getLangOpts().CPlusPlus
17128 ? diag::ext_flexible_array_union_gnu
17129 : diag::err_flexible_array_union;
17130 else if (NumNamedMembers < 1)
17131 DiagID = getLangOpts().MicrosoftExt
17132 ? diag::ext_flexible_array_empty_aggregate_ms
17133 : getLangOpts().CPlusPlus
17134 ? diag::ext_flexible_array_empty_aggregate_gnu
17135 : diag::err_flexible_array_empty_aggregate;
17136
17137 if (DiagID)
17138 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17139 << Record->getTagKind();
17140 // While the layout of types that contain virtual bases is not specified
17141 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17142 // virtual bases after the derived members. This would make a flexible
17143 // array member declared at the end of an object not adjacent to the end
17144 // of the type.
17145 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17146 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17147 << FD->getDeclName() << Record->getTagKind();
17148 if (!getLangOpts().C99)
17149 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17150 << FD->getDeclName() << Record->getTagKind();
17151
17152 // If the element type has a non-trivial destructor, we would not
17153 // implicitly destroy the elements, so disallow it for now.
17154 //
17155 // FIXME: GCC allows this. We should probably either implicitly delete
17156 // the destructor of the containing class, or just allow this.
17157 QualType BaseElem = Context.getBaseElementType(FD->getType());
17158 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17159 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17160 << FD->getDeclName() << FD->getType();
17161 FD->setInvalidDecl();
17162 EnclosingDecl->setInvalidDecl();
17163 continue;
17164 }
17165 // Okay, we have a legal flexible array member at the end of the struct.
17166 Record->setHasFlexibleArrayMember(true);
17167 } else {
17168 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17169 // unless they are followed by another ivar. That check is done
17170 // elsewhere, after synthesized ivars are known.
17171 }
17172 } else if (!FDTy->isDependentType() &&
17173 RequireCompleteSizedType(
17174 FD->getLocation(), FD->getType(),
17175 diag::err_field_incomplete_or_sizeless)) {
17176 // Incomplete type
17177 FD->setInvalidDecl();
17178 EnclosingDecl->setInvalidDecl();
17179 continue;
17180 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17181 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17182 // A type which contains a flexible array member is considered to be a
17183 // flexible array member.
17184 Record->setHasFlexibleArrayMember(true);
17185 if (!Record->isUnion()) {
17186 // If this is a struct/class and this is not the last element, reject
17187 // it. Note that GCC supports variable sized arrays in the middle of
17188 // structures.
17189 if (!IsLastField)
17190 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17191 << FD->getDeclName() << FD->getType();
17192 else {
17193 // We support flexible arrays at the end of structs in
17194 // other structs as an extension.
17195 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17196 << FD->getDeclName();
17197 }
17198 }
17199 }
17200 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17201 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17202 diag::err_abstract_type_in_decl,
17203 AbstractIvarType)) {
17204 // Ivars can not have abstract class types
17205 FD->setInvalidDecl();
17206 }
17207 if (Record && FDTTy->getDecl()->hasObjectMember())
17208 Record->setHasObjectMember(true);
17209 if (Record && FDTTy->getDecl()->hasVolatileMember())
17210 Record->setHasVolatileMember(true);
17211 } else if (FDTy->isObjCObjectType()) {
17212 /// A field cannot be an Objective-c object
17213 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17214 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17215 QualType T = Context.getObjCObjectPointerType(FD->getType());
17216 FD->setType(T);
17217 } else if (Record && Record->isUnion() &&
17218 FD->getType().hasNonTrivialObjCLifetime() &&
17219 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17220 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17221 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17222 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17223 // For backward compatibility, fields of C unions declared in system
17224 // headers that have non-trivial ObjC ownership qualifications are marked
17225 // as unavailable unless the qualifier is explicit and __strong. This can
17226 // break ABI compatibility between programs compiled with ARC and MRR, but
17227 // is a better option than rejecting programs using those unions under
17228 // ARC.
17229 FD->addAttr(UnavailableAttr::CreateImplicit(
17230 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17231 FD->getLocation()));
17232 } else if (getLangOpts().ObjC &&
17233 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17234 !Record->hasObjectMember()) {
17235 if (FD->getType()->isObjCObjectPointerType() ||
17236 FD->getType().isObjCGCStrong())
17237 Record->setHasObjectMember(true);
17238 else if (Context.getAsArrayType(FD->getType())) {
17239 QualType BaseType = Context.getBaseElementType(FD->getType());
17240 if (BaseType->isRecordType() &&
17241 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17242 Record->setHasObjectMember(true);
17243 else if (BaseType->isObjCObjectPointerType() ||
17244 BaseType.isObjCGCStrong())
17245 Record->setHasObjectMember(true);
17246 }
17247 }
17248
17249 if (Record && !getLangOpts().CPlusPlus &&
17250 !shouldIgnoreForRecordTriviality(FD)) {
17251 QualType FT = FD->getType();
17252 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17253 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17254 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17255 Record->isUnion())
17256 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17257 }
17258 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17259 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17260 Record->setNonTrivialToPrimitiveCopy(true);
17261 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17262 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17263 }
17264 if (FT.isDestructedType()) {
17265 Record->setNonTrivialToPrimitiveDestroy(true);
17266 Record->setParamDestroyedInCallee(true);
17267 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17268 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17269 }
17270
17271 if (const auto *RT = FT->getAs<RecordType>()) {
17272 if (RT->getDecl()->getArgPassingRestrictions() ==
17273 RecordDecl::APK_CanNeverPassInRegs)
17274 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17275 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17276 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17277 }
17278
17279 if (Record && FD->getType().isVolatileQualified())
17280 Record->setHasVolatileMember(true);
17281 // Keep track of the number of named members.
17282 if (FD->getIdentifier())
17283 ++NumNamedMembers;
17284 }
17285
17286 // Okay, we successfully defined 'Record'.
17287 if (Record) {
17288 bool Completed = false;
17289 if (CXXRecord) {
17290 if (!CXXRecord->isInvalidDecl()) {
17291 // Set access bits correctly on the directly-declared conversions.
17292 for (CXXRecordDecl::conversion_iterator
17293 I = CXXRecord->conversion_begin(),
17294 E = CXXRecord->conversion_end(); I != E; ++I)
17295 I.setAccess((*I)->getAccess());
17296 }
17297
17298 // Add any implicitly-declared members to this class.
17299 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17300
17301 if (!CXXRecord->isDependentType()) {
17302 if (!CXXRecord->isInvalidDecl()) {
17303 // If we have virtual base classes, we may end up finding multiple
17304 // final overriders for a given virtual function. Check for this
17305 // problem now.
17306 if (CXXRecord->getNumVBases()) {
17307 CXXFinalOverriderMap FinalOverriders;
17308 CXXRecord->getFinalOverriders(FinalOverriders);
17309
17310 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17311 MEnd = FinalOverriders.end();
17312 M != MEnd; ++M) {
17313 for (OverridingMethods::iterator SO = M->second.begin(),
17314 SOEnd = M->second.end();
17315 SO != SOEnd; ++SO) {
17316 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17317, __PRETTY_FUNCTION__))
17317 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17317, __PRETTY_FUNCTION__))
;
17318 if (SO->second.size() == 1)
17319 continue;
17320
17321 // C++ [class.virtual]p2:
17322 // In a derived class, if a virtual member function of a base
17323 // class subobject has more than one final overrider the
17324 // program is ill-formed.
17325 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17326 << (const NamedDecl *)M->first << Record;
17327 Diag(M->first->getLocation(),
17328 diag::note_overridden_virtual_function);
17329 for (OverridingMethods::overriding_iterator
17330 OM = SO->second.begin(),
17331 OMEnd = SO->second.end();
17332 OM != OMEnd; ++OM)
17333 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17334 << (const NamedDecl *)M->first << OM->Method->getParent();
17335
17336 Record->setInvalidDecl();
17337 }
17338 }
17339 CXXRecord->completeDefinition(&FinalOverriders);
17340 Completed = true;
17341 }
17342 }
17343 }
17344 }
17345
17346 if (!Completed)
17347 Record->completeDefinition();
17348
17349 // Handle attributes before checking the layout.
17350 ProcessDeclAttributeList(S, Record, Attrs);
17351
17352 // We may have deferred checking for a deleted destructor. Check now.
17353 if (CXXRecord) {
17354 auto *Dtor = CXXRecord->getDestructor();
17355 if (Dtor && Dtor->isImplicit() &&
17356 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17357 CXXRecord->setImplicitDestructorIsDeleted();
17358 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17359 }
17360 }
17361
17362 if (Record->hasAttrs()) {
17363 CheckAlignasUnderalignment(Record);
17364
17365 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17366 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17367 IA->getRange(), IA->getBestCase(),
17368 IA->getInheritanceModel());
17369 }
17370
17371 // Check if the structure/union declaration is a type that can have zero
17372 // size in C. For C this is a language extension, for C++ it may cause
17373 // compatibility problems.
17374 bool CheckForZeroSize;
17375 if (!getLangOpts().CPlusPlus) {
17376 CheckForZeroSize = true;
17377 } else {
17378 // For C++ filter out types that cannot be referenced in C code.
17379 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17380 CheckForZeroSize =
17381 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17382 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17383 CXXRecord->isCLike();
17384 }
17385 if (CheckForZeroSize) {
17386 bool ZeroSize = true;
17387 bool IsEmpty = true;
17388 unsigned NonBitFields = 0;
17389 for (RecordDecl::field_iterator I = Record->field_begin(),
17390 E = Record->field_end();
17391 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17392 IsEmpty = false;
17393 if (I->isUnnamedBitfield()) {
17394 if (!I->isZeroLengthBitField(Context))
17395 ZeroSize = false;
17396 } else {
17397 ++NonBitFields;
17398 QualType FieldType = I->getType();
17399 if (FieldType->isIncompleteType() ||
17400 !Context.getTypeSizeInChars(FieldType).isZero())
17401 ZeroSize = false;
17402 }
17403 }
17404
17405 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17406 // allowed in C++, but warn if its declaration is inside
17407 // extern "C" block.
17408 if (ZeroSize) {
17409 Diag(RecLoc, getLangOpts().CPlusPlus ?
17410 diag::warn_zero_size_struct_union_in_extern_c :
17411 diag::warn_zero_size_struct_union_compat)
17412 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17413 }
17414
17415 // Structs without named members are extension in C (C99 6.7.2.1p7),
17416 // but are accepted by GCC.
17417 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17418 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17419 diag::ext_no_named_members_in_struct_union)
17420 << Record->isUnion();
17421 }
17422 }
17423 } else {
17424 ObjCIvarDecl **ClsFields =
17425 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17426 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17427 ID->setEndOfDefinitionLoc(RBrac);
17428 // Add ivar's to class's DeclContext.
17429 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17430 ClsFields[i]->setLexicalDeclContext(ID);
17431 ID->addDecl(ClsFields[i]);
17432 }
17433 // Must enforce the rule that ivars in the base classes may not be
17434 // duplicates.
17435 if (ID->getSuperClass())
17436 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17437 } else if (ObjCImplementationDecl *IMPDecl =
17438 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17439 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? static_cast<void> (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17439, __PRETTY_FUNCTION__))
;
17440 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17441 // Ivar declared in @implementation never belongs to the implementation.
17442 // Only it is in implementation's lexical context.
17443 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17444 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17445 IMPDecl->setIvarLBraceLoc(LBrac);
17446 IMPDecl->setIvarRBraceLoc(RBrac);
17447 } else if (ObjCCategoryDecl *CDecl =
17448 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17449 // case of ivars in class extension; all other cases have been
17450 // reported as errors elsewhere.
17451 // FIXME. Class extension does not have a LocEnd field.
17452 // CDecl->setLocEnd(RBrac);
17453 // Add ivar's to class extension's DeclContext.
17454 // Diagnose redeclaration of private ivars.
17455 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17456 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17457 if (IDecl) {
17458 if (const ObjCIvarDecl *ClsIvar =
17459 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17460 Diag(ClsFields[i]->getLocation(),
17461 diag::err_duplicate_ivar_declaration);
17462 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17463 continue;
17464 }
17465 for (const auto *Ext : IDecl->known_extensions()) {
17466 if (const ObjCIvarDecl *ClsExtIvar
17467 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17468 Diag(ClsFields[i]->getLocation(),
17469 diag::err_duplicate_ivar_declaration);
17470 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17471 continue;
17472 }
17473 }
17474 }
17475 ClsFields[i]->setLexicalDeclContext(CDecl);
17476 CDecl->addDecl(ClsFields[i]);
17477 }
17478 CDecl->setIvarLBraceLoc(LBrac);
17479 CDecl->setIvarRBraceLoc(RBrac);
17480 }
17481 }
17482}
17483
17484/// Determine whether the given integral value is representable within
17485/// the given type T.
17486static bool isRepresentableIntegerValue(ASTContext &Context,
17487 llvm::APSInt &Value,
17488 QualType T) {
17489 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17490, __PRETTY_FUNCTION__))
17490 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17490, __PRETTY_FUNCTION__))
;
17491 unsigned BitWidth = Context.getIntWidth(T);
17492
17493 if (Value.isUnsigned() || Value.isNonNegative()) {
17494 if (T->isSignedIntegerOrEnumerationType())
17495 --BitWidth;
17496 return Value.getActiveBits() <= BitWidth;
17497 }
17498 return Value.getMinSignedBits() <= BitWidth;
17499}
17500
17501// Given an integral type, return the next larger integral type
17502// (or a NULL type of no such type exists).
17503static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17504 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17505 // enum checking below.
17506 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17507, __PRETTY_FUNCTION__))
17507 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17507, __PRETTY_FUNCTION__))
;
17508 const unsigned NumTypes = 4;
17509 QualType SignedIntegralTypes[NumTypes] = {
17510 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17511 };
17512 QualType UnsignedIntegralTypes[NumTypes] = {
17513 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17514 Context.UnsignedLongLongTy
17515 };
17516
17517 unsigned BitWidth = Context.getTypeSize(T);
17518 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17519 : UnsignedIntegralTypes;
17520 for (unsigned I = 0; I != NumTypes; ++I)
17521 if (Context.getTypeSize(Types[I]) > BitWidth)
17522 return Types[I];
17523
17524 return QualType();
17525}
17526
17527EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17528 EnumConstantDecl *LastEnumConst,
17529 SourceLocation IdLoc,
17530 IdentifierInfo *Id,
17531 Expr *Val) {
17532 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17533 llvm::APSInt EnumVal(IntWidth);
17534 QualType EltTy;
17535
17536 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17537 Val = nullptr;
17538
17539 if (Val)
17540 Val = DefaultLvalueConversion(Val).get();
17541
17542 if (Val) {
17543 if (Enum->isDependentType() || Val->isTypeDependent())
17544 EltTy = Context.DependentTy;
17545 else {
17546 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17547 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17548 // constant-expression in the enumerator-definition shall be a converted
17549 // constant expression of the underlying type.
17550 EltTy = Enum->getIntegerType();
17551 ExprResult Converted =
17552 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17553 CCEK_Enumerator);
17554 if (Converted.isInvalid())
17555 Val = nullptr;
17556 else
17557 Val = Converted.get();
17558 } else if (!Val->isValueDependent() &&
17559 !(Val = VerifyIntegerConstantExpression(Val,
17560 &EnumVal).get())) {
17561 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17562 } else {
17563 if (Enum->isComplete()) {
17564 EltTy = Enum->getIntegerType();
17565
17566 // In Obj-C and Microsoft mode, require the enumeration value to be
17567 // representable in the underlying type of the enumeration. In C++11,
17568 // we perform a non-narrowing conversion as part of converted constant
17569 // expression checking.
17570 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17571 if (Context.getTargetInfo()
17572 .getTriple()
17573 .isWindowsMSVCEnvironment()) {
17574 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17575 } else {
17576 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17577 }
17578 }
17579
17580 // Cast to the underlying type.
17581 Val = ImpCastExprToType(Val, EltTy,
17582 EltTy->isBooleanType() ? CK_IntegralToBoolean
17583 : CK_IntegralCast)
17584 .get();
17585 } else if (getLangOpts().CPlusPlus) {
17586 // C++11 [dcl.enum]p5:
17587 // If the underlying type is not fixed, the type of each enumerator
17588 // is the type of its initializing value:
17589 // - If an initializer is specified for an enumerator, the
17590 // initializing value has the same type as the expression.
17591 EltTy = Val->getType();
17592 } else {
17593 // C99 6.7.2.2p2:
17594 // The expression that defines the value of an enumeration constant
17595 // shall be an integer constant expression that has a value
17596 // representable as an int.
17597
17598 // Complain if the value is not representable in an int.
17599 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17600 Diag(IdLoc, diag::ext_enum_value_not_int)
17601 << EnumVal.toString(10) << Val->getSourceRange()
17602 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17603 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17604 // Force the type of the expression to 'int'.
17605 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17606 }
17607 EltTy = Val->getType();
17608 }
17609 }
17610 }
17611 }
17612
17613 if (!Val) {
17614 if (Enum->isDependentType())
17615 EltTy = Context.DependentTy;
17616 else if (!LastEnumConst) {
17617 // C++0x [dcl.enum]p5:
17618 // If the underlying type is not fixed, the type of each enumerator
17619 // is the type of its initializing value:
17620 // - If no initializer is specified for the first enumerator, the
17621 // initializing value has an unspecified integral type.
17622 //
17623 // GCC uses 'int' for its unspecified integral type, as does
17624 // C99 6.7.2.2p3.
17625 if (Enum->isFixed()) {
17626 EltTy = Enum->getIntegerType();
17627 }
17628 else {
17629 EltTy = Context.IntTy;
17630 }
17631 } else {
17632 // Assign the last value + 1.
17633 EnumVal = LastEnumConst->getInitVal();
17634 ++EnumVal;
17635 EltTy = LastEnumConst->getType();
17636
17637 // Check for overflow on increment.
17638 if (EnumVal < LastEnumConst->getInitVal()) {
17639 // C++0x [dcl.enum]p5:
17640 // If the underlying type is not fixed, the type of each enumerator
17641 // is the type of its initializing value:
17642 //
17643 // - Otherwise the type of the initializing value is the same as
17644 // the type of the initializing value of the preceding enumerator
17645 // unless the incremented value is not representable in that type,
17646 // in which case the type is an unspecified integral type
17647 // sufficient to contain the incremented value. If no such type
17648 // exists, the program is ill-formed.
17649 QualType T = getNextLargerIntegralType(Context, EltTy);
17650 if (T.isNull() || Enum->isFixed()) {
17651 // There is no integral type larger enough to represent this
17652 // value. Complain, then allow the value to wrap around.
17653 EnumVal = LastEnumConst->getInitVal();
17654 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17655 ++EnumVal;
17656 if (Enum->isFixed())
17657 // When the underlying type is fixed, this is ill-formed.
17658 Diag(IdLoc, diag::err_enumerator_wrapped)
17659 << EnumVal.toString(10)
17660 << EltTy;
17661 else
17662 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17663 << EnumVal.toString(10);
17664 } else {
17665 EltTy = T;
17666 }
17667
17668 // Retrieve the last enumerator's value, extent that type to the
17669 // type that is supposed to be large enough to represent the incremented
17670 // value, then increment.
17671 EnumVal = LastEnumConst->getInitVal();
17672 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17673 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17674 ++EnumVal;
17675
17676 // If we're not in C++, diagnose the overflow of enumerator values,
17677 // which in C99 means that the enumerator value is not representable in
17678 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17679 // permits enumerator values that are representable in some larger
17680 // integral type.
17681 if (!getLangOpts().CPlusPlus && !T.isNull())
17682 Diag(IdLoc, diag::warn_enum_value_overflow);
17683 } else if (!getLangOpts().CPlusPlus &&
17684 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17685 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17686 Diag(IdLoc, diag::ext_enum_value_not_int)
17687 << EnumVal.toString(10) << 1;
17688 }
17689 }
17690 }
17691
17692 if (!EltTy->isDependentType()) {
17693 // Make the enumerator value match the signedness and size of the
17694 // enumerator's type.
17695 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17696 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17697 }
17698
17699 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17700 Val, EnumVal);
17701}
17702
17703Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17704 SourceLocation IILoc) {
17705 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17706 !getLangOpts().CPlusPlus)
17707 return SkipBodyInfo();
17708
17709 // We have an anonymous enum definition. Look up the first enumerator to
17710 // determine if we should merge the definition with an existing one and
17711 // skip the body.
17712 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17713 forRedeclarationInCurContext());
17714 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17715 if (!PrevECD)
17716 return SkipBodyInfo();
17717
17718 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17719 NamedDecl *Hidden;
17720 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17721 SkipBodyInfo Skip;
17722 Skip.Previous = Hidden;
17723 return Skip;
17724 }
17725
17726 return SkipBodyInfo();
17727}
17728
17729Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17730 SourceLocation IdLoc, IdentifierInfo *Id,
17731 const ParsedAttributesView &Attrs,
17732 SourceLocation EqualLoc, Expr *Val) {
17733 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17734 EnumConstantDecl *LastEnumConst =
17735 cast_or_null<EnumConstantDecl>(lastEnumConst);
17736
17737 // The scope passed in may not be a decl scope. Zip up the scope tree until
17738 // we find one that is.
17739 S = getNonFieldDeclScope(S);
17740
17741 // Verify that there isn't already something declared with this name in this
17742 // scope.
17743 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17744 LookupName(R, S);
17745 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17746
17747 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17748 // Maybe we will complain about the shadowed template parameter.
17749 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17750 // Just pretend that we didn't see the previous declaration.
17751 PrevDecl = nullptr;
17752 }
17753
17754 // C++ [class.mem]p15:
17755 // If T is the name of a class, then each of the following shall have a name
17756 // different from T:
17757 // - every enumerator of every member of class T that is an unscoped
17758 // enumerated type
17759 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17760 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17761 DeclarationNameInfo(Id, IdLoc));
17762
17763 EnumConstantDecl *New =
17764 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17765 if (!New)
17766 return nullptr;
17767
17768 if (PrevDecl) {
17769 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17770 // Check for other kinds of shadowing not already handled.
17771 CheckShadow(New, PrevDecl, R);
17772 }
17773
17774 // When in C++, we may get a TagDecl with the same name; in this case the
17775 // enum constant will 'hide' the tag.
17776 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17777, __PRETTY_FUNCTION__))
17777 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17777, __PRETTY_FUNCTION__))
;
17778 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17779 if (isa<EnumConstantDecl>(PrevDecl))
17780 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17781 else
17782 Diag(IdLoc, diag::err_redefinition) << Id;
17783 notePreviousDefinition(PrevDecl, IdLoc);
17784 return nullptr;
17785 }
17786 }
17787
17788 // Process attributes.
17789 ProcessDeclAttributeList(S, New, Attrs);
17790 AddPragmaAttributes(S, New);
17791
17792 // Register this decl in the current scope stack.
17793 New->setAccess(TheEnumDecl->getAccess());
17794 PushOnScopeChains(New, S);
17795
17796 ActOnDocumentableDecl(New);
17797
17798 return New;
17799}
17800
17801// Returns true when the enum initial expression does not trigger the
17802// duplicate enum warning. A few common cases are exempted as follows:
17803// Element2 = Element1
17804// Element2 = Element1 + 1
17805// Element2 = Element1 - 1
17806// Where Element2 and Element1 are from the same enum.
17807static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
17808 Expr *InitExpr = ECD->getInitExpr();
17809 if (!InitExpr)
17810 return true;
17811 InitExpr = InitExpr->IgnoreImpCasts();
17812
17813 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
17814 if (!BO->isAdditiveOp())
17815 return true;
17816 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
17817 if (!IL)
17818 return true;
17819 if (IL->getValue() != 1)
17820 return true;
17821
17822 InitExpr = BO->getLHS();
17823 }
17824
17825 // This checks if the elements are from the same enum.
17826 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
17827 if (!DRE)
17828 return true;
17829
17830 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
17831 if (!EnumConstant)
17832 return true;
17833
17834 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
17835 Enum)
17836 return true;
17837
17838 return false;
17839}
17840
17841// Emits a warning when an element is implicitly set a value that
17842// a previous element has already been set to.
17843static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
17844 EnumDecl *Enum, QualType EnumType) {
17845 // Avoid anonymous enums
17846 if (!Enum->getIdentifier())
17847 return;
17848
17849 // Only check for small enums.
17850 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
17851 return;
17852
17853 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
17854 return;
17855
17856 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
17857 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
17858
17859 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
17860
17861 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
17862 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
17863
17864 // Use int64_t as a key to avoid needing special handling for map keys.
17865 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
17866 llvm::APSInt Val = D->getInitVal();
17867 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
17868 };
17869
17870 DuplicatesVector DupVector;
17871 ValueToVectorMap EnumMap;
17872
17873 // Populate the EnumMap with all values represented by enum constants without
17874 // an initializer.
17875 for (auto *Element : Elements) {
17876 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
17877
17878 // Null EnumConstantDecl means a previous diagnostic has been emitted for
17879 // this constant. Skip this enum since it may be ill-formed.
17880 if (!ECD) {
17881 return;
17882 }
17883
17884 // Constants with initalizers are handled in the next loop.
17885 if (ECD->getInitExpr())
17886 continue;
17887
17888 // Duplicate values are handled in the next loop.
17889 EnumMap.insert({EnumConstantToKey(ECD), ECD});
17890 }
17891
17892 if (EnumMap.size() == 0)
17893 return;
17894
17895 // Create vectors for any values that has duplicates.
17896 for (auto *Element : Elements) {
17897 // The last loop returned if any constant was null.
17898 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
17899 if (!ValidDuplicateEnum(ECD, Enum))
17900 continue;
17901
17902 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
17903 if (Iter == EnumMap.end())
17904 continue;
17905
17906 DeclOrVector& Entry = Iter->second;
17907 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
17908 // Ensure constants are different.
17909 if (D == ECD)
17910 continue;
17911
17912 // Create new vector and push values onto it.
17913 auto Vec = std::make_unique<ECDVector>();
17914 Vec->push_back(D);
17915 Vec->push_back(ECD);
17916
17917 // Update entry to point to the duplicates vector.
17918 Entry = Vec.get();
17919
17920 // Store the vector somewhere we can consult later for quick emission of
17921 // diagnostics.
17922 DupVector.emplace_back(std::move(Vec));
17923 continue;
17924 }
17925
17926 ECDVector *Vec = Entry.get<ECDVector*>();
17927 // Make sure constants are not added more than once.
17928 if (*Vec->begin() == ECD)
17929 continue;
17930
17931 Vec->push_back(ECD);
17932 }
17933
17934 // Emit diagnostics.
17935 for (const auto &Vec : DupVector) {
17936 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17936, __PRETTY_FUNCTION__))
;
17937
17938 // Emit warning for one enum constant.
17939 auto *FirstECD = Vec->front();
17940 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
17941 << FirstECD << FirstECD->getInitVal().toString(10)
17942 << FirstECD->getSourceRange();
17943
17944 // Emit one note for each of the remaining enum constants with
17945 // the same value.
17946 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
17947 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
17948 << ECD << ECD->getInitVal().toString(10)
17949 << ECD->getSourceRange();
17950 }
17951}
17952
17953bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
17954 bool AllowMask) const {
17955 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17955, __PRETTY_FUNCTION__))
;
17956 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 17956, __PRETTY_FUNCTION__))
;
17957
17958 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
17959 llvm::APInt &FlagBits = R.first->second;
17960
17961 if (R.second) {
17962 for (auto *E : ED->enumerators()) {
17963 const auto &EVal = E->getInitVal();
17964 // Only single-bit enumerators introduce new flag values.
17965 if (EVal.isPowerOf2())
17966 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
17967 }
17968 }
17969
17970 // A value is in a flag enum if either its bits are a subset of the enum's
17971 // flag bits (the first condition) or we are allowing masks and the same is
17972 // true of its complement (the second condition). When masks are allowed, we
17973 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
17974 //
17975 // While it's true that any value could be used as a mask, the assumption is
17976 // that a mask will have all of the insignificant bits set. Anything else is
17977 // likely a logic error.
17978 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
17979 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
17980}
17981
17982void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
17983 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
17984 const ParsedAttributesView &Attrs) {
17985 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
17986 QualType EnumType = Context.getTypeDeclType(Enum);
17987
17988 ProcessDeclAttributeList(S, Enum, Attrs);
17989
17990 if (Enum->isDependentType()) {
17991 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
17992 EnumConstantDecl *ECD =
17993 cast_or_null<EnumConstantDecl>(Elements[i]);
17994 if (!ECD) continue;
17995
17996 ECD->setType(EnumType);
17997 }
17998
17999 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18000 return;
18001 }
18002
18003 // TODO: If the result value doesn't fit in an int, it must be a long or long
18004 // long value. ISO C does not support this, but GCC does as an extension,
18005 // emit a warning.
18006 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18007 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18008 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18009
18010 // Verify that all the values are okay, compute the size of the values, and
18011 // reverse the list.
18012 unsigned NumNegativeBits = 0;
18013 unsigned NumPositiveBits = 0;
18014
18015 // Keep track of whether all elements have type int.
18016 bool AllElementsInt = true;
18017
18018 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18019 EnumConstantDecl *ECD =
18020 cast_or_null<EnumConstantDecl>(Elements[i]);
18021 if (!ECD) continue; // Already issued a diagnostic.
18022
18023 const llvm::APSInt &InitVal = ECD->getInitVal();
18024
18025 // Keep track of the size of positive and negative values.
18026 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18027 NumPositiveBits = std::max(NumPositiveBits,
18028 (unsigned)InitVal.getActiveBits());
18029 else
18030 NumNegativeBits = std::max(NumNegativeBits,
18031 (unsigned)InitVal.getMinSignedBits());
18032
18033 // Keep track of whether every enum element has type int (very common).
18034 if (AllElementsInt)
18035 AllElementsInt = ECD->getType() == Context.IntTy;
18036 }
18037
18038 // Figure out the type that should be used for this enum.
18039 QualType BestType;
18040 unsigned BestWidth;
18041
18042 // C++0x N3000 [conv.prom]p3:
18043 // An rvalue of an unscoped enumeration type whose underlying
18044 // type is not fixed can be converted to an rvalue of the first
18045 // of the following types that can represent all the values of
18046 // the enumeration: int, unsigned int, long int, unsigned long
18047 // int, long long int, or unsigned long long int.
18048 // C99 6.4.4.3p2:
18049 // An identifier declared as an enumeration constant has type int.
18050 // The C99 rule is modified by a gcc extension
18051 QualType BestPromotionType;
18052
18053 bool Packed = Enum->hasAttr<PackedAttr>();
18054 // -fshort-enums is the equivalent to specifying the packed attribute on all
18055 // enum definitions.
18056 if (LangOpts.ShortEnums)
18057 Packed = true;
18058
18059 // If the enum already has a type because it is fixed or dictated by the
18060 // target, promote that type instead of analyzing the enumerators.
18061 if (Enum->isComplete()) {
18062 BestType = Enum->getIntegerType();
18063 if (BestType->isPromotableIntegerType())
18064 BestPromotionType = Context.getPromotedIntegerType(BestType);
18065 else
18066 BestPromotionType = BestType;
18067
18068 BestWidth = Context.getIntWidth(BestType);
18069 }
18070 else if (NumNegativeBits) {
18071 // If there is a negative value, figure out the smallest integer type (of
18072 // int/long/longlong) that fits.
18073 // If it's packed, check also if it fits a char or a short.
18074 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18075 BestType = Context.SignedCharTy;
18076 BestWidth = CharWidth;
18077 } else if (Packed && NumNegativeBits <= ShortWidth &&
18078 NumPositiveBits < ShortWidth) {
18079 BestType = Context.ShortTy;
18080 BestWidth = ShortWidth;
18081 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18082 BestType = Context.IntTy;
18083 BestWidth = IntWidth;
18084 } else {
18085 BestWidth = Context.getTargetInfo().getLongWidth();
18086
18087 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18088 BestType = Context.LongTy;
18089 } else {
18090 BestWidth = Context.getTargetInfo().getLongLongWidth();
18091
18092 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18093 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18094 BestType = Context.LongLongTy;
18095 }
18096 }
18097 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18098 } else {
18099 // If there is no negative value, figure out the smallest type that fits
18100 // all of the enumerator values.
18101 // If it's packed, check also if it fits a char or a short.
18102 if (Packed && NumPositiveBits <= CharWidth) {
18103 BestType = Context.UnsignedCharTy;
18104 BestPromotionType = Context.IntTy;
18105 BestWidth = CharWidth;
18106 } else if (Packed && NumPositiveBits <= ShortWidth) {
18107 BestType = Context.UnsignedShortTy;
18108 BestPromotionType = Context.IntTy;
18109 BestWidth = ShortWidth;
18110 } else if (NumPositiveBits <= IntWidth) {
18111 BestType = Context.UnsignedIntTy;
18112 BestWidth = IntWidth;
18113 BestPromotionType
18114 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18115 ? Context.UnsignedIntTy : Context.IntTy;
18116 } else if (NumPositiveBits <=
18117 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18118 BestType = Context.UnsignedLongTy;
18119 BestPromotionType
18120 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18121 ? Context.UnsignedLongTy : Context.LongTy;
18122 } else {
18123 BestWidth = Context.getTargetInfo().getLongLongWidth();
18124 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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 18125, __PRETTY_FUNCTION__))
18125 "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~++20200927111121+5811d723998/clang/lib/Sema/SemaDecl.cpp"
, 18125, __PRETTY_FUNCTION__))
;
18126 BestType = Context.UnsignedLongLongTy;
18127 BestPromotionType
18128 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18129 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18130 }
18131 }
18132
18133 // Loop over all of the enumerator constants, changing their types to match
18134 // the type of the enum if needed.
18135 for (auto *D : Elements) {
18136 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18137 if (!ECD) continue; // Already issued a diagnostic.
18138
18139 // Standard C says the enumerators have int type, but we allow, as an
18140 // extension, the enumerators to be larger than int size. If each
18141 // enumerator value fits in an int, type it as an int, otherwise type it the
18142 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18143 // that X has type 'int', not 'unsigned'.
18144
18145 // Determine whether the value fits into an int.
18146 llvm::APSInt InitVal = ECD->getInitVal();
18147
18148 // If it fits into an integer type, force it. Otherwise force it to match
18149 // the enum decl type.
18150 QualType NewTy;
18151 unsigned NewWidth;
18152 bool NewSign;
18153 if (!getLangOpts().CPlusPlus &&
18154 !Enum->isFixed() &&
18155 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18156 NewTy = Context.IntTy;
18157 NewWidth = IntWidth;
18158 NewSign = true;
18159 } else if (ECD->getType() == BestType) {
18160 // Already the right type!
18161 if (getLangOpts().CPlusPlus)
18162 // C++ [dcl.enum]p4: Following the closing brace of an
18163 // enum-specifier, each enumerator has the type of its
18164 // enumeration.
18165 ECD->setType(EnumType);
18166 continue;
18167 } else {
18168 NewTy = BestType;
18169 NewWidth = BestWidth;
18170 NewSign = BestType->isSignedIntegerOrEnumerationType();
18171 }
18172
18173 // Adjust the APSInt value.
18174 InitVal = InitVal.extOrTrunc(NewWidth);
18175 InitVal.setIsSigned(NewSign);
18176 ECD->setInitVal(InitVal);
18177
18178 // Adjust the Expr initializer and type.
18179 if (ECD->getInitExpr() &&
18180 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18181 ECD->setInitExpr(ImplicitCastExpr::Create(
18182 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18183 /*base paths*/ nullptr, VK_RValue, FPOptionsOverride()));
18184 if (getLangOpts().CPlusPlus)
18185 // C++ [dcl.enum]p4: Following the closing brace of an
18186 // enum-specifier, each enumerator has the type of its
18187 // enumeration.
18188 ECD->setType(EnumType);
18189 else
18190 ECD->setType(NewTy);
18191 }
18192
18193 Enum->completeDefinition(BestType, BestPromotionType,
18194 NumPositiveBits, NumNegativeBits);
18195
18196 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18197
18198 if (Enum->isClosedFlag()) {
18199 for (Decl *D : Elements) {
18200 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18201 if (!ECD) continue; // Already issued a diagnostic.
18202
18203 llvm::APSInt InitVal = ECD->getInitVal();
18204 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18205 !IsValueInFlagEnum(Enum, InitVal, true))
18206 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18207 << ECD << Enum;
18208 }
18209 }
18210
18211 // Now that the enum type is defined, ensure it's not been underaligned.
18212 if (Enum->hasAttrs())
18213 CheckAlignasUnderalignment(Enum);
18214}
18215
18216Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18217 SourceLocation StartLoc,
18218 SourceLocation EndLoc) {
18219 StringLiteral *AsmString = cast<StringLiteral>(expr);
18220
18221 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18222 AsmString, StartLoc,
18223 EndLoc);
18224 CurContext->addDecl(New);
18225 return New;
18226}
18227
18228void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18229 IdentifierInfo* AliasName,
18230 SourceLocation PragmaLoc,
18231 SourceLocation NameLoc,
18232 SourceLocation AliasNameLoc) {
18233 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18234 LookupOrdinaryName);
18235 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18236 AttributeCommonInfo::AS_Pragma);
18237 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18238 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18239
18240 // If a declaration that:
18241 // 1) declares a function or a variable
18242 // 2) has external linkage
18243 // already exists, add a label attribute to it.
18244 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18245 if (isDeclExternC(PrevDecl))
18246 PrevDecl->addAttr(Attr);
18247 else
18248 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18249 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18250 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18251 } else
18252 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18253}
18254
18255void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18256 SourceLocation PragmaLoc,
18257 SourceLocation NameLoc) {
18258 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18259
18260 if (PrevDecl) {
18261 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18262 } else {
18263 (void)WeakUndeclaredIdentifiers.insert(
18264 std::pair<IdentifierInfo*,WeakInfo>
18265 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18266 }
18267}
18268
18269void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18270 IdentifierInfo* AliasName,
18271 SourceLocation PragmaLoc,
18272 SourceLocation NameLoc,
18273 SourceLocation AliasNameLoc) {
18274 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18275 LookupOrdinaryName);
18276 WeakInfo W = WeakInfo(Name, NameLoc);
18277
18278 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18279 if (!PrevDecl->hasAttr<AliasAttr>())
18280 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18281 DeclApplyPragmaWeak(TUScope, ND, W);
18282 } else {
18283 (void)WeakUndeclaredIdentifiers.insert(
18284 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18285 }
18286}
18287
18288Decl *Sema::getObjCDeclContext() const {
18289 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18290}
18291
18292Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18293 bool Final) {
18294 // SYCL functions can be template, so we check if they have appropriate
18295 // attribute prior to checking if it is a template.
18296 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18297 return FunctionEmissionStatus::Emitted;
18298
18299 // Templates are emitted when they're instantiated.
18300 if (FD->isDependentContext())
18301 return FunctionEmissionStatus::TemplateDiscarded;
18302
18303 FunctionEmissionStatus OMPES = FunctionEmissionStatus::Unknown;
18304 if (LangOpts.OpenMPIsDevice) {
18305 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18306 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18307 if (DevTy.hasValue()) {
18308 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18309 OMPES = FunctionEmissionStatus::OMPDiscarded;
18310 else if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost ||
18311 *DevTy == OMPDeclareTargetDeclAttr::DT_Any) {
18312 OMPES = FunctionEmissionStatus::Emitted;
18313 }
18314 }
18315 } else if (LangOpts.OpenMP) {
18316 // In OpenMP 4.5 all the functions are host functions.
18317 if (LangOpts.OpenMP <= 45) {
18318 OMPES = FunctionEmissionStatus::Emitted;
18319 } else {
18320 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18321 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18322 // In OpenMP 5.0 or above, DevTy may be changed later by
18323 // #pragma omp declare target to(*) device_type(*). Therefore DevTy
18324 // having no value does not imply host. The emission status will be
18325 // checked again at the end of compilation unit.
18326 if (DevTy.hasValue()) {
18327 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
18328 OMPES = FunctionEmissionStatus::OMPDiscarded;
18329 } else if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host ||
18330 *DevTy == OMPDeclareTargetDeclAttr::DT_Any)
18331 OMPES = FunctionEmissionStatus::Emitted;
18332 } else if (Final)
18333 OMPES = FunctionEmissionStatus::Emitted;
18334 }
18335 }
18336 if (OMPES == FunctionEmissionStatus::OMPDiscarded ||
18337 (OMPES == FunctionEmissionStatus::Emitted && !LangOpts.CUDA))
18338 return OMPES;
18339
18340 if (LangOpts.CUDA) {
18341 // When compiling for device, host functions are never emitted. Similarly,
18342 // when compiling for host, device and global functions are never emitted.
18343 // (Technically, we do emit a host-side stub for global functions, but this
18344 // doesn't count for our purposes here.)
18345 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18346 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18347 return FunctionEmissionStatus::CUDADiscarded;
18348 if (!LangOpts.CUDAIsDevice &&
18349 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18350 return FunctionEmissionStatus::CUDADiscarded;
18351
18352 // Check whether this function is externally visible -- if so, it's
18353 // known-emitted.
18354 //
18355 // We have to check the GVA linkage of the function's *definition* -- if we
18356 // only have a declaration, we don't know whether or not the function will
18357 // be emitted, because (say) the definition could include "inline".
18358 FunctionDecl *Def = FD->getDefinition();
18359
18360 if (Def &&
18361 !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def))
18362 && (!LangOpts.OpenMP || OMPES == FunctionEmissionStatus::Emitted))
18363 return FunctionEmissionStatus::Emitted;
18364 }
18365
18366 // Otherwise, the function is known-emitted if it's in our set of
18367 // known-emitted functions.
18368 return FunctionEmissionStatus::Unknown;
18369}
18370
18371bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18372 // Host-side references to a __global__ function refer to the stub, so the
18373 // function itself is never emitted and therefore should not be marked.
18374 // If we have host fn calls kernel fn calls host+device, the HD function
18375 // does not get instantiated on the host. We model this by omitting at the
18376 // call to the kernel from the callgraph. This ensures that, when compiling
18377 // for host, only HD functions actually called from the host get marked as
18378 // known-emitted.
18379 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18380 IdentifyCUDATarget(Callee) == CFT_Global;
18381}

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- 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/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class Type;
65
66enum {
67 TypeAlignmentInBits = 4,
68 TypeAlignment = 1 << TypeAlignmentInBits
69};
70
71namespace serialization {
72 template <class T> class AbstractTypeReader;
73 template <class T> class AbstractTypeWriter;
74}
75
76} // namespace clang
77
78namespace llvm {
79
80 template <typename T>
81 struct PointerLikeTypeTraits;
82 template<>
83 struct PointerLikeTypeTraits< ::clang::Type*> {
84 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
85
86 static inline ::clang::Type *getFromVoidPointer(void *P) {
87 return static_cast< ::clang::Type*>(P);
88 }
89
90 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
91 };
92
93 template<>
94 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
95 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
96
97 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
98 return static_cast< ::clang::ExtQuals*>(P);
99 }
100
101 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
102 };
103
104} // namespace llvm
105
106namespace clang {
107
108class ASTContext;
109template <typename> class CanQual;
110class CXXRecordDecl;
111class DeclContext;
112class EnumDecl;
113class Expr;
114class ExtQualsTypeCommonBase;
115class FunctionDecl;
116class IdentifierInfo;
117class NamedDecl;
118class ObjCInterfaceDecl;
119class ObjCProtocolDecl;
120class ObjCTypeParamDecl;
121struct PrintingPolicy;
122class RecordDecl;
123class Stmt;
124class TagDecl;
125class TemplateArgument;
126class TemplateArgumentListInfo;
127class TemplateArgumentLoc;
128class TemplateTypeParmDecl;
129class TypedefNameDecl;
130class UnresolvedUsingTypenameDecl;
131
132using CanQualType = CanQual<Type>;
133
134// Provide forward declarations for all of the *Type classes.
135#define TYPE(Class, Base) class Class##Type;
136#include "clang/AST/TypeNodes.inc"
137
138/// The collection of all-type qualifiers we support.
139/// Clang supports five independent qualifiers:
140/// * C99: const, volatile, and restrict
141/// * MS: __unaligned
142/// * Embedded C (TR18037): address spaces
143/// * Objective C: the GC attributes (none, weak, or strong)
144class Qualifiers {
145public:
146 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
147 Const = 0x1,
148 Restrict = 0x2,
149 Volatile = 0x4,
150 CVRMask = Const | Volatile | Restrict
151 };
152
153 enum GC {
154 GCNone = 0,
155 Weak,
156 Strong
157 };
158
159 enum ObjCLifetime {
160 /// There is no lifetime qualification on this type.
161 OCL_None,
162
163 /// This object can be modified without requiring retains or
164 /// releases.
165 OCL_ExplicitNone,
166
167 /// Assigning into this object requires the old value to be
168 /// released and the new value to be retained. The timing of the
169 /// release of the old value is inexact: it may be moved to
170 /// immediately after the last known point where the value is
171 /// live.
172 OCL_Strong,
173
174 /// Reading or writing from this object requires a barrier call.
175 OCL_Weak,
176
177 /// Assigning into this object requires a lifetime extension.
178 OCL_Autoreleasing
179 };
180
181 enum {
182 /// The maximum supported address space number.
183 /// 23 bits should be enough for anyone.
184 MaxAddressSpace = 0x7fffffu,
185
186 /// The width of the "fast" qualifier mask.
187 FastWidth = 3,
188
189 /// The fast qualifier mask.
190 FastMask = (1 << FastWidth) - 1
191 };
192
193 /// Returns the common set of qualifiers while removing them from
194 /// the given sets.
195 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
196 // If both are only CVR-qualified, bit operations are sufficient.
197 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
198 Qualifiers Q;
199 Q.Mask = L.Mask & R.Mask;
200 L.Mask &= ~Q.Mask;
201 R.Mask &= ~Q.Mask;
202 return Q;
203 }
204
205 Qualifiers Q;
206 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
207 Q.addCVRQualifiers(CommonCRV);
208 L.removeCVRQualifiers(CommonCRV);
209 R.removeCVRQualifiers(CommonCRV);
210
211 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
212 Q.setObjCGCAttr(L.getObjCGCAttr());
213 L.removeObjCGCAttr();
214 R.removeObjCGCAttr();
215 }
216
217 if (L.getObjCLifetime() == R.getObjCLifetime()) {
218 Q.setObjCLifetime(L.getObjCLifetime());
219 L.removeObjCLifetime();
220 R.removeObjCLifetime();
221 }
222
223 if (L.getAddressSpace() == R.getAddressSpace()) {
224 Q.setAddressSpace(L.getAddressSpace());
225 L.removeAddressSpace();
226 R.removeAddressSpace();
227 }
228 return Q;
229 }
230
231 static Qualifiers fromFastMask(unsigned Mask) {
232 Qualifiers Qs;
233 Qs.addFastQualifiers(Mask);
234 return Qs;
235 }
236
237 static Qualifiers fromCVRMask(unsigned CVR) {
238 Qualifiers Qs;
239 Qs.addCVRQualifiers(CVR);
240 return Qs;
241 }
242
243 static Qualifiers fromCVRUMask(unsigned CVRU) {
244 Qualifiers Qs;
245 Qs.addCVRUQualifiers(CVRU);
246 return Qs;
247 }
248
249 // Deserialize qualifiers from an opaque representation.
250 static Qualifiers fromOpaqueValue(unsigned opaque) {
251 Qualifiers Qs;
252 Qs.Mask = opaque;
253 return Qs;
254 }
255
256 // Serialize these qualifiers into an opaque representation.
257 unsigned getAsOpaqueValue() const {
258 return Mask;
259 }
260
261 bool hasConst() const { return Mask & Const; }
262 bool hasOnlyConst() const { return Mask == Const; }
263 void removeConst() { Mask &= ~Const; }
264 void addConst() { Mask |= Const; }
265
266 bool hasVolatile() const { return Mask & Volatile; }
267 bool hasOnlyVolatile() const { return Mask == Volatile; }
268 void removeVolatile() { Mask &= ~Volatile; }
269 void addVolatile() { Mask |= Volatile; }
270
271 bool hasRestrict() const { return Mask & Restrict; }
272 bool hasOnlyRestrict() const { return Mask == Restrict; }
273 void removeRestrict() { Mask &= ~Restrict; }
274 void addRestrict() { Mask |= Restrict; }
275
276 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
277 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
278 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
279
280 void setCVRQualifiers(unsigned mask) {
281 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 281, __PRETTY_FUNCTION__))
;
282 Mask = (Mask & ~CVRMask) | mask;
283 }
284 void removeCVRQualifiers(unsigned mask) {
285 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 285, __PRETTY_FUNCTION__))
;
286 Mask &= ~mask;
287 }
288 void removeCVRQualifiers() {
289 removeCVRQualifiers(CVRMask);
290 }
291 void addCVRQualifiers(unsigned mask) {
292 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 292, __PRETTY_FUNCTION__))
;
293 Mask |= mask;
294 }
295 void addCVRUQualifiers(unsigned mask) {
296 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 296, __PRETTY_FUNCTION__))
;
297 Mask |= mask;
298 }
299
300 bool hasUnaligned() const { return Mask & UMask; }
301 void setUnaligned(bool flag) {
302 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
303 }
304 void removeUnaligned() { Mask &= ~UMask; }
305 void addUnaligned() { Mask |= UMask; }
306
307 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
308 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
309 void setObjCGCAttr(GC type) {
310 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
311 }
312 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
313 void addObjCGCAttr(GC type) {
314 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 314, __PRETTY_FUNCTION__))
;
315 setObjCGCAttr(type);
316 }
317 Qualifiers withoutObjCGCAttr() const {
318 Qualifiers qs = *this;
319 qs.removeObjCGCAttr();
320 return qs;
321 }
322 Qualifiers withoutObjCLifetime() const {
323 Qualifiers qs = *this;
324 qs.removeObjCLifetime();
325 return qs;
326 }
327 Qualifiers withoutAddressSpace() const {
328 Qualifiers qs = *this;
329 qs.removeAddressSpace();
330 return qs;
331 }
332
333 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
334 ObjCLifetime getObjCLifetime() const {
335 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
336 }
337 void setObjCLifetime(ObjCLifetime type) {
338 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
339 }
340 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
341 void addObjCLifetime(ObjCLifetime type) {
342 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 342, __PRETTY_FUNCTION__))
;
343 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 Mask |= (type << LifetimeShift);
345 }
346
347 /// True if the lifetime is neither None or ExplicitNone.
348 bool hasNonTrivialObjCLifetime() const {
349 ObjCLifetime lifetime = getObjCLifetime();
350 return (lifetime > OCL_ExplicitNone);
351 }
352
353 /// True if the lifetime is either strong or weak.
354 bool hasStrongOrWeakObjCLifetime() const {
355 ObjCLifetime lifetime = getObjCLifetime();
356 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
357 }
358
359 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
360 LangAS getAddressSpace() const {
361 return static_cast<LangAS>(Mask >> AddressSpaceShift);
362 }
363 bool hasTargetSpecificAddressSpace() const {
364 return isTargetAddressSpace(getAddressSpace());
365 }
366 /// Get the address space attribute value to be printed by diagnostics.
367 unsigned getAddressSpaceAttributePrintValue() const {
368 auto Addr = getAddressSpace();
369 // This function is not supposed to be used with language specific
370 // address spaces. If that happens, the diagnostic message should consider
371 // printing the QualType instead of the address space value.
372 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 372, __PRETTY_FUNCTION__))
;
373 if (Addr != LangAS::Default)
374 return toTargetAddressSpace(Addr);
375 // TODO: The diagnostic messages where Addr may be 0 should be fixed
376 // since it cannot differentiate the situation where 0 denotes the default
377 // address space or user specified __attribute__((address_space(0))).
378 return 0;
379 }
380 void setAddressSpace(LangAS space) {
381 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 381, __PRETTY_FUNCTION__))
;
382 Mask = (Mask & ~AddressSpaceMask)
383 | (((uint32_t) space) << AddressSpaceShift);
384 }
385 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
386 void addAddressSpace(LangAS space) {
387 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 387, __PRETTY_FUNCTION__))
;
388 setAddressSpace(space);
389 }
390
391 // Fast qualifiers are those that can be allocated directly
392 // on a QualType object.
393 bool hasFastQualifiers() const { return getFastQualifiers(); }
394 unsigned getFastQualifiers() const { return Mask & FastMask; }
395 void setFastQualifiers(unsigned mask) {
396 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 396, __PRETTY_FUNCTION__))
;
397 Mask = (Mask & ~FastMask) | mask;
398 }
399 void removeFastQualifiers(unsigned mask) {
400 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 400, __PRETTY_FUNCTION__))
;
401 Mask &= ~mask;
402 }
403 void removeFastQualifiers() {
404 removeFastQualifiers(FastMask);
405 }
406 void addFastQualifiers(unsigned mask) {
407 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 407, __PRETTY_FUNCTION__))
;
408 Mask |= mask;
409 }
410
411 /// Return true if the set contains any qualifiers which require an ExtQuals
412 /// node to be allocated.
413 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
414 Qualifiers getNonFastQualifiers() const {
415 Qualifiers Quals = *this;
416 Quals.setFastQualifiers(0);
417 return Quals;
418 }
419
420 /// Return true if the set contains any qualifiers.
421 bool hasQualifiers() const { return Mask; }
422 bool empty() const { return !Mask; }
423
424 /// Add the qualifiers from the given set to this set.
425 void addQualifiers(Qualifiers Q) {
426 // If the other set doesn't have any non-boolean qualifiers, just
427 // bit-or it in.
428 if (!(Q.Mask & ~CVRMask))
429 Mask |= Q.Mask;
430 else {
431 Mask |= (Q.Mask & CVRMask);
432 if (Q.hasAddressSpace())
433 addAddressSpace(Q.getAddressSpace());
434 if (Q.hasObjCGCAttr())
435 addObjCGCAttr(Q.getObjCGCAttr());
436 if (Q.hasObjCLifetime())
437 addObjCLifetime(Q.getObjCLifetime());
438 }
439 }
440
441 /// Remove the qualifiers from the given set from this set.
442 void removeQualifiers(Qualifiers Q) {
443 // If the other set doesn't have any non-boolean qualifiers, just
444 // bit-and the inverse in.
445 if (!(Q.Mask & ~CVRMask))
446 Mask &= ~Q.Mask;
447 else {
448 Mask &= ~(Q.Mask & CVRMask);
449 if (getObjCGCAttr() == Q.getObjCGCAttr())
450 removeObjCGCAttr();
451 if (getObjCLifetime() == Q.getObjCLifetime())
452 removeObjCLifetime();
453 if (getAddressSpace() == Q.getAddressSpace())
454 removeAddressSpace();
455 }
456 }
457
458 /// Add the qualifiers from the given set to this set, given that
459 /// they don't conflict.
460 void addConsistentQualifiers(Qualifiers qs) {
461 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
462 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 462, __PRETTY_FUNCTION__))
;
463 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
464 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 464, __PRETTY_FUNCTION__))
;
465 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
466 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 466, __PRETTY_FUNCTION__))
;
467 Mask |= qs.Mask;
468 }
469
470 /// Returns true if address space A is equal to or a superset of B.
471 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
472 /// overlapping address spaces.
473 /// CL1.1 or CL1.2:
474 /// every address space is a superset of itself.
475 /// CL2.0 adds:
476 /// __generic is a superset of any address space except for __constant.
477 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
478 // Address spaces must match exactly.
479 return A == B ||
480 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
481 // for __constant can be used as __generic.
482 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
483 // We also define global_device and global_host address spaces,
484 // to distinguish global pointers allocated on host from pointers
485 // allocated on device, which are a subset of __global.
486 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
487 B == LangAS::opencl_global_host)) ||
488 // Consider pointer size address spaces to be equivalent to default.
489 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
490 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
491 }
492
493 /// Returns true if the address space in these qualifiers is equal to or
494 /// a superset of the address space in the argument qualifiers.
495 bool isAddressSpaceSupersetOf(Qualifiers other) const {
496 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
497 }
498
499 /// Determines if these qualifiers compatibly include another set.
500 /// Generally this answers the question of whether an object with the other
501 /// qualifiers can be safely used as an object with these qualifiers.
502 bool compatiblyIncludes(Qualifiers other) const {
503 return isAddressSpaceSupersetOf(other) &&
504 // ObjC GC qualifiers can match, be added, or be removed, but can't
505 // be changed.
506 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
507 !other.hasObjCGCAttr()) &&
508 // ObjC lifetime qualifiers must match exactly.
509 getObjCLifetime() == other.getObjCLifetime() &&
510 // CVR qualifiers may subset.
511 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
512 // U qualifier may superset.
513 (!other.hasUnaligned() || hasUnaligned());
514 }
515
516 /// Determines if these qualifiers compatibly include another set of
517 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
518 ///
519 /// One set of Objective-C lifetime qualifiers compatibly includes the other
520 /// if the lifetime qualifiers match, or if both are non-__weak and the
521 /// including set also contains the 'const' qualifier, or both are non-__weak
522 /// and one is None (which can only happen in non-ARC modes).
523 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
524 if (getObjCLifetime() == other.getObjCLifetime())
525 return true;
526
527 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
528 return false;
529
530 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
531 return true;
532
533 return hasConst();
534 }
535
536 /// Determine whether this set of qualifiers is a strict superset of
537 /// another set of qualifiers, not considering qualifier compatibility.
538 bool isStrictSupersetOf(Qualifiers Other) const;
539
540 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
541 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
542
543 explicit operator bool() const { return hasQualifiers(); }
544
545 Qualifiers &operator+=(Qualifiers R) {
546 addQualifiers(R);
547 return *this;
548 }
549
550 // Union two qualifier sets. If an enumerated qualifier appears
551 // in both sets, use the one from the right.
552 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
553 L += R;
554 return L;
555 }
556
557 Qualifiers &operator-=(Qualifiers R) {
558 removeQualifiers(R);
559 return *this;
560 }
561
562 /// Compute the difference between two qualifier sets.
563 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
564 L -= R;
565 return L;
566 }
567
568 std::string getAsString() const;
569 std::string getAsString(const PrintingPolicy &Policy) const;
570
571 static std::string getAddrSpaceAsString(LangAS AS);
572
573 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
574 void print(raw_ostream &OS, const PrintingPolicy &Policy,
575 bool appendSpaceIfNonEmpty = false) const;
576
577 void Profile(llvm::FoldingSetNodeID &ID) const {
578 ID.AddInteger(Mask);
579 }
580
581private:
582 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
583 // |C R V|U|GCAttr|Lifetime|AddressSpace|
584 uint32_t Mask = 0;
585
586 static const uint32_t UMask = 0x8;
587 static const uint32_t UShift = 3;
588 static const uint32_t GCAttrMask = 0x30;
589 static const uint32_t GCAttrShift = 4;
590 static const uint32_t LifetimeMask = 0x1C0;
591 static const uint32_t LifetimeShift = 6;
592 static const uint32_t AddressSpaceMask =
593 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
594 static const uint32_t AddressSpaceShift = 9;
595};
596
597/// A std::pair-like structure for storing a qualified type split
598/// into its local qualifiers and its locally-unqualified type.
599struct SplitQualType {
600 /// The locally-unqualified type.
601 const Type *Ty = nullptr;
602
603 /// The local qualifiers.
604 Qualifiers Quals;
605
606 SplitQualType() = default;
607 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
608
609 SplitQualType getSingleStepDesugaredType() const; // end of this file
610
611 // Make std::tie work.
612 std::pair<const Type *,Qualifiers> asPair() const {
613 return std::pair<const Type *, Qualifiers>(Ty, Quals);
614 }
615
616 friend bool operator==(SplitQualType a, SplitQualType b) {
617 return a.Ty == b.Ty && a.Quals == b.Quals;
618 }
619 friend bool operator!=(SplitQualType a, SplitQualType b) {
620 return a.Ty != b.Ty || a.Quals != b.Quals;
621 }
622};
623
624/// The kind of type we are substituting Objective-C type arguments into.
625///
626/// The kind of substitution affects the replacement of type parameters when
627/// no concrete type information is provided, e.g., when dealing with an
628/// unspecialized type.
629enum class ObjCSubstitutionContext {
630 /// An ordinary type.
631 Ordinary,
632
633 /// The result type of a method or function.
634 Result,
635
636 /// The parameter type of a method or function.
637 Parameter,
638
639 /// The type of a property.
640 Property,
641
642 /// The superclass of a type.
643 Superclass,
644};
645
646/// A (possibly-)qualified type.
647///
648/// For efficiency, we don't store CV-qualified types as nodes on their
649/// own: instead each reference to a type stores the qualifiers. This
650/// greatly reduces the number of nodes we need to allocate for types (for
651/// example we only need one for 'int', 'const int', 'volatile int',
652/// 'const volatile int', etc).
653///
654/// As an added efficiency bonus, instead of making this a pair, we
655/// just store the two bits we care about in the low bits of the
656/// pointer. To handle the packing/unpacking, we make QualType be a
657/// simple wrapper class that acts like a smart pointer. A third bit
658/// indicates whether there are extended qualifiers present, in which
659/// case the pointer points to a special structure.
660class QualType {
661 friend class QualifierCollector;
662
663 // Thankfully, these are efficiently composable.
664 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
665 Qualifiers::FastWidth> Value;
666
667 const ExtQuals *getExtQualsUnsafe() const {
668 return Value.getPointer().get<const ExtQuals*>();
669 }
670
671 const Type *getTypePtrUnsafe() const {
672 return Value.getPointer().get<const Type*>();
673 }
674
675 const ExtQualsTypeCommonBase *getCommonPtr() const {
676 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 676, __PRETTY_FUNCTION__))
;
677 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
678 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
679 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
680 }
681
682public:
683 QualType() = default;
684 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
685 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
686
687 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
688 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
689
690 /// Retrieves a pointer to the underlying (unqualified) type.
691 ///
692 /// This function requires that the type not be NULL. If the type might be
693 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
694 const Type *getTypePtr() const;
695
696 const Type *getTypePtrOrNull() const;
697
698 /// Retrieves a pointer to the name of the base type.
699 const IdentifierInfo *getBaseTypeIdentifier() const;
700
701 /// Divides a QualType into its unqualified type and a set of local
702 /// qualifiers.
703 SplitQualType split() const;
704
705 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
706
707 static QualType getFromOpaquePtr(const void *Ptr) {
708 QualType T;
709 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
710 return T;
711 }
712
713 const Type &operator*() const {
714 return *getTypePtr();
715 }
716
717 const Type *operator->() const {
718 return getTypePtr();
719 }
720
721 bool isCanonical() const;
722 bool isCanonicalAsParam() const;
723
724 /// Return true if this QualType doesn't point to a type yet.
725 bool isNull() const {
726 return Value.getPointer().isNull();
727 }
728
729 /// Determine whether this particular QualType instance has the
730 /// "const" qualifier set, without looking through typedefs that may have
731 /// added "const" at a different level.
732 bool isLocalConstQualified() const {
733 return (getLocalFastQualifiers() & Qualifiers::Const);
734 }
735
736 /// Determine whether this type is const-qualified.
737 bool isConstQualified() const;
738
739 /// Determine whether this particular QualType instance has the
740 /// "restrict" qualifier set, without looking through typedefs that may have
741 /// added "restrict" at a different level.
742 bool isLocalRestrictQualified() const {
743 return (getLocalFastQualifiers() & Qualifiers::Restrict);
744 }
745
746 /// Determine whether this type is restrict-qualified.
747 bool isRestrictQualified() const;
748
749 /// Determine whether this particular QualType instance has the
750 /// "volatile" qualifier set, without looking through typedefs that may have
751 /// added "volatile" at a different level.
752 bool isLocalVolatileQualified() const {
753 return (getLocalFastQualifiers() & Qualifiers::Volatile);
754 }
755
756 /// Determine whether this type is volatile-qualified.
757 bool isVolatileQualified() const;
758
759 /// Determine whether this particular QualType instance has any
760 /// qualifiers, without looking through any typedefs that might add
761 /// qualifiers at a different level.
762 bool hasLocalQualifiers() const {
763 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
764 }
765
766 /// Determine whether this type has any qualifiers.
767 bool hasQualifiers() const;
768
769 /// Determine whether this particular QualType instance has any
770 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
771 /// instance.
772 bool hasLocalNonFastQualifiers() const {
773 return Value.getPointer().is<const ExtQuals*>();
774 }
775
776 /// Retrieve the set of qualifiers local to this particular QualType
777 /// instance, not including any qualifiers acquired through typedefs or
778 /// other sugar.
779 Qualifiers getLocalQualifiers() const;
780
781 /// Retrieve the set of qualifiers applied to this type.
782 Qualifiers getQualifiers() const;
783
784 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
785 /// local to this particular QualType instance, not including any qualifiers
786 /// acquired through typedefs or other sugar.
787 unsigned getLocalCVRQualifiers() const {
788 return getLocalFastQualifiers();
789 }
790
791 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
792 /// applied to this type.
793 unsigned getCVRQualifiers() const;
794
795 bool isConstant(const ASTContext& Ctx) const {
796 return QualType::isConstant(*this, Ctx);
797 }
798
799 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
800 bool isPODType(const ASTContext &Context) const;
801
802 /// Return true if this is a POD type according to the rules of the C++98
803 /// standard, regardless of the current compilation's language.
804 bool isCXX98PODType(const ASTContext &Context) const;
805
806 /// Return true if this is a POD type according to the more relaxed rules
807 /// of the C++11 standard, regardless of the current compilation's language.
808 /// (C++0x [basic.types]p9). Note that, unlike
809 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
810 bool isCXX11PODType(const ASTContext &Context) const;
811
812 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
813 bool isTrivialType(const ASTContext &Context) const;
814
815 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
816 bool isTriviallyCopyableType(const ASTContext &Context) const;
817
818
819 /// Returns true if it is a class and it might be dynamic.
820 bool mayBeDynamicClass() const;
821
822 /// Returns true if it is not a class or if the class might not be dynamic.
823 bool mayBeNotDynamicClass() const;
824
825 // Don't promise in the API that anything besides 'const' can be
826 // easily added.
827
828 /// Add the `const` type qualifier to this QualType.
829 void addConst() {
830 addFastQualifiers(Qualifiers::Const);
831 }
832 QualType withConst() const {
833 return withFastQualifiers(Qualifiers::Const);
834 }
835
836 /// Add the `volatile` type qualifier to this QualType.
837 void addVolatile() {
838 addFastQualifiers(Qualifiers::Volatile);
839 }
840 QualType withVolatile() const {
841 return withFastQualifiers(Qualifiers::Volatile);
842 }
843
844 /// Add the `restrict` qualifier to this QualType.
845 void addRestrict() {
846 addFastQualifiers(Qualifiers::Restrict);
847 }
848 QualType withRestrict() const {
849 return withFastQualifiers(Qualifiers::Restrict);
850 }
851
852 QualType withCVRQualifiers(unsigned CVR) const {
853 return withFastQualifiers(CVR);
854 }
855
856 void addFastQualifiers(unsigned TQs) {
857 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 858, __PRETTY_FUNCTION__))
858 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 858, __PRETTY_FUNCTION__))
;
859 Value.setInt(Value.getInt() | TQs);
860 }
861
862 void removeLocalConst();
863 void removeLocalVolatile();
864 void removeLocalRestrict();
865 void removeLocalCVRQualifiers(unsigned Mask);
866
867 void removeLocalFastQualifiers() { Value.setInt(0); }
868 void removeLocalFastQualifiers(unsigned Mask) {
869 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 869, __PRETTY_FUNCTION__))
;
870 Value.setInt(Value.getInt() & ~Mask);
871 }
872
873 // Creates a type with the given qualifiers in addition to any
874 // qualifiers already on this type.
875 QualType withFastQualifiers(unsigned TQs) const {
876 QualType T = *this;
877 T.addFastQualifiers(TQs);
878 return T;
879 }
880
881 // Creates a type with exactly the given fast qualifiers, removing
882 // any existing fast qualifiers.
883 QualType withExactLocalFastQualifiers(unsigned TQs) const {
884 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
885 }
886
887 // Removes fast qualifiers, but leaves any extended qualifiers in place.
888 QualType withoutLocalFastQualifiers() const {
889 QualType T = *this;
890 T.removeLocalFastQualifiers();
891 return T;
892 }
893
894 QualType getCanonicalType() const;
895
896 /// Return this type with all of the instance-specific qualifiers
897 /// removed, but without removing any qualifiers that may have been applied
898 /// through typedefs.
899 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
900
901 /// Retrieve the unqualified variant of the given type,
902 /// removing as little sugar as possible.
903 ///
904 /// This routine looks through various kinds of sugar to find the
905 /// least-desugared type that is unqualified. For example, given:
906 ///
907 /// \code
908 /// typedef int Integer;
909 /// typedef const Integer CInteger;
910 /// typedef CInteger DifferenceType;
911 /// \endcode
912 ///
913 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
914 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
915 ///
916 /// The resulting type might still be qualified if it's sugar for an array
917 /// type. To strip qualifiers even from within a sugared array type, use
918 /// ASTContext::getUnqualifiedArrayType.
919 inline QualType getUnqualifiedType() const;
920
921 /// Retrieve the unqualified variant of the given type, removing as little
922 /// sugar as possible.
923 ///
924 /// Like getUnqualifiedType(), but also returns the set of
925 /// qualifiers that were built up.
926 ///
927 /// The resulting type might still be qualified if it's sugar for an array
928 /// type. To strip qualifiers even from within a sugared array type, use
929 /// ASTContext::getUnqualifiedArrayType.
930 inline SplitQualType getSplitUnqualifiedType() const;
931
932 /// Determine whether this type is more qualified than the other
933 /// given type, requiring exact equality for non-CVR qualifiers.
934 bool isMoreQualifiedThan(QualType Other) const;
935
936 /// Determine whether this type is at least as qualified as the other
937 /// given type, requiring exact equality for non-CVR qualifiers.
938 bool isAtLeastAsQualifiedAs(QualType Other) const;
939
940 QualType getNonReferenceType() const;
941
942 /// Determine the type of a (typically non-lvalue) expression with the
943 /// specified result type.
944 ///
945 /// This routine should be used for expressions for which the return type is
946 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
947 /// an lvalue. It removes a top-level reference (since there are no
948 /// expressions of reference type) and deletes top-level cvr-qualifiers
949 /// from non-class types (in C++) or all types (in C).
950 QualType getNonLValueExprType(const ASTContext &Context) const;
951
952 /// Remove an outer pack expansion type (if any) from this type. Used as part
953 /// of converting the type of a declaration to the type of an expression that
954 /// references that expression. It's meaningless for an expression to have a
955 /// pack expansion type.
956 QualType getNonPackExpansionType() const;
957
958 /// Return the specified type with any "sugar" removed from
959 /// the type. This takes off typedefs, typeof's etc. If the outer level of
960 /// the type is already concrete, it returns it unmodified. This is similar
961 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
962 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
963 /// concrete.
964 ///
965 /// Qualifiers are left in place.
966 QualType getDesugaredType(const ASTContext &Context) const {
967 return getDesugaredType(*this, Context);
968 }
969
970 SplitQualType getSplitDesugaredType() const {
971 return getSplitDesugaredType(*this);
972 }
973
974 /// Return the specified type with one level of "sugar" removed from
975 /// the type.
976 ///
977 /// This routine takes off the first typedef, typeof, etc. If the outer level
978 /// of the type is already concrete, it returns it unmodified.
979 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
980 return getSingleStepDesugaredTypeImpl(*this, Context);
981 }
982
983 /// Returns the specified type after dropping any
984 /// outer-level parentheses.
985 QualType IgnoreParens() const {
986 if (isa<ParenType>(*this))
987 return QualType::IgnoreParens(*this);
988 return *this;
989 }
990
991 /// Indicate whether the specified types and qualifiers are identical.
992 friend bool operator==(const QualType &LHS, const QualType &RHS) {
993 return LHS.Value == RHS.Value;
994 }
995 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
996 return LHS.Value != RHS.Value;
997 }
998 friend bool operator<(const QualType &LHS, const QualType &RHS) {
999 return LHS.Value < RHS.Value;
1000 }
1001
1002 static std::string getAsString(SplitQualType split,
1003 const PrintingPolicy &Policy) {
1004 return getAsString(split.Ty, split.Quals, Policy);
1005 }
1006 static std::string getAsString(const Type *ty, Qualifiers qs,
1007 const PrintingPolicy &Policy);
1008
1009 std::string getAsString() const;
1010 std::string getAsString(const PrintingPolicy &Policy) const;
1011
1012 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1013 const Twine &PlaceHolder = Twine(),
1014 unsigned Indentation = 0) const;
1015
1016 static void print(SplitQualType split, raw_ostream &OS,
1017 const PrintingPolicy &policy, const Twine &PlaceHolder,
1018 unsigned Indentation = 0) {
1019 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1020 }
1021
1022 static void print(const Type *ty, Qualifiers qs,
1023 raw_ostream &OS, const PrintingPolicy &policy,
1024 const Twine &PlaceHolder,
1025 unsigned Indentation = 0);
1026
1027 void getAsStringInternal(std::string &Str,
1028 const PrintingPolicy &Policy) const;
1029
1030 static void getAsStringInternal(SplitQualType split, std::string &out,
1031 const PrintingPolicy &policy) {
1032 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1033 }
1034
1035 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1036 std::string &out,
1037 const PrintingPolicy &policy);
1038
1039 class StreamedQualTypeHelper {
1040 const QualType &T;
1041 const PrintingPolicy &Policy;
1042 const Twine &PlaceHolder;
1043 unsigned Indentation;
1044
1045 public:
1046 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1047 const Twine &PlaceHolder, unsigned Indentation)
1048 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1049 Indentation(Indentation) {}
1050
1051 friend raw_ostream &operator<<(raw_ostream &OS,
1052 const StreamedQualTypeHelper &SQT) {
1053 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1054 return OS;
1055 }
1056 };
1057
1058 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1059 const Twine &PlaceHolder = Twine(),
1060 unsigned Indentation = 0) const {
1061 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1062 }
1063
1064 void dump(const char *s) const;
1065 void dump() const;
1066 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1067
1068 void Profile(llvm::FoldingSetNodeID &ID) const {
1069 ID.AddPointer(getAsOpaquePtr());
1070 }
1071
1072 /// Check if this type has any address space qualifier.
1073 inline bool hasAddressSpace() const;
1074
1075 /// Return the address space of this type.
1076 inline LangAS getAddressSpace() const;
1077
1078 /// Returns true if address space qualifiers overlap with T address space
1079 /// qualifiers.
1080 /// OpenCL C defines conversion rules for pointers to different address spaces
1081 /// and notion of overlapping address spaces.
1082 /// CL1.1 or CL1.2:
1083 /// address spaces overlap iff they are they same.
1084 /// OpenCL C v2.0 s6.5.5 adds:
1085 /// __generic overlaps with any address space except for __constant.
1086 bool isAddressSpaceOverlapping(QualType T) const {
1087 Qualifiers Q = getQualifiers();
1088 Qualifiers TQ = T.getQualifiers();
1089 // Address spaces overlap if at least one of them is a superset of another
1090 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1091 }
1092
1093 /// Returns gc attribute of this type.
1094 inline Qualifiers::GC getObjCGCAttr() const;
1095
1096 /// true when Type is objc's weak.
1097 bool isObjCGCWeak() const {
1098 return getObjCGCAttr() == Qualifiers::Weak;
1099 }
1100
1101 /// true when Type is objc's strong.
1102 bool isObjCGCStrong() const {
1103 return getObjCGCAttr() == Qualifiers::Strong;
1104 }
1105
1106 /// Returns lifetime attribute of this type.
1107 Qualifiers::ObjCLifetime getObjCLifetime() const {
1108 return getQualifiers().getObjCLifetime();
1109 }
1110
1111 bool hasNonTrivialObjCLifetime() const {
1112 return getQualifiers().hasNonTrivialObjCLifetime();
1113 }
1114
1115 bool hasStrongOrWeakObjCLifetime() const {
1116 return getQualifiers().hasStrongOrWeakObjCLifetime();
1117 }
1118
1119 // true when Type is objc's weak and weak is enabled but ARC isn't.
1120 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1121
1122 enum PrimitiveDefaultInitializeKind {
1123 /// The type does not fall into any of the following categories. Note that
1124 /// this case is zero-valued so that values of this enum can be used as a
1125 /// boolean condition for non-triviality.
1126 PDIK_Trivial,
1127
1128 /// The type is an Objective-C retainable pointer type that is qualified
1129 /// with the ARC __strong qualifier.
1130 PDIK_ARCStrong,
1131
1132 /// The type is an Objective-C retainable pointer type that is qualified
1133 /// with the ARC __weak qualifier.
1134 PDIK_ARCWeak,
1135
1136 /// The type is a struct containing a field whose type is not PCK_Trivial.
1137 PDIK_Struct
1138 };
1139
1140 /// Functions to query basic properties of non-trivial C struct types.
1141
1142 /// Check if this is a non-trivial type that would cause a C struct
1143 /// transitively containing this type to be non-trivial to default initialize
1144 /// and return the kind.
1145 PrimitiveDefaultInitializeKind
1146 isNonTrivialToPrimitiveDefaultInitialize() const;
1147
1148 enum PrimitiveCopyKind {
1149 /// The type does not fall into any of the following categories. Note that
1150 /// this case is zero-valued so that values of this enum can be used as a
1151 /// boolean condition for non-triviality.
1152 PCK_Trivial,
1153
1154 /// The type would be trivial except that it is volatile-qualified. Types
1155 /// that fall into one of the other non-trivial cases may additionally be
1156 /// volatile-qualified.
1157 PCK_VolatileTrivial,
1158
1159 /// The type is an Objective-C retainable pointer type that is qualified
1160 /// with the ARC __strong qualifier.
1161 PCK_ARCStrong,
1162
1163 /// The type is an Objective-C retainable pointer type that is qualified
1164 /// with the ARC __weak qualifier.
1165 PCK_ARCWeak,
1166
1167 /// The type is a struct containing a field whose type is neither
1168 /// PCK_Trivial nor PCK_VolatileTrivial.
1169 /// Note that a C++ struct type does not necessarily match this; C++ copying
1170 /// semantics are too complex to express here, in part because they depend
1171 /// on the exact constructor or assignment operator that is chosen by
1172 /// overload resolution to do the copy.
1173 PCK_Struct
1174 };
1175
1176 /// Check if this is a non-trivial type that would cause a C struct
1177 /// transitively containing this type to be non-trivial to copy and return the
1178 /// kind.
1179 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1180
1181 /// Check if this is a non-trivial type that would cause a C struct
1182 /// transitively containing this type to be non-trivial to destructively
1183 /// move and return the kind. Destructive move in this context is a C++-style
1184 /// move in which the source object is placed in a valid but unspecified state
1185 /// after it is moved, as opposed to a truly destructive move in which the
1186 /// source object is placed in an uninitialized state.
1187 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1188
1189 enum DestructionKind {
1190 DK_none,
1191 DK_cxx_destructor,
1192 DK_objc_strong_lifetime,
1193 DK_objc_weak_lifetime,
1194 DK_nontrivial_c_struct
1195 };
1196
1197 /// Returns a nonzero value if objects of this type require
1198 /// non-trivial work to clean up after. Non-zero because it's
1199 /// conceivable that qualifiers (objc_gc(weak)?) could make
1200 /// something require destruction.
1201 DestructionKind isDestructedType() const {
1202 return isDestructedTypeImpl(*this);
1203 }
1204
1205 /// Check if this is or contains a C union that is non-trivial to
1206 /// default-initialize, which is a union that has a member that is non-trivial
1207 /// to default-initialize. If this returns true,
1208 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1209 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1210
1211 /// Check if this is or contains a C union that is non-trivial to destruct,
1212 /// which is a union that has a member that is non-trivial to destruct. If
1213 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1214 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1215
1216 /// Check if this is or contains a C union that is non-trivial to copy, which
1217 /// is a union that has a member that is non-trivial to copy. If this returns
1218 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1219 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1220
1221 /// Determine whether expressions of the given type are forbidden
1222 /// from being lvalues in C.
1223 ///
1224 /// The expression types that are forbidden to be lvalues are:
1225 /// - 'void', but not qualified void
1226 /// - function types
1227 ///
1228 /// The exact rule here is C99 6.3.2.1:
1229 /// An lvalue is an expression with an object type or an incomplete
1230 /// type other than void.
1231 bool isCForbiddenLValueType() const;
1232
1233 /// Substitute type arguments for the Objective-C type parameters used in the
1234 /// subject type.
1235 ///
1236 /// \param ctx ASTContext in which the type exists.
1237 ///
1238 /// \param typeArgs The type arguments that will be substituted for the
1239 /// Objective-C type parameters in the subject type, which are generally
1240 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1241 /// parameters will be replaced with their bounds or id/Class, as appropriate
1242 /// for the context.
1243 ///
1244 /// \param context The context in which the subject type was written.
1245 ///
1246 /// \returns the resulting type.
1247 QualType substObjCTypeArgs(ASTContext &ctx,
1248 ArrayRef<QualType> typeArgs,
1249 ObjCSubstitutionContext context) const;
1250
1251 /// Substitute type arguments from an object type for the Objective-C type
1252 /// parameters used in the subject type.
1253 ///
1254 /// This operation combines the computation of type arguments for
1255 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1256 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1257 /// callers that need to perform a single substitution in isolation.
1258 ///
1259 /// \param objectType The type of the object whose member type we're
1260 /// substituting into. For example, this might be the receiver of a message
1261 /// or the base of a property access.
1262 ///
1263 /// \param dc The declaration context from which the subject type was
1264 /// retrieved, which indicates (for example) which type parameters should
1265 /// be substituted.
1266 ///
1267 /// \param context The context in which the subject type was written.
1268 ///
1269 /// \returns the subject type after replacing all of the Objective-C type
1270 /// parameters with their corresponding arguments.
1271 QualType substObjCMemberType(QualType objectType,
1272 const DeclContext *dc,
1273 ObjCSubstitutionContext context) const;
1274
1275 /// Strip Objective-C "__kindof" types from the given type.
1276 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1277
1278 /// Remove all qualifiers including _Atomic.
1279 QualType getAtomicUnqualifiedType() const;
1280
1281private:
1282 // These methods are implemented in a separate translation unit;
1283 // "static"-ize them to avoid creating temporary QualTypes in the
1284 // caller.
1285 static bool isConstant(QualType T, const ASTContext& Ctx);
1286 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1287 static SplitQualType getSplitDesugaredType(QualType T);
1288 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1289 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1290 const ASTContext &C);
1291 static QualType IgnoreParens(QualType T);
1292 static DestructionKind isDestructedTypeImpl(QualType type);
1293
1294 /// Check if \param RD is or contains a non-trivial C union.
1295 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1296 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1297 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1298};
1299
1300} // namespace clang
1301
1302namespace llvm {
1303
1304/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1305/// to a specific Type class.
1306template<> struct simplify_type< ::clang::QualType> {
1307 using SimpleType = const ::clang::Type *;
1308
1309 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1310 return Val.getTypePtr();
1311 }
1312};
1313
1314// Teach SmallPtrSet that QualType is "basically a pointer".
1315template<>
1316struct PointerLikeTypeTraits<clang::QualType> {
1317 static inline void *getAsVoidPointer(clang::QualType P) {
1318 return P.getAsOpaquePtr();
1319 }
1320
1321 static inline clang::QualType getFromVoidPointer(void *P) {
1322 return clang::QualType::getFromOpaquePtr(P);
1323 }
1324
1325 // Various qualifiers go in low bits.
1326 static constexpr int NumLowBitsAvailable = 0;
1327};
1328
1329} // namespace llvm
1330
1331namespace clang {
1332
1333/// Base class that is common to both the \c ExtQuals and \c Type
1334/// classes, which allows \c QualType to access the common fields between the
1335/// two.
1336class ExtQualsTypeCommonBase {
1337 friend class ExtQuals;
1338 friend class QualType;
1339 friend class Type;
1340
1341 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1342 /// a self-referential pointer (for \c Type).
1343 ///
1344 /// This pointer allows an efficient mapping from a QualType to its
1345 /// underlying type pointer.
1346 const Type *const BaseType;
1347
1348 /// The canonical type of this type. A QualType.
1349 QualType CanonicalType;
1350
1351 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1352 : BaseType(baseType), CanonicalType(canon) {}
1353};
1354
1355/// We can encode up to four bits in the low bits of a
1356/// type pointer, but there are many more type qualifiers that we want
1357/// to be able to apply to an arbitrary type. Therefore we have this
1358/// struct, intended to be heap-allocated and used by QualType to
1359/// store qualifiers.
1360///
1361/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1362/// in three low bits on the QualType pointer; a fourth bit records whether
1363/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1364/// Objective-C GC attributes) are much more rare.
1365class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1366 // NOTE: changing the fast qualifiers should be straightforward as
1367 // long as you don't make 'const' non-fast.
1368 // 1. Qualifiers:
1369 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1370 // Fast qualifiers must occupy the low-order bits.
1371 // b) Update Qualifiers::FastWidth and FastMask.
1372 // 2. QualType:
1373 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1374 // b) Update remove{Volatile,Restrict}, defined near the end of
1375 // this header.
1376 // 3. ASTContext:
1377 // a) Update get{Volatile,Restrict}Type.
1378
1379 /// The immutable set of qualifiers applied by this node. Always contains
1380 /// extended qualifiers.
1381 Qualifiers Quals;
1382
1383 ExtQuals *this_() { return this; }
1384
1385public:
1386 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1387 : ExtQualsTypeCommonBase(baseType,
1388 canon.isNull() ? QualType(this_(), 0) : canon),
1389 Quals(quals) {
1390 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1391, __PRETTY_FUNCTION__))
1391 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1391, __PRETTY_FUNCTION__))
;
1392 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1393, __PRETTY_FUNCTION__))
1393 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1393, __PRETTY_FUNCTION__))
;
1394 }
1395
1396 Qualifiers getQualifiers() const { return Quals; }
1397
1398 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1399 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1400
1401 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1402 Qualifiers::ObjCLifetime getObjCLifetime() const {
1403 return Quals.getObjCLifetime();
1404 }
1405
1406 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1407 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1408
1409 const Type *getBaseType() const { return BaseType; }
1410
1411public:
1412 void Profile(llvm::FoldingSetNodeID &ID) const {
1413 Profile(ID, getBaseType(), Quals);
1414 }
1415
1416 static void Profile(llvm::FoldingSetNodeID &ID,
1417 const Type *BaseType,
1418 Qualifiers Quals) {
1419 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1419, __PRETTY_FUNCTION__))
;
1420 ID.AddPointer(BaseType);
1421 Quals.Profile(ID);
1422 }
1423};
1424
1425/// The kind of C++11 ref-qualifier associated with a function type.
1426/// This determines whether a member function's "this" object can be an
1427/// lvalue, rvalue, or neither.
1428enum RefQualifierKind {
1429 /// No ref-qualifier was provided.
1430 RQ_None = 0,
1431
1432 /// An lvalue ref-qualifier was provided (\c &).
1433 RQ_LValue,
1434
1435 /// An rvalue ref-qualifier was provided (\c &&).
1436 RQ_RValue
1437};
1438
1439/// Which keyword(s) were used to create an AutoType.
1440enum class AutoTypeKeyword {
1441 /// auto
1442 Auto,
1443
1444 /// decltype(auto)
1445 DecltypeAuto,
1446
1447 /// __auto_type (GNU extension)
1448 GNUAutoType
1449};
1450
1451/// The base class of the type hierarchy.
1452///
1453/// A central concept with types is that each type always has a canonical
1454/// type. A canonical type is the type with any typedef names stripped out
1455/// of it or the types it references. For example, consider:
1456///
1457/// typedef int foo;
1458/// typedef foo* bar;
1459/// 'int *' 'foo *' 'bar'
1460///
1461/// There will be a Type object created for 'int'. Since int is canonical, its
1462/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1463/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1464/// there is a PointerType that represents 'int*', which, like 'int', is
1465/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1466/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1467/// is also 'int*'.
1468///
1469/// Non-canonical types are useful for emitting diagnostics, without losing
1470/// information about typedefs being used. Canonical types are useful for type
1471/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1472/// about whether something has a particular form (e.g. is a function type),
1473/// because they implicitly, recursively, strip all typedefs out of a type.
1474///
1475/// Types, once created, are immutable.
1476///
1477class alignas(8) Type : public ExtQualsTypeCommonBase {
1478public:
1479 enum TypeClass {
1480#define TYPE(Class, Base) Class,
1481#define LAST_TYPE(Class) TypeLast = Class
1482#define ABSTRACT_TYPE(Class, Base)
1483#include "clang/AST/TypeNodes.inc"
1484 };
1485
1486private:
1487 /// Bitfields required by the Type class.
1488 class TypeBitfields {
1489 friend class Type;
1490 template <class T> friend class TypePropertyCache;
1491
1492 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1493 unsigned TC : 8;
1494
1495 /// Store information on the type dependency.
1496 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1497
1498 /// True if the cache (i.e. the bitfields here starting with
1499 /// 'Cache') is valid.
1500 mutable unsigned CacheValid : 1;
1501
1502 /// Linkage of this type.
1503 mutable unsigned CachedLinkage : 3;
1504
1505 /// Whether this type involves and local or unnamed types.
1506 mutable unsigned CachedLocalOrUnnamed : 1;
1507
1508 /// Whether this type comes from an AST file.
1509 mutable unsigned FromAST : 1;
1510
1511 bool isCacheValid() const {
1512 return CacheValid;
1513 }
1514
1515 Linkage getLinkage() const {
1516 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1516, __PRETTY_FUNCTION__))
;
1517 return static_cast<Linkage>(CachedLinkage);
1518 }
1519
1520 bool hasLocalOrUnnamedType() const {
1521 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 1521, __PRETTY_FUNCTION__))
;
1522 return CachedLocalOrUnnamed;
1523 }
1524 };
1525 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1526
1527protected:
1528 // These classes allow subclasses to somewhat cleanly pack bitfields
1529 // into Type.
1530
1531 class ArrayTypeBitfields {
1532 friend class ArrayType;
1533
1534 unsigned : NumTypeBits;
1535
1536 /// CVR qualifiers from declarations like
1537 /// 'int X[static restrict 4]'. For function parameters only.
1538 unsigned IndexTypeQuals : 3;
1539
1540 /// Storage class qualifiers from declarations like
1541 /// 'int X[static restrict 4]'. For function parameters only.
1542 /// Actually an ArrayType::ArraySizeModifier.
1543 unsigned SizeModifier : 3;
1544 };
1545
1546 class ConstantArrayTypeBitfields {
1547 friend class ConstantArrayType;
1548
1549 unsigned : NumTypeBits + 3 + 3;
1550
1551 /// Whether we have a stored size expression.
1552 unsigned HasStoredSizeExpr : 1;
1553 };
1554
1555 class BuiltinTypeBitfields {
1556 friend class BuiltinType;
1557
1558 unsigned : NumTypeBits;
1559
1560 /// The kind (BuiltinType::Kind) of builtin type this is.
1561 unsigned Kind : 8;
1562 };
1563
1564 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1565 /// Only common bits are stored here. Additional uncommon bits are stored
1566 /// in a trailing object after FunctionProtoType.
1567 class FunctionTypeBitfields {
1568 friend class FunctionProtoType;
1569 friend class FunctionType;
1570
1571 unsigned : NumTypeBits;
1572
1573 /// Extra information which affects how the function is called, like
1574 /// regparm and the calling convention.
1575 unsigned ExtInfo : 13;
1576
1577 /// The ref-qualifier associated with a \c FunctionProtoType.
1578 ///
1579 /// This is a value of type \c RefQualifierKind.
1580 unsigned RefQualifier : 2;
1581
1582 /// Used only by FunctionProtoType, put here to pack with the
1583 /// other bitfields.
1584 /// The qualifiers are part of FunctionProtoType because...
1585 ///
1586 /// C++ 8.3.5p4: The return type, the parameter type list and the
1587 /// cv-qualifier-seq, [...], are part of the function type.
1588 unsigned FastTypeQuals : Qualifiers::FastWidth;
1589 /// Whether this function has extended Qualifiers.
1590 unsigned HasExtQuals : 1;
1591
1592 /// The number of parameters this function has, not counting '...'.
1593 /// According to [implimits] 8 bits should be enough here but this is
1594 /// somewhat easy to exceed with metaprogramming and so we would like to
1595 /// keep NumParams as wide as reasonably possible.
1596 unsigned NumParams : 16;
1597
1598 /// The type of exception specification this function has.
1599 unsigned ExceptionSpecType : 4;
1600
1601 /// Whether this function has extended parameter information.
1602 unsigned HasExtParameterInfos : 1;
1603
1604 /// Whether the function is variadic.
1605 unsigned Variadic : 1;
1606
1607 /// Whether this function has a trailing return type.
1608 unsigned HasTrailingReturn : 1;
1609 };
1610
1611 class ObjCObjectTypeBitfields {
1612 friend class ObjCObjectType;
1613
1614 unsigned : NumTypeBits;
1615
1616 /// The number of type arguments stored directly on this object type.
1617 unsigned NumTypeArgs : 7;
1618
1619 /// The number of protocols stored directly on this object type.
1620 unsigned NumProtocols : 6;
1621
1622 /// Whether this is a "kindof" type.
1623 unsigned IsKindOf : 1;
1624 };
1625
1626 class ReferenceTypeBitfields {
1627 friend class ReferenceType;
1628
1629 unsigned : NumTypeBits;
1630
1631 /// True if the type was originally spelled with an lvalue sigil.
1632 /// This is never true of rvalue references but can also be false
1633 /// on lvalue references because of C++0x [dcl.typedef]p9,
1634 /// as follows:
1635 ///
1636 /// typedef int &ref; // lvalue, spelled lvalue
1637 /// typedef int &&rvref; // rvalue
1638 /// ref &a; // lvalue, inner ref, spelled lvalue
1639 /// ref &&a; // lvalue, inner ref
1640 /// rvref &a; // lvalue, inner ref, spelled lvalue
1641 /// rvref &&a; // rvalue, inner ref
1642 unsigned SpelledAsLValue : 1;
1643
1644 /// True if the inner type is a reference type. This only happens
1645 /// in non-canonical forms.
1646 unsigned InnerRef : 1;
1647 };
1648
1649 class TypeWithKeywordBitfields {
1650 friend class TypeWithKeyword;
1651
1652 unsigned : NumTypeBits;
1653
1654 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1655 unsigned Keyword : 8;
1656 };
1657
1658 enum { NumTypeWithKeywordBits = 8 };
1659
1660 class ElaboratedTypeBitfields {
1661 friend class ElaboratedType;
1662
1663 unsigned : NumTypeBits;
1664 unsigned : NumTypeWithKeywordBits;
1665
1666 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1667 unsigned HasOwnedTagDecl : 1;
1668 };
1669
1670 class VectorTypeBitfields {
1671 friend class VectorType;
1672 friend class DependentVectorType;
1673
1674 unsigned : NumTypeBits;
1675
1676 /// The kind of vector, either a generic vector type or some
1677 /// target-specific vector type such as for AltiVec or Neon.
1678 unsigned VecKind : 3;
1679 /// The number of elements in the vector.
1680 uint32_t NumElements;
1681 };
1682
1683 class AttributedTypeBitfields {
1684 friend class AttributedType;
1685
1686 unsigned : NumTypeBits;
1687
1688 /// An AttributedType::Kind
1689 unsigned AttrKind : 32 - NumTypeBits;
1690 };
1691
1692 class AutoTypeBitfields {
1693 friend class AutoType;
1694
1695 unsigned : NumTypeBits;
1696
1697 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1698 /// or '__auto_type'? AutoTypeKeyword value.
1699 unsigned Keyword : 2;
1700
1701 /// The number of template arguments in the type-constraints, which is
1702 /// expected to be able to hold at least 1024 according to [implimits].
1703 /// However as this limit is somewhat easy to hit with template
1704 /// metaprogramming we'd prefer to keep it as large as possible.
1705 /// At the moment it has been left as a non-bitfield since this type
1706 /// safely fits in 64 bits as an unsigned, so there is no reason to
1707 /// introduce the performance impact of a bitfield.
1708 unsigned NumArgs;
1709 };
1710
1711 class SubstTemplateTypeParmPackTypeBitfields {
1712 friend class SubstTemplateTypeParmPackType;
1713
1714 unsigned : NumTypeBits;
1715
1716 /// The number of template arguments in \c Arguments, which is
1717 /// expected to be able to hold at least 1024 according to [implimits].
1718 /// However as this limit is somewhat easy to hit with template
1719 /// metaprogramming we'd prefer to keep it as large as possible.
1720 /// At the moment it has been left as a non-bitfield since this type
1721 /// safely fits in 64 bits as an unsigned, so there is no reason to
1722 /// introduce the performance impact of a bitfield.
1723 unsigned NumArgs;
1724 };
1725
1726 class TemplateSpecializationTypeBitfields {
1727 friend class TemplateSpecializationType;
1728
1729 unsigned : NumTypeBits;
1730
1731 /// Whether this template specialization type is a substituted type alias.
1732 unsigned TypeAlias : 1;
1733
1734 /// The number of template arguments named in this class template
1735 /// specialization, which is expected to be able to hold at least 1024
1736 /// according to [implimits]. However, as this limit is somewhat easy to
1737 /// hit with template metaprogramming we'd prefer to keep it as large
1738 /// as possible. At the moment it has been left as a non-bitfield since
1739 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1740 /// to introduce the performance impact of a bitfield.
1741 unsigned NumArgs;
1742 };
1743
1744 class DependentTemplateSpecializationTypeBitfields {
1745 friend class DependentTemplateSpecializationType;
1746
1747 unsigned : NumTypeBits;
1748 unsigned : NumTypeWithKeywordBits;
1749
1750 /// The number of template arguments named in this class template
1751 /// specialization, which is expected to be able to hold at least 1024
1752 /// according to [implimits]. However, as this limit is somewhat easy to
1753 /// hit with template metaprogramming we'd prefer to keep it as large
1754 /// as possible. At the moment it has been left as a non-bitfield since
1755 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1756 /// to introduce the performance impact of a bitfield.
1757 unsigned NumArgs;
1758 };
1759
1760 class PackExpansionTypeBitfields {
1761 friend class PackExpansionType;
1762
1763 unsigned : NumTypeBits;
1764
1765 /// The number of expansions that this pack expansion will
1766 /// generate when substituted (+1), which is expected to be able to
1767 /// hold at least 1024 according to [implimits]. However, as this limit
1768 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1769 /// keep it as large as possible. At the moment it has been left as a
1770 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1771 /// there is no reason to introduce the performance impact of a bitfield.
1772 ///
1773 /// This field will only have a non-zero value when some of the parameter
1774 /// packs that occur within the pattern have been substituted but others
1775 /// have not.
1776 unsigned NumExpansions;
1777 };
1778
1779 union {
1780 TypeBitfields TypeBits;
1781 ArrayTypeBitfields ArrayTypeBits;
1782 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1783 AttributedTypeBitfields AttributedTypeBits;
1784 AutoTypeBitfields AutoTypeBits;
1785 BuiltinTypeBitfields BuiltinTypeBits;
1786 FunctionTypeBitfields FunctionTypeBits;
1787 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1788 ReferenceTypeBitfields ReferenceTypeBits;
1789 TypeWithKeywordBitfields TypeWithKeywordBits;
1790 ElaboratedTypeBitfields ElaboratedTypeBits;
1791 VectorTypeBitfields VectorTypeBits;
1792 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1793 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1794 DependentTemplateSpecializationTypeBitfields
1795 DependentTemplateSpecializationTypeBits;
1796 PackExpansionTypeBitfields PackExpansionTypeBits;
1797 };
1798
1799private:
1800 template <class T> friend class TypePropertyCache;
1801
1802 /// Set whether this type comes from an AST file.
1803 void setFromAST(bool V = true) const {
1804 TypeBits.FromAST = V;
1805 }
1806
1807protected:
1808 friend class ASTContext;
1809
1810 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1811 : ExtQualsTypeCommonBase(this,
1812 canon.isNull() ? QualType(this_(), 0) : canon) {
1813 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1814 "changing bitfields changed sizeof(Type)!");
1815 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1816 "Insufficient alignment!");
1817 TypeBits.TC = tc;
1818 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1819 TypeBits.CacheValid = false;
1820 TypeBits.CachedLocalOrUnnamed = false;
1821 TypeBits.CachedLinkage = NoLinkage;
1822 TypeBits.FromAST = false;
1823 }
1824
1825 // silence VC++ warning C4355: 'this' : used in base member initializer list
1826 Type *this_() { return this; }
1827
1828 void setDependence(TypeDependence D) {
1829 TypeBits.Dependence = static_cast<unsigned>(D);
1830 }
1831
1832 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1833
1834public:
1835 friend class ASTReader;
1836 friend class ASTWriter;
1837 template <class T> friend class serialization::AbstractTypeReader;
1838 template <class T> friend class serialization::AbstractTypeWriter;
1839
1840 Type(const Type &) = delete;
1841 Type(Type &&) = delete;
1842 Type &operator=(const Type &) = delete;
1843 Type &operator=(Type &&) = delete;
1844
1845 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1846
1847 /// Whether this type comes from an AST file.
1848 bool isFromAST() const { return TypeBits.FromAST; }
1849
1850 /// Whether this type is or contains an unexpanded parameter
1851 /// pack, used to support C++0x variadic templates.
1852 ///
1853 /// A type that contains a parameter pack shall be expanded by the
1854 /// ellipsis operator at some point. For example, the typedef in the
1855 /// following example contains an unexpanded parameter pack 'T':
1856 ///
1857 /// \code
1858 /// template<typename ...T>
1859 /// struct X {
1860 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1861 /// };
1862 /// \endcode
1863 ///
1864 /// Note that this routine does not specify which
1865 bool containsUnexpandedParameterPack() const {
1866 return getDependence() & TypeDependence::UnexpandedPack;
1867 }
1868
1869 /// Determines if this type would be canonical if it had no further
1870 /// qualification.
1871 bool isCanonicalUnqualified() const {
1872 return CanonicalType == QualType(this, 0);
1873 }
1874
1875 /// Pull a single level of sugar off of this locally-unqualified type.
1876 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1877 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1878 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1879
1880 /// As an extension, we classify types as one of "sized" or "sizeless";
1881 /// every type is one or the other. Standard types are all sized;
1882 /// sizeless types are purely an extension.
1883 ///
1884 /// Sizeless types contain data with no specified size, alignment,
1885 /// or layout.
1886 bool isSizelessType() const;
1887 bool isSizelessBuiltinType() const;
1888
1889 /// Determines if this is a sizeless type supported by the
1890 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1891 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1892 bool isVLSTBuiltinType() const;
1893
1894 /// Returns the representative type for the element of an SVE builtin type.
1895 /// This is used to represent fixed-length SVE vectors created with the
1896 /// 'arm_sve_vector_bits' type attribute as VectorType.
1897 QualType getSveEltType(const ASTContext &Ctx) const;
1898
1899 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1900 /// object types, function types, and incomplete types.
1901
1902 /// Return true if this is an incomplete type.
1903 /// A type that can describe objects, but which lacks information needed to
1904 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1905 /// routine will need to determine if the size is actually required.
1906 ///
1907 /// Def If non-null, and the type refers to some kind of declaration
1908 /// that can be completed (such as a C struct, C++ class, or Objective-C
1909 /// class), will be set to the declaration.
1910 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1911
1912 /// Return true if this is an incomplete or object
1913 /// type, in other words, not a function type.
1914 bool isIncompleteOrObjectType() const {
1915 return !isFunctionType();
1916 }
1917
1918 /// Determine whether this type is an object type.
1919 bool isObjectType() const {
1920 // C++ [basic.types]p8:
1921 // An object type is a (possibly cv-qualified) type that is not a
1922 // function type, not a reference type, and not a void type.
1923 return !isReferenceType() && !isFunctionType() && !isVoidType();
1924 }
1925
1926 /// Return true if this is a literal type
1927 /// (C++11 [basic.types]p10)
1928 bool isLiteralType(const ASTContext &Ctx) const;
1929
1930 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1931 bool isStructuralType() const;
1932
1933 /// Test if this type is a standard-layout type.
1934 /// (C++0x [basic.type]p9)
1935 bool isStandardLayoutType() const;
1936
1937 /// Helper methods to distinguish type categories. All type predicates
1938 /// operate on the canonical type, ignoring typedefs and qualifiers.
1939
1940 /// Returns true if the type is a builtin type.
1941 bool isBuiltinType() const;
1942
1943 /// Test for a particular builtin type.
1944 bool isSpecificBuiltinType(unsigned K) const;
1945
1946 /// Test for a type which does not represent an actual type-system type but
1947 /// is instead used as a placeholder for various convenient purposes within
1948 /// Clang. All such types are BuiltinTypes.
1949 bool isPlaceholderType() const;
1950 const BuiltinType *getAsPlaceholderType() const;
1951
1952 /// Test for a specific placeholder type.
1953 bool isSpecificPlaceholderType(unsigned K) const;
1954
1955 /// Test for a placeholder type other than Overload; see
1956 /// BuiltinType::isNonOverloadPlaceholderType.
1957 bool isNonOverloadPlaceholderType() const;
1958
1959 /// isIntegerType() does *not* include complex integers (a GCC extension).
1960 /// isComplexIntegerType() can be used to test for complex integers.
1961 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1962 bool isEnumeralType() const;
1963
1964 /// Determine whether this type is a scoped enumeration type.
1965 bool isScopedEnumeralType() const;
1966 bool isBooleanType() const;
1967 bool isCharType() const;
1968 bool isWideCharType() const;
1969 bool isChar8Type() const;
1970 bool isChar16Type() const;
1971 bool isChar32Type() const;
1972 bool isAnyCharacterType() const;
1973 bool isIntegralType(const ASTContext &Ctx) const;
1974
1975 /// Determine whether this type is an integral or enumeration type.
1976 bool isIntegralOrEnumerationType() const;
1977
1978 /// Determine whether this type is an integral or unscoped enumeration type.
1979 bool isIntegralOrUnscopedEnumerationType() const;
1980 bool isUnscopedEnumerationType() const;
1981
1982 /// Floating point categories.
1983 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1984 /// isComplexType() does *not* include complex integers (a GCC extension).
1985 /// isComplexIntegerType() can be used to test for complex integers.
1986 bool isComplexType() const; // C99 6.2.5p11 (complex)
1987 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1988 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1989 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1990 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1991 bool isBFloat16Type() const;
1992 bool isFloat128Type() const;
1993 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1994 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1995 bool isVoidType() const; // C99 6.2.5p19
1996 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1997 bool isAggregateType() const;
1998 bool isFundamentalType() const;
1999 bool isCompoundType() const;
2000
2001 // Type Predicates: Check to see if this type is structurally the specified
2002 // type, ignoring typedefs and qualifiers.
2003 bool isFunctionType() const;
2004 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2005 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2006 bool isPointerType() const;
2007 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2008 bool isBlockPointerType() const;
2009 bool isVoidPointerType() const;
2010 bool isReferenceType() const;
2011 bool isLValueReferenceType() const;
2012 bool isRValueReferenceType() const;
2013 bool isObjectPointerType() const;
2014 bool isFunctionPointerType() const;
2015 bool isFunctionReferenceType() const;
2016 bool isMemberPointerType() const;
2017 bool isMemberFunctionPointerType() const;
2018 bool isMemberDataPointerType() const;
2019 bool isArrayType() const;
2020 bool isConstantArrayType() const;
2021 bool isIncompleteArrayType() const;
2022 bool isVariableArrayType() const;
2023 bool isDependentSizedArrayType() const;
2024 bool isRecordType() const;
2025 bool isClassType() const;
2026 bool isStructureType() const;
2027 bool isObjCBoxableRecordType() const;
2028 bool isInterfaceType() const;
2029 bool isStructureOrClassType() const;
2030 bool isUnionType() const;
2031 bool isComplexIntegerType() const; // GCC _Complex integer type.
2032 bool isVectorType() const; // GCC vector type.
2033 bool isExtVectorType() const; // Extended vector type.
2034 bool isMatrixType() const; // Matrix type.
2035 bool isConstantMatrixType() const; // Constant matrix type.
2036 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2037 bool isObjCObjectPointerType() const; // pointer to ObjC object
2038 bool isObjCRetainableType() const; // ObjC object or block pointer
2039 bool isObjCLifetimeType() const; // (array of)* retainable type
2040 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2041 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2042 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2043 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2044 // for the common case.
2045 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2046 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2047 bool isObjCQualifiedIdType() const; // id<foo>
2048 bool isObjCQualifiedClassType() const; // Class<foo>
2049 bool isObjCObjectOrInterfaceType() const;
2050 bool isObjCIdType() const; // id
2051 bool isDecltypeType() const;
2052 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2053 /// qualifier?
2054 ///
2055 /// This approximates the answer to the following question: if this
2056 /// translation unit were compiled in ARC, would this type be qualified
2057 /// with __unsafe_unretained?
2058 bool isObjCInertUnsafeUnretainedType() const {
2059 return hasAttr(attr::ObjCInertUnsafeUnretained);
2060 }
2061
2062 /// Whether the type is Objective-C 'id' or a __kindof type of an
2063 /// object type, e.g., __kindof NSView * or __kindof id
2064 /// <NSCopying>.
2065 ///
2066 /// \param bound Will be set to the bound on non-id subtype types,
2067 /// which will be (possibly specialized) Objective-C class type, or
2068 /// null for 'id.
2069 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2070 const ObjCObjectType *&bound) const;
2071
2072 bool isObjCClassType() const; // Class
2073
2074 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2075 /// Class type, e.g., __kindof Class <NSCopying>.
2076 ///
2077 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2078 /// here because Objective-C's type system cannot express "a class
2079 /// object for a subclass of NSFoo".
2080 bool isObjCClassOrClassKindOfType() const;
2081
2082 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2083 bool isObjCSelType() const; // Class
2084 bool isObjCBuiltinType() const; // 'id' or 'Class'
2085 bool isObjCARCBridgableType() const;
2086 bool isCARCBridgableType() const;
2087 bool isTemplateTypeParmType() const; // C++ template type parameter
2088 bool isNullPtrType() const; // C++11 std::nullptr_t
2089 bool isNothrowT() const; // C++ std::nothrow_t
2090 bool isAlignValT() const; // C++17 std::align_val_t
2091 bool isStdByteType() const; // C++17 std::byte
2092 bool isAtomicType() const; // C11 _Atomic()
2093 bool isUndeducedAutoType() const; // C++11 auto or
2094 // C++14 decltype(auto)
2095
2096#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2097 bool is##Id##Type() const;
2098#include "clang/Basic/OpenCLImageTypes.def"
2099
2100 bool isImageType() const; // Any OpenCL image type
2101
2102 bool isSamplerT() const; // OpenCL sampler_t
2103 bool isEventT() const; // OpenCL event_t
2104 bool isClkEventT() const; // OpenCL clk_event_t
2105 bool isQueueT() const; // OpenCL queue_t
2106 bool isReserveIDT() const; // OpenCL reserve_id_t
2107
2108#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2109 bool is##Id##Type() const;
2110#include "clang/Basic/OpenCLExtensionTypes.def"
2111 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2112 bool isOCLIntelSubgroupAVCType() const;
2113 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2114
2115 bool isPipeType() const; // OpenCL pipe type
2116 bool isExtIntType() const; // Extended Int Type
2117 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2118
2119 /// Determines if this type, which must satisfy
2120 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2121 /// than implicitly __strong.
2122 bool isObjCARCImplicitlyUnretainedType() const;
2123
2124 /// Check if the type is the CUDA device builtin surface type.
2125 bool isCUDADeviceBuiltinSurfaceType() const;
2126 /// Check if the type is the CUDA device builtin texture type.
2127 bool isCUDADeviceBuiltinTextureType() const;
2128
2129 /// Return the implicit lifetime for this type, which must not be dependent.
2130 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2131
2132 enum ScalarTypeKind {
2133 STK_CPointer,
2134 STK_BlockPointer,
2135 STK_ObjCObjectPointer,
2136 STK_MemberPointer,
2137 STK_Bool,
2138 STK_Integral,
2139 STK_Floating,
2140 STK_IntegralComplex,
2141 STK_FloatingComplex,
2142 STK_FixedPoint
2143 };
2144
2145 /// Given that this is a scalar type, classify it.
2146 ScalarTypeKind getScalarTypeKind() const;
2147
2148 TypeDependence getDependence() const {
2149 return static_cast<TypeDependence>(TypeBits.Dependence);
2150 }
2151
2152 /// Whether this type is an error type.
2153 bool containsErrors() const {
2154 return getDependence() & TypeDependence::Error;
2155 }
2156
2157 /// Whether this type is a dependent type, meaning that its definition
2158 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2159 bool isDependentType() const {
2160 return getDependence() & TypeDependence::Dependent;
2161 }
2162
2163 /// Determine whether this type is an instantiation-dependent type,
2164 /// meaning that the type involves a template parameter (even if the
2165 /// definition does not actually depend on the type substituted for that
2166 /// template parameter).
2167 bool isInstantiationDependentType() const {
2168 return getDependence() & TypeDependence::Instantiation;
2169 }
2170
2171 /// Determine whether this type is an undeduced type, meaning that
2172 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2173 /// deduced.
2174 bool isUndeducedType() const;
2175
2176 /// Whether this type is a variably-modified type (C99 6.7.5).
2177 bool isVariablyModifiedType() const {
2178 return getDependence() & TypeDependence::VariablyModified;
2179 }
2180
2181 /// Whether this type involves a variable-length array type
2182 /// with a definite size.
2183 bool hasSizedVLAType() const;
2184
2185 /// Whether this type is or contains a local or unnamed type.
2186 bool hasUnnamedOrLocalType() const;
2187
2188 bool isOverloadableType() const;
2189
2190 /// Determine wither this type is a C++ elaborated-type-specifier.
2191 bool isElaboratedTypeSpecifier() const;
2192
2193 bool canDecayToPointerType() const;
2194
2195 /// Whether this type is represented natively as a pointer. This includes
2196 /// pointers, references, block pointers, and Objective-C interface,
2197 /// qualified id, and qualified interface types, as well as nullptr_t.
2198 bool hasPointerRepresentation() const;
2199
2200 /// Whether this type can represent an objective pointer type for the
2201 /// purpose of GC'ability
2202 bool hasObjCPointerRepresentation() const;
2203
2204 /// Determine whether this type has an integer representation
2205 /// of some sort, e.g., it is an integer type or a vector.
2206 bool hasIntegerRepresentation() const;
2207
2208 /// Determine whether this type has an signed integer representation
2209 /// of some sort, e.g., it is an signed integer type or a vector.
2210 bool hasSignedIntegerRepresentation() const;
2211
2212 /// Determine whether this type has an unsigned integer representation
2213 /// of some sort, e.g., it is an unsigned integer type or a vector.
2214 bool hasUnsignedIntegerRepresentation() const;
2215
2216 /// Determine whether this type has a floating-point representation
2217 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2218 bool hasFloatingRepresentation() const;
2219
2220 // Type Checking Functions: Check to see if this type is structurally the
2221 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2222 // the best type we can.
2223 const RecordType *getAsStructureType() const;
2224 /// NOTE: getAs*ArrayType are methods on ASTContext.
2225 const RecordType *getAsUnionType() const;
2226 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2227 const ObjCObjectType *getAsObjCInterfaceType() const;
2228
2229 // The following is a convenience method that returns an ObjCObjectPointerType
2230 // for object declared using an interface.
2231 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2232 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2233 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2234 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2235
2236 /// Retrieves the CXXRecordDecl that this type refers to, either
2237 /// because the type is a RecordType or because it is the injected-class-name
2238 /// type of a class template or class template partial specialization.
2239 CXXRecordDecl *getAsCXXRecordDecl() const;
2240
2241 /// Retrieves the RecordDecl this type refers to.
2242 RecordDecl *getAsRecordDecl() const;
2243
2244 /// Retrieves the TagDecl that this type refers to, either
2245 /// because the type is a TagType or because it is the injected-class-name
2246 /// type of a class template or class template partial specialization.
2247 TagDecl *getAsTagDecl() const;
2248
2249 /// If this is a pointer or reference to a RecordType, return the
2250 /// CXXRecordDecl that the type refers to.
2251 ///
2252 /// If this is not a pointer or reference, or the type being pointed to does
2253 /// not refer to a CXXRecordDecl, returns NULL.
2254 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2255
2256 /// Get the DeducedType whose type will be deduced for a variable with
2257 /// an initializer of this type. This looks through declarators like pointer
2258 /// types, but not through decltype or typedefs.
2259 DeducedType *getContainedDeducedType() const;
2260
2261 /// Get the AutoType whose type will be deduced for a variable with
2262 /// an initializer of this type. This looks through declarators like pointer
2263 /// types, but not through decltype or typedefs.
2264 AutoType *getContainedAutoType() const {
2265 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2266 }
2267
2268 /// Determine whether this type was written with a leading 'auto'
2269 /// corresponding to a trailing return type (possibly for a nested
2270 /// function type within a pointer to function type or similar).
2271 bool hasAutoForTrailingReturnType() const;
2272
2273 /// Member-template getAs<specific type>'. Look through sugar for
2274 /// an instance of \<specific type>. This scheme will eventually
2275 /// replace the specific getAsXXXX methods above.
2276 ///
2277 /// There are some specializations of this member template listed
2278 /// immediately following this class.
2279 template <typename T> const T *getAs() const;
2280
2281 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2282 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2283 /// This is used when you need to walk over sugar nodes that represent some
2284 /// kind of type adjustment from a type that was written as a \<specific type>
2285 /// to another type that is still canonically a \<specific type>.
2286 template <typename T> const T *getAsAdjusted() const;
2287
2288 /// A variant of getAs<> for array types which silently discards
2289 /// qualifiers from the outermost type.
2290 const ArrayType *getAsArrayTypeUnsafe() const;
2291
2292 /// Member-template castAs<specific type>. Look through sugar for
2293 /// the underlying instance of \<specific type>.
2294 ///
2295 /// This method has the same relationship to getAs<T> as cast<T> has
2296 /// to dyn_cast<T>; which is to say, the underlying type *must*
2297 /// have the intended type, and this method will never return null.
2298 template <typename T> const T *castAs() const;
2299
2300 /// A variant of castAs<> for array type which silently discards
2301 /// qualifiers from the outermost type.
2302 const ArrayType *castAsArrayTypeUnsafe() const;
2303
2304 /// Determine whether this type had the specified attribute applied to it
2305 /// (looking through top-level type sugar).
2306 bool hasAttr(attr::Kind AK) const;
2307
2308 /// Get the base element type of this type, potentially discarding type
2309 /// qualifiers. This should never be used when type qualifiers
2310 /// are meaningful.
2311 const Type *getBaseElementTypeUnsafe() const;
2312
2313 /// If this is an array type, return the element type of the array,
2314 /// potentially with type qualifiers missing.
2315 /// This should never be used when type qualifiers are meaningful.
2316 const Type *getArrayElementTypeNoTypeQual() const;
2317
2318 /// If this is a pointer type, return the pointee type.
2319 /// If this is an array type, return the array element type.
2320 /// This should never be used when type qualifiers are meaningful.
2321 const Type *getPointeeOrArrayElementType() const;
2322
2323 /// If this is a pointer, ObjC object pointer, or block
2324 /// pointer, this returns the respective pointee.
2325 QualType getPointeeType() const;
2326
2327 /// Return the specified type with any "sugar" removed from the type,
2328 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2329 const Type *getUnqualifiedDesugaredType() const;
2330
2331 /// More type predicates useful for type checking/promotion
2332 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2333
2334 /// Return true if this is an integer type that is
2335 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2336 /// or an enum decl which has a signed representation.
2337 bool isSignedIntegerType() const;
2338
2339 /// Return true if this is an integer type that is
2340 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2341 /// or an enum decl which has an unsigned representation.
2342 bool isUnsignedIntegerType() const;
2343
2344 /// Determines whether this is an integer type that is signed or an
2345 /// enumeration types whose underlying type is a signed integer type.
2346 bool isSignedIntegerOrEnumerationType() const;
2347
2348 /// Determines whether this is an integer type that is unsigned or an
2349 /// enumeration types whose underlying type is a unsigned integer type.
2350 bool isUnsignedIntegerOrEnumerationType() const;
2351
2352 /// Return true if this is a fixed point type according to
2353 /// ISO/IEC JTC1 SC22 WG14 N1169.
2354 bool isFixedPointType() const;
2355
2356 /// Return true if this is a fixed point or integer type.
2357 bool isFixedPointOrIntegerType() const;
2358
2359 /// Return true if this is a saturated fixed point type according to
2360 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2361 bool isSaturatedFixedPointType() const;
2362
2363 /// Return true if this is a saturated fixed point type according to
2364 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2365 bool isUnsaturatedFixedPointType() const;
2366
2367 /// Return true if this is a fixed point type that is signed according
2368 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2369 bool isSignedFixedPointType() const;
2370
2371 /// Return true if this is a fixed point type that is unsigned according
2372 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2373 bool isUnsignedFixedPointType() const;
2374
2375 /// Return true if this is not a variable sized type,
2376 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2377 /// incomplete types.
2378 bool isConstantSizeType() const;
2379
2380 /// Returns true if this type can be represented by some
2381 /// set of type specifiers.
2382 bool isSpecifierType() const;
2383
2384 /// Determine the linkage of this type.
2385 Linkage getLinkage() const;
2386
2387 /// Determine the visibility of this type.
2388 Visibility getVisibility() const {
2389 return getLinkageAndVisibility().getVisibility();
2390 }
2391
2392 /// Return true if the visibility was explicitly set is the code.
2393 bool isVisibilityExplicit() const {
2394 return getLinkageAndVisibility().isVisibilityExplicit();
2395 }
2396
2397 /// Determine the linkage and visibility of this type.
2398 LinkageInfo getLinkageAndVisibility() const;
2399
2400 /// True if the computed linkage is valid. Used for consistency
2401 /// checking. Should always return true.
2402 bool isLinkageValid() const;
2403
2404 /// Determine the nullability of the given type.
2405 ///
2406 /// Note that nullability is only captured as sugar within the type
2407 /// system, not as part of the canonical type, so nullability will
2408 /// be lost by canonicalization and desugaring.
2409 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2410
2411 /// Determine whether the given type can have a nullability
2412 /// specifier applied to it, i.e., if it is any kind of pointer type.
2413 ///
2414 /// \param ResultIfUnknown The value to return if we don't yet know whether
2415 /// this type can have nullability because it is dependent.
2416 bool canHaveNullability(bool ResultIfUnknown = true) const;
2417
2418 /// Retrieve the set of substitutions required when accessing a member
2419 /// of the Objective-C receiver type that is declared in the given context.
2420 ///
2421 /// \c *this is the type of the object we're operating on, e.g., the
2422 /// receiver for a message send or the base of a property access, and is
2423 /// expected to be of some object or object pointer type.
2424 ///
2425 /// \param dc The declaration context for which we are building up a
2426 /// substitution mapping, which should be an Objective-C class, extension,
2427 /// category, or method within.
2428 ///
2429 /// \returns an array of type arguments that can be substituted for
2430 /// the type parameters of the given declaration context in any type described
2431 /// within that context, or an empty optional to indicate that no
2432 /// substitution is required.
2433 Optional<ArrayRef<QualType>>
2434 getObjCSubstitutions(const DeclContext *dc) const;
2435
2436 /// Determines if this is an ObjC interface type that may accept type
2437 /// parameters.
2438 bool acceptsObjCTypeParams() const;
2439
2440 const char *getTypeClassName() const;
2441
2442 QualType getCanonicalTypeInternal() const {
2443 return CanonicalType;
2444 }
2445
2446 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2447 void dump() const;
2448 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2449};
2450
2451/// This will check for a TypedefType by removing any existing sugar
2452/// until it reaches a TypedefType or a non-sugared type.
2453template <> const TypedefType *Type::getAs() const;
2454
2455/// This will check for a TemplateSpecializationType by removing any
2456/// existing sugar until it reaches a TemplateSpecializationType or a
2457/// non-sugared type.
2458template <> const TemplateSpecializationType *Type::getAs() const;
2459
2460/// This will check for an AttributedType by removing any existing sugar
2461/// until it reaches an AttributedType or a non-sugared type.
2462template <> const AttributedType *Type::getAs() const;
2463
2464// We can do canonical leaf types faster, because we don't have to
2465// worry about preserving child type decoration.
2466#define TYPE(Class, Base)
2467#define LEAF_TYPE(Class) \
2468template <> inline const Class##Type *Type::getAs() const { \
2469 return dyn_cast<Class##Type>(CanonicalType); \
2470} \
2471template <> inline const Class##Type *Type::castAs() const { \
2472 return cast<Class##Type>(CanonicalType); \
2473}
2474#include "clang/AST/TypeNodes.inc"
2475
2476/// This class is used for builtin types like 'int'. Builtin
2477/// types are always canonical and have a literal name field.
2478class BuiltinType : public Type {
2479public:
2480 enum Kind {
2481// OpenCL image types
2482#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2483#include "clang/Basic/OpenCLImageTypes.def"
2484// OpenCL extension types
2485#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2486#include "clang/Basic/OpenCLExtensionTypes.def"
2487// SVE Types
2488#define SVE_TYPE(Name, Id, SingletonId) Id,
2489#include "clang/Basic/AArch64SVEACLETypes.def"
2490// All other builtin types
2491#define BUILTIN_TYPE(Id, SingletonId) Id,
2492#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2493#include "clang/AST/BuiltinTypes.def"
2494 };
2495
2496private:
2497 friend class ASTContext; // ASTContext creates these.
2498
2499 BuiltinType(Kind K)
2500 : Type(Builtin, QualType(),
2501 K == Dependent ? TypeDependence::DependentInstantiation
2502 : TypeDependence::None) {
2503 BuiltinTypeBits.Kind = K;
2504 }
2505
2506public:
2507 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2508 StringRef getName(const PrintingPolicy &Policy) const;
2509
2510 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2511 // The StringRef is null-terminated.
2512 StringRef str = getName(Policy);
2513 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 2513, __PRETTY_FUNCTION__))
;
2514 return str.data();
2515 }
2516
2517 bool isSugared() const { return false; }
2518 QualType desugar() const { return QualType(this, 0); }
2519
2520 bool isInteger() const {
2521 return getKind() >= Bool && getKind() <= Int128;
2522 }
2523
2524 bool isSignedInteger() const {
2525 return getKind() >= Char_S && getKind() <= Int128;
2526 }
2527
2528 bool isUnsignedInteger() const {
2529 return getKind() >= Bool && getKind() <= UInt128;
2530 }
2531
2532 bool isFloatingPoint() const {
2533 return getKind() >= Half && getKind() <= Float128;
2534 }
2535
2536 /// Determines whether the given kind corresponds to a placeholder type.
2537 static bool isPlaceholderTypeKind(Kind K) {
2538 return K >= Overload;
2539 }
2540
2541 /// Determines whether this type is a placeholder type, i.e. a type
2542 /// which cannot appear in arbitrary positions in a fully-formed
2543 /// expression.
2544 bool isPlaceholderType() const {
2545 return isPlaceholderTypeKind(getKind());
2546 }
2547
2548 /// Determines whether this type is a placeholder type other than
2549 /// Overload. Most placeholder types require only syntactic
2550 /// information about their context in order to be resolved (e.g.
2551 /// whether it is a call expression), which means they can (and
2552 /// should) be resolved in an earlier "phase" of analysis.
2553 /// Overload expressions sometimes pick up further information
2554 /// from their context, like whether the context expects a
2555 /// specific function-pointer type, and so frequently need
2556 /// special treatment.
2557 bool isNonOverloadPlaceholderType() const {
2558 return getKind() > Overload;
2559 }
2560
2561 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2562};
2563
2564/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2565/// types (_Complex float etc) as well as the GCC integer complex extensions.
2566class ComplexType : public Type, public llvm::FoldingSetNode {
2567 friend class ASTContext; // ASTContext creates these.
2568
2569 QualType ElementType;
2570
2571 ComplexType(QualType Element, QualType CanonicalPtr)
2572 : Type(Complex, CanonicalPtr, Element->getDependence()),
2573 ElementType(Element) {}
2574
2575public:
2576 QualType getElementType() const { return ElementType; }
2577
2578 bool isSugared() const { return false; }
2579 QualType desugar() const { return QualType(this, 0); }
2580
2581 void Profile(llvm::FoldingSetNodeID &ID) {
2582 Profile(ID, getElementType());
2583 }
2584
2585 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2586 ID.AddPointer(Element.getAsOpaquePtr());
2587 }
2588
2589 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2590};
2591
2592/// Sugar for parentheses used when specifying types.
2593class ParenType : public Type, public llvm::FoldingSetNode {
2594 friend class ASTContext; // ASTContext creates these.
2595
2596 QualType Inner;
2597
2598 ParenType(QualType InnerType, QualType CanonType)
2599 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2600
2601public:
2602 QualType getInnerType() const { return Inner; }
2603
2604 bool isSugared() const { return true; }
2605 QualType desugar() const { return getInnerType(); }
2606
2607 void Profile(llvm::FoldingSetNodeID &ID) {
2608 Profile(ID, getInnerType());
2609 }
2610
2611 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2612 Inner.Profile(ID);
2613 }
2614
2615 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2616};
2617
2618/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2619class PointerType : public Type, public llvm::FoldingSetNode {
2620 friend class ASTContext; // ASTContext creates these.
2621
2622 QualType PointeeType;
2623
2624 PointerType(QualType Pointee, QualType CanonicalPtr)
2625 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2626 PointeeType(Pointee) {}
2627
2628public:
2629 QualType getPointeeType() const { return PointeeType; }
2630
2631 bool isSugared() const { return false; }
2632 QualType desugar() const { return QualType(this, 0); }
2633
2634 void Profile(llvm::FoldingSetNodeID &ID) {
2635 Profile(ID, getPointeeType());
2636 }
2637
2638 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2639 ID.AddPointer(Pointee.getAsOpaquePtr());
2640 }
2641
2642 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2643};
2644
2645/// Represents a type which was implicitly adjusted by the semantic
2646/// engine for arbitrary reasons. For example, array and function types can
2647/// decay, and function types can have their calling conventions adjusted.
2648class AdjustedType : public Type, public llvm::FoldingSetNode {
2649 QualType OriginalTy;
2650 QualType AdjustedTy;
2651
2652protected:
2653 friend class ASTContext; // ASTContext creates these.
2654
2655 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2656 QualType CanonicalPtr)
2657 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2658 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2659
2660public:
2661 QualType getOriginalType() const { return OriginalTy; }
2662 QualType getAdjustedType() const { return AdjustedTy; }
2663
2664 bool isSugared() const { return true; }
2665 QualType desugar() const { return AdjustedTy; }
2666
2667 void Profile(llvm::FoldingSetNodeID &ID) {
2668 Profile(ID, OriginalTy, AdjustedTy);
2669 }
2670
2671 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2672 ID.AddPointer(Orig.getAsOpaquePtr());
2673 ID.AddPointer(New.getAsOpaquePtr());
2674 }
2675
2676 static bool classof(const Type *T) {
2677 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2678 }
2679};
2680
2681/// Represents a pointer type decayed from an array or function type.
2682class DecayedType : public AdjustedType {
2683 friend class ASTContext; // ASTContext creates these.
2684
2685 inline
2686 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2687
2688public:
2689 QualType getDecayedType() const { return getAdjustedType(); }
2690
2691 inline QualType getPointeeType() const;
2692
2693 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2694};
2695
2696/// Pointer to a block type.
2697/// This type is to represent types syntactically represented as
2698/// "void (^)(int)", etc. Pointee is required to always be a function type.
2699class BlockPointerType : public Type, public llvm::FoldingSetNode {
2700 friend class ASTContext; // ASTContext creates these.
2701
2702 // Block is some kind of pointer type
2703 QualType PointeeType;
2704
2705 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2706 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2707 PointeeType(Pointee) {}
2708
2709public:
2710 // Get the pointee type. Pointee is required to always be a function type.
2711 QualType getPointeeType() const { return PointeeType; }
2712
2713 bool isSugared() const { return false; }
2714 QualType desugar() const { return QualType(this, 0); }
2715
2716 void Profile(llvm::FoldingSetNodeID &ID) {
2717 Profile(ID, getPointeeType());
2718 }
2719
2720 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2721 ID.AddPointer(Pointee.getAsOpaquePtr());
2722 }
2723
2724 static bool classof(const Type *T) {
2725 return T->getTypeClass() == BlockPointer;
2726 }
2727};
2728
2729/// Base for LValueReferenceType and RValueReferenceType
2730class ReferenceType : public Type, public llvm::FoldingSetNode {
2731 QualType PointeeType;
2732
2733protected:
2734 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2735 bool SpelledAsLValue)
2736 : Type(tc, CanonicalRef, Referencee->getDependence()),
2737 PointeeType(Referencee) {
2738 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2739 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2740 }
2741
2742public:
2743 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2744 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2745
2746 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2747
2748 QualType getPointeeType() const {
2749 // FIXME: this might strip inner qualifiers; okay?
2750 const ReferenceType *T = this;
2751 while (T->isInnerRef())
2752 T = T->PointeeType->castAs<ReferenceType>();
2753 return T->PointeeType;
2754 }
2755
2756 void Profile(llvm::FoldingSetNodeID &ID) {
2757 Profile(ID, PointeeType, isSpelledAsLValue());
2758 }
2759
2760 static void Profile(llvm::FoldingSetNodeID &ID,
2761 QualType Referencee,
2762 bool SpelledAsLValue) {
2763 ID.AddPointer(Referencee.getAsOpaquePtr());
2764 ID.AddBoolean(SpelledAsLValue);
2765 }
2766
2767 static bool classof(const Type *T) {
2768 return T->getTypeClass() == LValueReference ||
2769 T->getTypeClass() == RValueReference;
2770 }
2771};
2772
2773/// An lvalue reference type, per C++11 [dcl.ref].
2774class LValueReferenceType : public ReferenceType {
2775 friend class ASTContext; // ASTContext creates these
2776
2777 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2778 bool SpelledAsLValue)
2779 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2780 SpelledAsLValue) {}
2781
2782public:
2783 bool isSugared() const { return false; }
2784 QualType desugar() const { return QualType(this, 0); }
2785
2786 static bool classof(const Type *T) {
2787 return T->getTypeClass() == LValueReference;
2788 }
2789};
2790
2791/// An rvalue reference type, per C++11 [dcl.ref].
2792class RValueReferenceType : public ReferenceType {
2793 friend class ASTContext; // ASTContext creates these
2794
2795 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2796 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2797
2798public:
2799 bool isSugared() const { return false; }
2800 QualType desugar() const { return QualType(this, 0); }
2801
2802 static bool classof(const Type *T) {
2803 return T->getTypeClass() == RValueReference;
2804 }
2805};
2806
2807/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2808///
2809/// This includes both pointers to data members and pointer to member functions.
2810class MemberPointerType : public Type, public llvm::FoldingSetNode {
2811 friend class ASTContext; // ASTContext creates these.
2812
2813 QualType PointeeType;
2814
2815 /// The class of which the pointee is a member. Must ultimately be a
2816 /// RecordType, but could be a typedef or a template parameter too.
2817 const Type *Class;
2818
2819 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2820 : Type(MemberPointer, CanonicalPtr,
2821 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2822 Pointee->getDependence()),
2823 PointeeType(Pointee), Class(Cls) {}
2824
2825public:
2826 QualType getPointeeType() const { return PointeeType; }
2827
2828 /// Returns true if the member type (i.e. the pointee type) is a
2829 /// function type rather than a data-member type.
2830 bool isMemberFunctionPointer() const {
2831 return PointeeType->isFunctionProtoType();
2832 }
2833
2834 /// Returns true if the member type (i.e. the pointee type) is a
2835 /// data type rather than a function type.
2836 bool isMemberDataPointer() const {
2837 return !PointeeType->isFunctionProtoType();
2838 }
2839
2840 const Type *getClass() const { return Class; }
2841 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2842
2843 bool isSugared() const { return false; }
2844 QualType desugar() const { return QualType(this, 0); }
2845
2846 void Profile(llvm::FoldingSetNodeID &ID) {
2847 Profile(ID, getPointeeType(), getClass());
2848 }
2849
2850 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2851 const Type *Class) {
2852 ID.AddPointer(Pointee.getAsOpaquePtr());
2853 ID.AddPointer(Class);
2854 }
2855
2856 static bool classof(const Type *T) {
2857 return T->getTypeClass() == MemberPointer;
2858 }
2859};
2860
2861/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2862class ArrayType : public Type, public llvm::FoldingSetNode {
2863public:
2864 /// Capture whether this is a normal array (e.g. int X[4])
2865 /// an array with a static size (e.g. int X[static 4]), or an array
2866 /// with a star size (e.g. int X[*]).
2867 /// 'static' is only allowed on function parameters.
2868 enum ArraySizeModifier {
2869 Normal, Static, Star
2870 };
2871
2872private:
2873 /// The element type of the array.
2874 QualType ElementType;
2875
2876protected:
2877 friend class ASTContext; // ASTContext creates these.
2878
2879 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2880 unsigned tq, const Expr *sz = nullptr);
2881
2882public:
2883 QualType getElementType() const { return ElementType; }
2884
2885 ArraySizeModifier getSizeModifier() const {
2886 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2887 }
2888
2889 Qualifiers getIndexTypeQualifiers() const {
2890 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2891 }
2892
2893 unsigned getIndexTypeCVRQualifiers() const {
2894 return ArrayTypeBits.IndexTypeQuals;
2895 }
2896
2897 static bool classof(const Type *T) {
2898 return T->getTypeClass() == ConstantArray ||
2899 T->getTypeClass() == VariableArray ||
2900 T->getTypeClass() == IncompleteArray ||
2901 T->getTypeClass() == DependentSizedArray;
2902 }
2903};
2904
2905/// Represents the canonical version of C arrays with a specified constant size.
2906/// For example, the canonical type for 'int A[4 + 4*100]' is a
2907/// ConstantArrayType where the element type is 'int' and the size is 404.
2908class ConstantArrayType final
2909 : public ArrayType,
2910 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2911 friend class ASTContext; // ASTContext creates these.
2912 friend TrailingObjects;
2913
2914 llvm::APInt Size; // Allows us to unique the type.
2915
2916 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2917 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2918 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2919 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2920 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2921 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 2921, __PRETTY_FUNCTION__))
;
2922 *getTrailingObjects<const Expr*>() = sz;
2923 }
2924 }
2925
2926 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2927 return ConstantArrayTypeBits.HasStoredSizeExpr;
2928 }
2929
2930public:
2931 const llvm::APInt &getSize() const { return Size; }
2932 const Expr *getSizeExpr() const {
2933 return ConstantArrayTypeBits.HasStoredSizeExpr
2934 ? *getTrailingObjects<const Expr *>()
2935 : nullptr;
2936 }
2937 bool isSugared() const { return false; }
2938 QualType desugar() const { return QualType(this, 0); }
2939
2940 /// Determine the number of bits required to address a member of
2941 // an array with the given element type and number of elements.
2942 static unsigned getNumAddressingBits(const ASTContext &Context,
2943 QualType ElementType,
2944 const llvm::APInt &NumElements);
2945
2946 /// Determine the maximum number of active bits that an array's size
2947 /// can require, which limits the maximum size of the array.
2948 static unsigned getMaxSizeBits(const ASTContext &Context);
2949
2950 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2951 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2952 getSizeModifier(), getIndexTypeCVRQualifiers());
2953 }
2954
2955 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2956 QualType ET, const llvm::APInt &ArraySize,
2957 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2958 unsigned TypeQuals);
2959
2960 static bool classof(const Type *T) {
2961 return T->getTypeClass() == ConstantArray;
2962 }
2963};
2964
2965/// Represents a C array with an unspecified size. For example 'int A[]' has
2966/// an IncompleteArrayType where the element type is 'int' and the size is
2967/// unspecified.
2968class IncompleteArrayType : public ArrayType {
2969 friend class ASTContext; // ASTContext creates these.
2970
2971 IncompleteArrayType(QualType et, QualType can,
2972 ArraySizeModifier sm, unsigned tq)
2973 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2974
2975public:
2976 friend class StmtIteratorBase;
2977
2978 bool isSugared() const { return false; }
2979 QualType desugar() const { return QualType(this, 0); }
2980
2981 static bool classof(const Type *T) {
2982 return T->getTypeClass() == IncompleteArray;
2983 }
2984
2985 void Profile(llvm::FoldingSetNodeID &ID) {
2986 Profile(ID, getElementType(), getSizeModifier(),
2987 getIndexTypeCVRQualifiers());
2988 }
2989
2990 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2991 ArraySizeModifier SizeMod, unsigned TypeQuals) {
2992 ID.AddPointer(ET.getAsOpaquePtr());
2993 ID.AddInteger(SizeMod);
2994 ID.AddInteger(TypeQuals);
2995 }
2996};
2997
2998/// Represents a C array with a specified size that is not an
2999/// integer-constant-expression. For example, 'int s[x+foo()]'.
3000/// Since the size expression is an arbitrary expression, we store it as such.
3001///
3002/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3003/// should not be: two lexically equivalent variable array types could mean
3004/// different things, for example, these variables do not have the same type
3005/// dynamically:
3006///
3007/// void foo(int x) {
3008/// int Y[x];
3009/// ++x;
3010/// int Z[x];
3011/// }
3012class VariableArrayType : public ArrayType {
3013 friend class ASTContext; // ASTContext creates these.
3014
3015 /// An assignment-expression. VLA's are only permitted within
3016 /// a function block.
3017 Stmt *SizeExpr;
3018
3019 /// The range spanned by the left and right array brackets.
3020 SourceRange Brackets;
3021
3022 VariableArrayType(QualType et, QualType can, Expr *e,
3023 ArraySizeModifier sm, unsigned tq,
3024 SourceRange brackets)
3025 : ArrayType(VariableArray, et, can, sm, tq, e),
3026 SizeExpr((Stmt*) e), Brackets(brackets) {}
3027
3028public:
3029 friend class StmtIteratorBase;
3030
3031 Expr *getSizeExpr() const {
3032 // We use C-style casts instead of cast<> here because we do not wish
3033 // to have a dependency of Type.h on Stmt.h/Expr.h.
3034 return (Expr*) SizeExpr;
3035 }
3036
3037 SourceRange getBracketsRange() const { return Brackets; }
3038 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3039 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3040
3041 bool isSugared() const { return false; }
3042 QualType desugar() const { return QualType(this, 0); }
3043
3044 static bool classof(const Type *T) {
3045 return T->getTypeClass() == VariableArray;
3046 }
3047
3048 void Profile(llvm::FoldingSetNodeID &ID) {
3049 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 3049)
;
3050 }
3051};
3052
3053/// Represents an array type in C++ whose size is a value-dependent expression.
3054///
3055/// For example:
3056/// \code
3057/// template<typename T, int Size>
3058/// class array {
3059/// T data[Size];
3060/// };
3061/// \endcode
3062///
3063/// For these types, we won't actually know what the array bound is
3064/// until template instantiation occurs, at which point this will
3065/// become either a ConstantArrayType or a VariableArrayType.
3066class DependentSizedArrayType : public ArrayType {
3067 friend class ASTContext; // ASTContext creates these.
3068
3069 const ASTContext &Context;
3070
3071 /// An assignment expression that will instantiate to the
3072 /// size of the array.
3073 ///
3074 /// The expression itself might be null, in which case the array
3075 /// type will have its size deduced from an initializer.
3076 Stmt *SizeExpr;
3077
3078 /// The range spanned by the left and right array brackets.
3079 SourceRange Brackets;
3080
3081 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3082 Expr *e, ArraySizeModifier sm, unsigned tq,
3083 SourceRange brackets);
3084
3085public:
3086 friend class StmtIteratorBase;
3087
3088 Expr *getSizeExpr() const {
3089 // We use C-style casts instead of cast<> here because we do not wish
3090 // to have a dependency of Type.h on Stmt.h/Expr.h.
3091 return (Expr*) SizeExpr;
3092 }
3093
3094 SourceRange getBracketsRange() const { return Brackets; }
3095 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3096 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3097
3098 bool isSugared() const { return false; }
3099 QualType desugar() const { return QualType(this, 0); }
3100
3101 static bool classof(const Type *T) {
3102 return T->getTypeClass() == DependentSizedArray;
3103 }
3104
3105 void Profile(llvm::FoldingSetNodeID &ID) {
3106 Profile(ID, Context, getElementType(),
3107 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3108 }
3109
3110 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3111 QualType ET, ArraySizeModifier SizeMod,
3112 unsigned TypeQuals, Expr *E);
3113};
3114
3115/// Represents an extended address space qualifier where the input address space
3116/// value is dependent. Non-dependent address spaces are not represented with a
3117/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3118///
3119/// For example:
3120/// \code
3121/// template<typename T, int AddrSpace>
3122/// class AddressSpace {
3123/// typedef T __attribute__((address_space(AddrSpace))) type;
3124/// }
3125/// \endcode
3126class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3127 friend class ASTContext;
3128
3129 const ASTContext &Context;
3130 Expr *AddrSpaceExpr;
3131 QualType PointeeType;
3132 SourceLocation loc;
3133
3134 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3135 QualType can, Expr *AddrSpaceExpr,
3136 SourceLocation loc);
3137
3138public:
3139 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3140 QualType getPointeeType() const { return PointeeType; }
3141 SourceLocation getAttributeLoc() const { return loc; }
3142
3143 bool isSugared() const { return false; }
3144 QualType desugar() const { return QualType(this, 0); }
3145
3146 static bool classof(const Type *T) {
3147 return T->getTypeClass() == DependentAddressSpace;
3148 }
3149
3150 void Profile(llvm::FoldingSetNodeID &ID) {
3151 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3152 }
3153
3154 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3155 QualType PointeeType, Expr *AddrSpaceExpr);
3156};
3157
3158/// Represents an extended vector type where either the type or size is
3159/// dependent.
3160///
3161/// For example:
3162/// \code
3163/// template<typename T, int Size>
3164/// class vector {
3165/// typedef T __attribute__((ext_vector_type(Size))) type;
3166/// }
3167/// \endcode
3168class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3169 friend class ASTContext;
3170
3171 const ASTContext &Context;
3172 Expr *SizeExpr;
3173
3174 /// The element type of the array.
3175 QualType ElementType;
3176
3177 SourceLocation loc;
3178
3179 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3180 QualType can, Expr *SizeExpr, SourceLocation loc);
3181
3182public:
3183 Expr *getSizeExpr() const { return SizeExpr; }
3184 QualType getElementType() const { return ElementType; }
3185 SourceLocation getAttributeLoc() const { return loc; }
3186
3187 bool isSugared() const { return false; }
3188 QualType desugar() const { return QualType(this, 0); }
3189
3190 static bool classof(const Type *T) {
3191 return T->getTypeClass() == DependentSizedExtVector;
3192 }
3193
3194 void Profile(llvm::FoldingSetNodeID &ID) {
3195 Profile(ID, Context, getElementType(), getSizeExpr());
3196 }
3197
3198 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3199 QualType ElementType, Expr *SizeExpr);
3200};
3201
3202
3203/// Represents a GCC generic vector type. This type is created using
3204/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3205/// bytes; or from an Altivec __vector or vector declaration.
3206/// Since the constructor takes the number of vector elements, the
3207/// client is responsible for converting the size into the number of elements.
3208class VectorType : public Type, public llvm::FoldingSetNode {
3209public:
3210 enum VectorKind {
3211 /// not a target-specific vector type
3212 GenericVector,
3213
3214 /// is AltiVec vector
3215 AltiVecVector,
3216
3217 /// is AltiVec 'vector Pixel'
3218 AltiVecPixel,
3219
3220 /// is AltiVec 'vector bool ...'
3221 AltiVecBool,
3222
3223 /// is ARM Neon vector
3224 NeonVector,
3225
3226 /// is ARM Neon polynomial vector
3227 NeonPolyVector,
3228
3229 /// is AArch64 SVE fixed-length data vector
3230 SveFixedLengthDataVector,
3231
3232 /// is AArch64 SVE fixed-length predicate vector
3233 SveFixedLengthPredicateVector
3234 };
3235
3236protected:
3237 friend class ASTContext; // ASTContext creates these.
3238
3239 /// The element type of the vector.
3240 QualType ElementType;
3241
3242 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3243 VectorKind vecKind);
3244
3245 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3246 QualType canonType, VectorKind vecKind);
3247
3248public:
3249 QualType getElementType() const { return ElementType; }
3250 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3251
3252 bool isSugared() const { return false; }
3253 QualType desugar() const { return QualType(this, 0); }
3254
3255 VectorKind getVectorKind() const {
3256 return VectorKind(VectorTypeBits.VecKind);
3257 }
3258
3259 void Profile(llvm::FoldingSetNodeID &ID) {
3260 Profile(ID, getElementType(), getNumElements(),
3261 getTypeClass(), getVectorKind());
3262 }
3263
3264 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3265 unsigned NumElements, TypeClass TypeClass,
3266 VectorKind VecKind) {
3267 ID.AddPointer(ElementType.getAsOpaquePtr());
3268 ID.AddInteger(NumElements);
3269 ID.AddInteger(TypeClass);
3270 ID.AddInteger(VecKind);
3271 }
3272
3273 static bool classof(const Type *T) {
3274 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3275 }
3276};
3277
3278/// Represents a vector type where either the type or size is dependent.
3279////
3280/// For example:
3281/// \code
3282/// template<typename T, int Size>
3283/// class vector {
3284/// typedef T __attribute__((vector_size(Size))) type;
3285/// }
3286/// \endcode
3287class DependentVectorType : public Type, public llvm::FoldingSetNode {
3288 friend class ASTContext;
3289
3290 const ASTContext &Context;
3291 QualType ElementType;
3292 Expr *SizeExpr;
3293 SourceLocation Loc;
3294
3295 DependentVectorType(const ASTContext &Context, QualType ElementType,
3296 QualType CanonType, Expr *SizeExpr,
3297 SourceLocation Loc, VectorType::VectorKind vecKind);
3298
3299public:
3300 Expr *getSizeExpr() const { return SizeExpr; }
3301 QualType getElementType() const { return ElementType; }
3302 SourceLocation getAttributeLoc() const { return Loc; }
3303 VectorType::VectorKind getVectorKind() const {
3304 return VectorType::VectorKind(VectorTypeBits.VecKind);
3305 }
3306
3307 bool isSugared() const { return false; }
3308 QualType desugar() const { return QualType(this, 0); }
3309
3310 static bool classof(const Type *T) {
3311 return T->getTypeClass() == DependentVector;
3312 }
3313
3314 void Profile(llvm::FoldingSetNodeID &ID) {
3315 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3316 }
3317
3318 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3319 QualType ElementType, const Expr *SizeExpr,
3320 VectorType::VectorKind VecKind);
3321};
3322
3323/// ExtVectorType - Extended vector type. This type is created using
3324/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3325/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3326/// class enables syntactic extensions, like Vector Components for accessing
3327/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3328/// Shading Language).
3329class ExtVectorType : public VectorType {
3330 friend class ASTContext; // ASTContext creates these.
3331
3332 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3333 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3334
3335public:
3336 static int getPointAccessorIdx(char c) {
3337 switch (c) {
3338 default: return -1;
3339 case 'x': case 'r': return 0;
3340 case 'y': case 'g': return 1;
3341 case 'z': case 'b': return 2;
3342 case 'w': case 'a': return 3;
3343 }
3344 }
3345
3346 static int getNumericAccessorIdx(char c) {
3347 switch (c) {
3348 default: return -1;
3349 case '0': return 0;
3350 case '1': return 1;
3351 case '2': return 2;
3352 case '3': return 3;
3353 case '4': return 4;
3354 case '5': return 5;
3355 case '6': return 6;
3356 case '7': return 7;
3357 case '8': return 8;
3358 case '9': return 9;
3359 case 'A':
3360 case 'a': return 10;
3361 case 'B':
3362 case 'b': return 11;
3363 case 'C':
3364 case 'c': return 12;
3365 case 'D':
3366 case 'd': return 13;
3367 case 'E':
3368 case 'e': return 14;
3369 case 'F':
3370 case 'f': return 15;
3371 }
3372 }
3373
3374 static int getAccessorIdx(char c, bool isNumericAccessor) {
3375 if (isNumericAccessor)
3376 return getNumericAccessorIdx(c);
3377 else
3378 return getPointAccessorIdx(c);
3379 }
3380
3381 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3382 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3383 return unsigned(idx-1) < getNumElements();
3384 return false;
3385 }
3386
3387 bool isSugared() const { return false; }
3388 QualType desugar() const { return QualType(this, 0); }
3389
3390 static bool classof(const Type *T) {
3391 return T->getTypeClass() == ExtVector;
3392 }
3393};
3394
3395/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3396/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3397/// number of rows and "columns" specifies the number of columns.
3398class MatrixType : public Type, public llvm::FoldingSetNode {
3399protected:
3400 friend class ASTContext;
3401
3402 /// The element type of the matrix.
3403 QualType ElementType;
3404
3405 MatrixType(QualType ElementTy, QualType CanonElementTy);
3406
3407 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3408 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3409
3410public:
3411 /// Returns type of the elements being stored in the matrix
3412 QualType getElementType() const { return ElementType; }
3413
3414 /// Valid elements types are the following:
3415 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3416 /// and _Bool
3417 /// * the standard floating types float or double
3418 /// * a half-precision floating point type, if one is supported on the target
3419 static bool isValidElementType(QualType T) {
3420 return T->isDependentType() ||
3421 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3422 }
3423
3424 bool isSugared() const { return false; }
3425 QualType desugar() const { return QualType(this, 0); }
3426
3427 static bool classof(const Type *T) {
3428 return T->getTypeClass() == ConstantMatrix ||
3429 T->getTypeClass() == DependentSizedMatrix;
3430 }
3431};
3432
3433/// Represents a concrete matrix type with constant number of rows and columns
3434class ConstantMatrixType final : public MatrixType {
3435protected:
3436 friend class ASTContext;
3437
3438 /// The element type of the matrix.
3439 // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3440 QualType ElementType;
3441
3442 /// Number of rows and columns.
3443 unsigned NumRows;
3444 unsigned NumColumns;
3445
3446 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3447
3448 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3449 unsigned NColumns, QualType CanonElementType);
3450
3451 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3452 unsigned NColumns, QualType CanonElementType);
3453
3454public:
3455 /// Returns the number of rows in the matrix.
3456 unsigned getNumRows() const { return NumRows; }
3457
3458 /// Returns the number of columns in the matrix.
3459 unsigned getNumColumns() const { return NumColumns; }
3460
3461 /// Returns the number of elements required to embed the matrix into a vector.
3462 unsigned getNumElementsFlattened() const {
3463 return getNumRows() * getNumColumns();
3464 }
3465
3466 /// Returns true if \p NumElements is a valid matrix dimension.
3467 static constexpr bool isDimensionValid(size_t NumElements) {
3468 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3469 }
3470
3471 /// Returns the maximum number of elements per dimension.
3472 static constexpr unsigned getMaxElementsPerDimension() {
3473 return MaxElementsPerDimension;
3474 }
3475
3476 void Profile(llvm::FoldingSetNodeID &ID) {
3477 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3478 getTypeClass());
3479 }
3480
3481 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3482 unsigned NumRows, unsigned NumColumns,
3483 TypeClass TypeClass) {
3484 ID.AddPointer(ElementType.getAsOpaquePtr());
3485 ID.AddInteger(NumRows);
3486 ID.AddInteger(NumColumns);
3487 ID.AddInteger(TypeClass);
3488 }
3489
3490 static bool classof(const Type *T) {
3491 return T->getTypeClass() == ConstantMatrix;
3492 }
3493};
3494
3495/// Represents a matrix type where the type and the number of rows and columns
3496/// is dependent on a template.
3497class DependentSizedMatrixType final : public MatrixType {
3498 friend class ASTContext;
3499
3500 const ASTContext &Context;
3501 Expr *RowExpr;
3502 Expr *ColumnExpr;
3503
3504 SourceLocation loc;
3505
3506 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3507 QualType CanonicalType, Expr *RowExpr,
3508 Expr *ColumnExpr, SourceLocation loc);
3509
3510public:
3511 QualType getElementType() const { return ElementType; }
3512 Expr *getRowExpr() const { return RowExpr; }
3513 Expr *getColumnExpr() const { return ColumnExpr; }
3514 SourceLocation getAttributeLoc() const { return loc; }
3515
3516 bool isSugared() const { return false; }
3517 QualType desugar() const { return QualType(this, 0); }
3518
3519 static bool classof(const Type *T) {
3520 return T->getTypeClass() == DependentSizedMatrix;
3521 }
3522
3523 void Profile(llvm::FoldingSetNodeID &ID) {
3524 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3525 }
3526
3527 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3528 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3529};
3530
3531/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3532/// class of FunctionNoProtoType and FunctionProtoType.
3533class FunctionType : public Type {
3534 // The type returned by the function.
3535 QualType ResultType;
3536
3537public:
3538 /// Interesting information about a specific parameter that can't simply
3539 /// be reflected in parameter's type. This is only used by FunctionProtoType
3540 /// but is in FunctionType to make this class available during the
3541 /// specification of the bases of FunctionProtoType.
3542 ///
3543 /// It makes sense to model language features this way when there's some
3544 /// sort of parameter-specific override (such as an attribute) that
3545 /// affects how the function is called. For example, the ARC ns_consumed
3546 /// attribute changes whether a parameter is passed at +0 (the default)
3547 /// or +1 (ns_consumed). This must be reflected in the function type,
3548 /// but isn't really a change to the parameter type.
3549 ///
3550 /// One serious disadvantage of modelling language features this way is
3551 /// that they generally do not work with language features that attempt
3552 /// to destructure types. For example, template argument deduction will
3553 /// not be able to match a parameter declared as
3554 /// T (*)(U)
3555 /// against an argument of type
3556 /// void (*)(__attribute__((ns_consumed)) id)
3557 /// because the substitution of T=void, U=id into the former will
3558 /// not produce the latter.
3559 class ExtParameterInfo {
3560 enum {
3561 ABIMask = 0x0F,
3562 IsConsumed = 0x10,
3563 HasPassObjSize = 0x20,
3564 IsNoEscape = 0x40,
3565 };
3566 unsigned char Data = 0;
3567
3568 public:
3569 ExtParameterInfo() = default;
3570
3571 /// Return the ABI treatment of this parameter.
3572 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3573 ExtParameterInfo withABI(ParameterABI kind) const {
3574 ExtParameterInfo copy = *this;
3575 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3576 return copy;
3577 }
3578
3579 /// Is this parameter considered "consumed" by Objective-C ARC?
3580 /// Consumed parameters must have retainable object type.
3581 bool isConsumed() const { return (Data & IsConsumed); }
3582 ExtParameterInfo withIsConsumed(bool consumed) const {
3583 ExtParameterInfo copy = *this;
3584 if (consumed)
3585 copy.Data |= IsConsumed;
3586 else
3587 copy.Data &= ~IsConsumed;
3588 return copy;
3589 }
3590
3591 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3592 ExtParameterInfo withHasPassObjectSize() const {
3593 ExtParameterInfo Copy = *this;
3594 Copy.Data |= HasPassObjSize;
3595 return Copy;
3596 }
3597
3598 bool isNoEscape() const { return Data & IsNoEscape; }
3599 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3600 ExtParameterInfo Copy = *this;
3601 if (NoEscape)
3602 Copy.Data |= IsNoEscape;
3603 else
3604 Copy.Data &= ~IsNoEscape;
3605 return Copy;
3606 }
3607
3608 unsigned char getOpaqueValue() const { return Data; }
3609 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3610 ExtParameterInfo result;
3611 result.Data = data;
3612 return result;
3613 }
3614
3615 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3616 return lhs.Data == rhs.Data;
3617 }
3618
3619 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3620 return lhs.Data != rhs.Data;
3621 }
3622 };
3623
3624 /// A class which abstracts out some details necessary for
3625 /// making a call.
3626 ///
3627 /// It is not actually used directly for storing this information in
3628 /// a FunctionType, although FunctionType does currently use the
3629 /// same bit-pattern.
3630 ///
3631 // If you add a field (say Foo), other than the obvious places (both,
3632 // constructors, compile failures), what you need to update is
3633 // * Operator==
3634 // * getFoo
3635 // * withFoo
3636 // * functionType. Add Foo, getFoo.
3637 // * ASTContext::getFooType
3638 // * ASTContext::mergeFunctionTypes
3639 // * FunctionNoProtoType::Profile
3640 // * FunctionProtoType::Profile
3641 // * TypePrinter::PrintFunctionProto
3642 // * AST read and write
3643 // * Codegen
3644 class ExtInfo {
3645 friend class FunctionType;
3646
3647 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3648 // adjust the Bits field below, and if you add bits, you'll need to adjust
3649 // Type::FunctionTypeBitfields::ExtInfo as well.
3650
3651 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3652 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3653 //
3654 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3655 enum { CallConvMask = 0x1F };
3656 enum { NoReturnMask = 0x20 };
3657 enum { ProducesResultMask = 0x40 };
3658 enum { NoCallerSavedRegsMask = 0x80 };
3659 enum {
3660 RegParmMask = 0x700,
3661 RegParmOffset = 8
3662 };
3663 enum { NoCfCheckMask = 0x800 };
3664 enum { CmseNSCallMask = 0x1000 };
3665 uint16_t Bits = CC_C;
3666
3667 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3668
3669 public:
3670 // Constructor with no defaults. Use this when you know that you
3671 // have all the elements (when reading an AST file for example).
3672 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3673 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3674 bool cmseNSCall) {
3675 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 3675, __PRETTY_FUNCTION__))
;
3676 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3677 (producesResult ? ProducesResultMask : 0) |
3678 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3679 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3680 (NoCfCheck ? NoCfCheckMask : 0) |
3681 (cmseNSCall ? CmseNSCallMask : 0);
3682 }
3683
3684 // Constructor with all defaults. Use when for example creating a
3685 // function known to use defaults.
3686 ExtInfo() = default;
3687
3688 // Constructor with just the calling convention, which is an important part
3689 // of the canonical type.
3690 ExtInfo(CallingConv CC) : Bits(CC) {}
3691
3692 bool getNoReturn() const { return Bits & NoReturnMask; }
3693 bool getProducesResult() const { return Bits & ProducesResultMask; }
3694 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3695 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3696 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3697 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3698
3699 unsigned getRegParm() const {
3700 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3701 if (RegParm > 0)
3702 --RegParm;
3703 return RegParm;
3704 }
3705
3706 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3707
3708 bool operator==(ExtInfo Other) const {
3709 return Bits == Other.Bits;
3710 }
3711 bool operator!=(ExtInfo Other) const {
3712 return Bits != Other.Bits;
3713 }
3714
3715 // Note that we don't have setters. That is by design, use
3716 // the following with methods instead of mutating these objects.
3717
3718 ExtInfo withNoReturn(bool noReturn) const {
3719 if (noReturn)
3720 return ExtInfo(Bits | NoReturnMask);
3721 else
3722 return ExtInfo(Bits & ~NoReturnMask);
3723 }
3724
3725 ExtInfo withProducesResult(bool producesResult) const {
3726 if (producesResult)
3727 return ExtInfo(Bits | ProducesResultMask);
3728 else
3729 return ExtInfo(Bits & ~ProducesResultMask);
3730 }
3731
3732 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3733 if (cmseNSCall)
3734 return ExtInfo(Bits | CmseNSCallMask);
3735 else
3736 return ExtInfo(Bits & ~CmseNSCallMask);
3737 }
3738
3739 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3740 if (noCallerSavedRegs)
3741 return ExtInfo(Bits | NoCallerSavedRegsMask);
3742 else
3743 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3744 }
3745
3746 ExtInfo withNoCfCheck(bool noCfCheck) const {
3747 if (noCfCheck)
3748 return ExtInfo(Bits | NoCfCheckMask);
3749 else
3750 return ExtInfo(Bits & ~NoCfCheckMask);
3751 }
3752
3753 ExtInfo withRegParm(unsigned RegParm) const {
3754 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 3754, __PRETTY_FUNCTION__))
;
3755 return ExtInfo((Bits & ~RegParmMask) |
3756 ((RegParm + 1) << RegParmOffset));
3757 }
3758
3759 ExtInfo withCallingConv(CallingConv cc) const {
3760 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3761 }
3762
3763 void Profile(llvm::FoldingSetNodeID &ID) const {
3764 ID.AddInteger(Bits);
3765 }
3766 };
3767
3768 /// A simple holder for a QualType representing a type in an
3769 /// exception specification. Unfortunately needed by FunctionProtoType
3770 /// because TrailingObjects cannot handle repeated types.
3771 struct ExceptionType { QualType Type; };
3772
3773 /// A simple holder for various uncommon bits which do not fit in
3774 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3775 /// alignment of subsequent objects in TrailingObjects. You must update
3776 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3777 struct alignas(void *) FunctionTypeExtraBitfields {
3778 /// The number of types in the exception specification.
3779 /// A whole unsigned is not needed here and according to
3780 /// [implimits] 8 bits would be enough here.
3781 unsigned NumExceptionType;
3782 };
3783
3784protected:
3785 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3786 TypeDependence Dependence, ExtInfo Info)
3787 : Type(tc, Canonical, Dependence), ResultType(res) {
3788 FunctionTypeBits.ExtInfo = Info.Bits;
3789 }
3790
3791 Qualifiers getFastTypeQuals() const {
3792 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3793 }
3794
3795public:
3796 QualType getReturnType() const { return ResultType; }
3797
3798 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3799 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3800
3801 /// Determine whether this function type includes the GNU noreturn
3802 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3803 /// type.
3804 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3805
3806 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3807 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3808 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3809
3810 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3811 "Const, volatile and restrict are assumed to be a subset of "
3812 "the fast qualifiers.");
3813
3814 bool isConst() const { return getFastTypeQuals().hasConst(); }
3815 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3816 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3817
3818 /// Determine the type of an expression that calls a function of
3819 /// this type.
3820 QualType getCallResultType(const ASTContext &Context) const {
3821 return getReturnType().getNonLValueExprType(Context);
3822 }
3823
3824 static StringRef getNameForCallConv(CallingConv CC);
3825
3826 static bool classof(const Type *T) {
3827 return T->getTypeClass() == FunctionNoProto ||
3828 T->getTypeClass() == FunctionProto;
3829 }
3830};
3831
3832/// Represents a K&R-style 'int foo()' function, which has
3833/// no information available about its arguments.
3834class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3835 friend class ASTContext; // ASTContext creates these.
3836
3837 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3838 : FunctionType(FunctionNoProto, Result, Canonical,
3839 Result->getDependence() &
3840 ~(TypeDependence::DependentInstantiation |
3841 TypeDependence::UnexpandedPack),
3842 Info) {}
3843
3844public:
3845 // No additional state past what FunctionType provides.
3846
3847 bool isSugared() const { return false; }
3848 QualType desugar() const { return QualType(this, 0); }
3849
3850 void Profile(llvm::FoldingSetNodeID &ID) {
3851 Profile(ID, getReturnType(), getExtInfo());
3852 }
3853
3854 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3855 ExtInfo Info) {
3856 Info.Profile(ID);
3857 ID.AddPointer(ResultType.getAsOpaquePtr());
3858 }
3859
3860 static bool classof(const Type *T) {
3861 return T->getTypeClass() == FunctionNoProto;
3862 }
3863};
3864
3865/// Represents a prototype with parameter type info, e.g.
3866/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3867/// parameters, not as having a single void parameter. Such a type can have
3868/// an exception specification, but this specification is not part of the
3869/// canonical type. FunctionProtoType has several trailing objects, some of
3870/// which optional. For more information about the trailing objects see
3871/// the first comment inside FunctionProtoType.
3872class FunctionProtoType final
3873 : public FunctionType,
3874 public llvm::FoldingSetNode,
3875 private llvm::TrailingObjects<
3876 FunctionProtoType, QualType, SourceLocation,
3877 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3878 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3879 friend class ASTContext; // ASTContext creates these.
3880 friend TrailingObjects;
3881
3882 // FunctionProtoType is followed by several trailing objects, some of
3883 // which optional. They are in order:
3884 //
3885 // * An array of getNumParams() QualType holding the parameter types.
3886 // Always present. Note that for the vast majority of FunctionProtoType,
3887 // these will be the only trailing objects.
3888 //
3889 // * Optionally if the function is variadic, the SourceLocation of the
3890 // ellipsis.
3891 //
3892 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3893 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3894 // a single FunctionTypeExtraBitfields. Present if and only if
3895 // hasExtraBitfields() is true.
3896 //
3897 // * Optionally exactly one of:
3898 // * an array of getNumExceptions() ExceptionType,
3899 // * a single Expr *,
3900 // * a pair of FunctionDecl *,
3901 // * a single FunctionDecl *
3902 // used to store information about the various types of exception
3903 // specification. See getExceptionSpecSize for the details.
3904 //
3905 // * Optionally an array of getNumParams() ExtParameterInfo holding
3906 // an ExtParameterInfo for each of the parameters. Present if and
3907 // only if hasExtParameterInfos() is true.
3908 //
3909 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3910 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3911 // if hasExtQualifiers() is true.
3912 //
3913 // The optional FunctionTypeExtraBitfields has to be before the data
3914 // related to the exception specification since it contains the number
3915 // of exception types.
3916 //
3917 // We put the ExtParameterInfos last. If all were equal, it would make
3918 // more sense to put these before the exception specification, because
3919 // it's much easier to skip past them compared to the elaborate switch
3920 // required to skip the exception specification. However, all is not
3921 // equal; ExtParameterInfos are used to model very uncommon features,
3922 // and it's better not to burden the more common paths.
3923
3924public:
3925 /// Holds information about the various types of exception specification.
3926 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3927 /// used to group together the various bits of information about the
3928 /// exception specification.
3929 struct ExceptionSpecInfo {
3930 /// The kind of exception specification this is.
3931 ExceptionSpecificationType Type = EST_None;
3932
3933 /// Explicitly-specified list of exception types.
3934 ArrayRef<QualType> Exceptions;
3935
3936 /// Noexcept expression, if this is a computed noexcept specification.
3937 Expr *NoexceptExpr = nullptr;
3938
3939 /// The function whose exception specification this is, for
3940 /// EST_Unevaluated and EST_Uninstantiated.
3941 FunctionDecl *SourceDecl = nullptr;
3942
3943 /// The function template whose exception specification this is instantiated
3944 /// from, for EST_Uninstantiated.
3945 FunctionDecl *SourceTemplate = nullptr;
3946
3947 ExceptionSpecInfo() = default;
3948
3949 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3950 };
3951
3952 /// Extra information about a function prototype. ExtProtoInfo is not
3953 /// stored as such in FunctionProtoType but is used to group together
3954 /// the various bits of extra information about a function prototype.
3955 struct ExtProtoInfo {
3956 FunctionType::ExtInfo ExtInfo;
3957 bool Variadic : 1;
3958 bool HasTrailingReturn : 1;
3959 Qualifiers TypeQuals;
3960 RefQualifierKind RefQualifier = RQ_None;
3961 ExceptionSpecInfo ExceptionSpec;
3962 const ExtParameterInfo *ExtParameterInfos = nullptr;
3963 SourceLocation EllipsisLoc;
3964
3965 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3966
3967 ExtProtoInfo(CallingConv CC)
3968 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3969
3970 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3971 ExtProtoInfo Result(*this);
3972 Result.ExceptionSpec = ESI;
3973 return Result;
3974 }
3975 };
3976
3977private:
3978 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3979 return getNumParams();
3980 }
3981
3982 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3983 return isVariadic();
3984 }
3985
3986 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3987 return hasExtraBitfields();
3988 }
3989
3990 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3991 return getExceptionSpecSize().NumExceptionType;
3992 }
3993
3994 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
3995 return getExceptionSpecSize().NumExprPtr;
3996 }
3997
3998 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
3999 return getExceptionSpecSize().NumFunctionDeclPtr;
4000 }
4001
4002 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4003 return hasExtParameterInfos() ? getNumParams() : 0;
4004 }
4005
4006 /// Determine whether there are any argument types that
4007 /// contain an unexpanded parameter pack.
4008 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4009 unsigned numArgs) {
4010 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4011 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4012 return true;
4013
4014 return false;
4015 }
4016
4017 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4018 QualType canonical, const ExtProtoInfo &epi);
4019
4020 /// This struct is returned by getExceptionSpecSize and is used to
4021 /// translate an ExceptionSpecificationType to the number and kind
4022 /// of trailing objects related to the exception specification.
4023 struct ExceptionSpecSizeHolder {
4024 unsigned NumExceptionType;
4025 unsigned NumExprPtr;
4026 unsigned NumFunctionDeclPtr;
4027 };
4028
4029 /// Return the number and kind of trailing objects
4030 /// related to the exception specification.
4031 static ExceptionSpecSizeHolder
4032 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4033 switch (EST) {
4034 case EST_None:
4035 case EST_DynamicNone:
4036 case EST_MSAny:
4037 case EST_BasicNoexcept:
4038 case EST_Unparsed:
4039 case EST_NoThrow:
4040 return {0, 0, 0};
4041
4042 case EST_Dynamic:
4043 return {NumExceptions, 0, 0};
4044
4045 case EST_DependentNoexcept:
4046 case EST_NoexceptFalse:
4047 case EST_NoexceptTrue:
4048 return {0, 1, 0};
4049
4050 case EST_Uninstantiated:
4051 return {0, 0, 2};
4052
4053 case EST_Unevaluated:
4054 return {0, 0, 1};
4055 }
4056 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4056)
;
4057 }
4058
4059 /// Return the number and kind of trailing objects
4060 /// related to the exception specification.
4061 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4062 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4063 }
4064
4065 /// Whether the trailing FunctionTypeExtraBitfields is present.
4066 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4067 // If the exception spec type is EST_Dynamic then we have > 0 exception
4068 // types and the exact number is stored in FunctionTypeExtraBitfields.
4069 return EST == EST_Dynamic;
4070 }
4071
4072 /// Whether the trailing FunctionTypeExtraBitfields is present.
4073 bool hasExtraBitfields() const {
4074 return hasExtraBitfields(getExceptionSpecType());
4075 }
4076
4077 bool hasExtQualifiers() const {
4078 return FunctionTypeBits.HasExtQuals;
4079 }
4080
4081public:
4082 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4083
4084 QualType getParamType(unsigned i) const {
4085 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4085, __PRETTY_FUNCTION__))
;
4086 return param_type_begin()[i];
4087 }
4088
4089 ArrayRef<QualType> getParamTypes() const {
4090 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4091 }
4092
4093 ExtProtoInfo getExtProtoInfo() const {
4094 ExtProtoInfo EPI;
4095 EPI.ExtInfo = getExtInfo();
4096 EPI.Variadic = isVariadic();
4097 EPI.EllipsisLoc = getEllipsisLoc();
4098 EPI.HasTrailingReturn = hasTrailingReturn();
4099 EPI.ExceptionSpec = getExceptionSpecInfo();
4100 EPI.TypeQuals = getMethodQuals();
4101 EPI.RefQualifier = getRefQualifier();
4102 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4103 return EPI;
4104 }
4105
4106 /// Get the kind of exception specification on this function.
4107 ExceptionSpecificationType getExceptionSpecType() const {
4108 return static_cast<ExceptionSpecificationType>(
4109 FunctionTypeBits.ExceptionSpecType);
4110 }
4111
4112 /// Return whether this function has any kind of exception spec.
4113 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4114
4115 /// Return whether this function has a dynamic (throw) exception spec.
4116 bool hasDynamicExceptionSpec() const {
4117 return isDynamicExceptionSpec(getExceptionSpecType());
4118 }
4119
4120 /// Return whether this function has a noexcept exception spec.
4121 bool hasNoexceptExceptionSpec() const {
4122 return isNoexceptExceptionSpec(getExceptionSpecType());
4123 }
4124
4125 /// Return whether this function has a dependent exception spec.
4126 bool hasDependentExceptionSpec() const;
4127
4128 /// Return whether this function has an instantiation-dependent exception
4129 /// spec.
4130 bool hasInstantiationDependentExceptionSpec() const;
4131
4132 /// Return all the available information about this type's exception spec.
4133 ExceptionSpecInfo getExceptionSpecInfo() const {
4134 ExceptionSpecInfo Result;
4135 Result.Type = getExceptionSpecType();
4136 if (Result.Type == EST_Dynamic) {
4137 Result.Exceptions = exceptions();
4138 } else if (isComputedNoexcept(Result.Type)) {
4139 Result.NoexceptExpr = getNoexceptExpr();
4140 } else if (Result.Type == EST_Uninstantiated) {
4141 Result.SourceDecl = getExceptionSpecDecl();
4142 Result.SourceTemplate = getExceptionSpecTemplate();
4143 } else if (Result.Type == EST_Unevaluated) {
4144 Result.SourceDecl = getExceptionSpecDecl();
4145 }
4146 return Result;
4147 }
4148
4149 /// Return the number of types in the exception specification.
4150 unsigned getNumExceptions() const {
4151 return getExceptionSpecType() == EST_Dynamic
4152 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4153 ->NumExceptionType
4154 : 0;
4155 }
4156
4157 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4158 QualType getExceptionType(unsigned i) const {
4159 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4159, __PRETTY_FUNCTION__))
;
4160 return exception_begin()[i];
4161 }
4162
4163 /// Return the expression inside noexcept(expression), or a null pointer
4164 /// if there is none (because the exception spec is not of this form).
4165 Expr *getNoexceptExpr() const {
4166 if (!isComputedNoexcept(getExceptionSpecType()))
4167 return nullptr;
4168 return *getTrailingObjects<Expr *>();
4169 }
4170
4171 /// If this function type has an exception specification which hasn't
4172 /// been determined yet (either because it has not been evaluated or because
4173 /// it has not been instantiated), this is the function whose exception
4174 /// specification is represented by this type.
4175 FunctionDecl *getExceptionSpecDecl() const {
4176 if (getExceptionSpecType() != EST_Uninstantiated &&
4177 getExceptionSpecType() != EST_Unevaluated)
4178 return nullptr;
4179 return getTrailingObjects<FunctionDecl *>()[0];
4180 }
4181
4182 /// If this function type has an uninstantiated exception
4183 /// specification, this is the function whose exception specification
4184 /// should be instantiated to find the exception specification for
4185 /// this type.
4186 FunctionDecl *getExceptionSpecTemplate() const {
4187 if (getExceptionSpecType() != EST_Uninstantiated)
4188 return nullptr;
4189 return getTrailingObjects<FunctionDecl *>()[1];
4190 }
4191
4192 /// Determine whether this function type has a non-throwing exception
4193 /// specification.
4194 CanThrowResult canThrow() const;
4195
4196 /// Determine whether this function type has a non-throwing exception
4197 /// specification. If this depends on template arguments, returns
4198 /// \c ResultIfDependent.
4199 bool isNothrow(bool ResultIfDependent = false) const {
4200 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4201 }
4202
4203 /// Whether this function prototype is variadic.
4204 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4205
4206 SourceLocation getEllipsisLoc() const {
4207 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4208 : SourceLocation();
4209 }
4210
4211 /// Determines whether this function prototype contains a
4212 /// parameter pack at the end.
4213 ///
4214 /// A function template whose last parameter is a parameter pack can be
4215 /// called with an arbitrary number of arguments, much like a variadic
4216 /// function.
4217 bool isTemplateVariadic() const;
4218
4219 /// Whether this function prototype has a trailing return type.
4220 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4221
4222 Qualifiers getMethodQuals() const {
4223 if (hasExtQualifiers())
4224 return *getTrailingObjects<Qualifiers>();
4225 else
4226 return getFastTypeQuals();
4227 }
4228
4229 /// Retrieve the ref-qualifier associated with this function type.
4230 RefQualifierKind getRefQualifier() const {
4231 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4232 }
4233
4234 using param_type_iterator = const QualType *;
4235 using param_type_range = llvm::iterator_range<param_type_iterator>;
4236
4237 param_type_range param_types() const {
4238 return param_type_range(param_type_begin(), param_type_end());
4239 }
4240
4241 param_type_iterator param_type_begin() const {
4242 return getTrailingObjects<QualType>();
4243 }
4244
4245 param_type_iterator param_type_end() const {
4246 return param_type_begin() + getNumParams();
4247 }
4248
4249 using exception_iterator = const QualType *;
4250
4251 ArrayRef<QualType> exceptions() const {
4252 return llvm::makeArrayRef(exception_begin(), exception_end());
4253 }
4254
4255 exception_iterator exception_begin() const {
4256 return reinterpret_cast<exception_iterator>(
4257 getTrailingObjects<ExceptionType>());
4258 }
4259
4260 exception_iterator exception_end() const {
4261 return exception_begin() + getNumExceptions();
4262 }
4263
4264 /// Is there any interesting extra information for any of the parameters
4265 /// of this function type?
4266 bool hasExtParameterInfos() const {
4267 return FunctionTypeBits.HasExtParameterInfos;
4268 }
4269
4270 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4271 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4271, __PRETTY_FUNCTION__))
;
4272 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4273 getNumParams());
4274 }
4275
4276 /// Return a pointer to the beginning of the array of extra parameter
4277 /// information, if present, or else null if none of the parameters
4278 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4279 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4280 if (!hasExtParameterInfos())
4281 return nullptr;
4282 return getTrailingObjects<ExtParameterInfo>();
4283 }
4284
4285 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4286 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4286, __PRETTY_FUNCTION__))
;
4287 if (hasExtParameterInfos())
4288 return getTrailingObjects<ExtParameterInfo>()[I];
4289 return ExtParameterInfo();
4290 }
4291
4292 ParameterABI getParameterABI(unsigned I) const {
4293 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4293, __PRETTY_FUNCTION__))
;
4294 if (hasExtParameterInfos())
4295 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4296 return ParameterABI::Ordinary;
4297 }
4298
4299 bool isParamConsumed(unsigned I) const {
4300 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4300, __PRETTY_FUNCTION__))
;
4301 if (hasExtParameterInfos())
4302 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4303 return false;
4304 }
4305
4306 bool isSugared() const { return false; }
4307 QualType desugar() const { return QualType(this, 0); }
4308
4309 void printExceptionSpecification(raw_ostream &OS,
4310 const PrintingPolicy &Policy) const;
4311
4312 static bool classof(const Type *T) {
4313 return T->getTypeClass() == FunctionProto;
4314 }
4315
4316 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4317 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4318 param_type_iterator ArgTys, unsigned NumArgs,
4319 const ExtProtoInfo &EPI, const ASTContext &Context,
4320 bool Canonical);
4321};
4322
4323/// Represents the dependent type named by a dependently-scoped
4324/// typename using declaration, e.g.
4325/// using typename Base<T>::foo;
4326///
4327/// Template instantiation turns these into the underlying type.
4328class UnresolvedUsingType : public Type {
4329 friend class ASTContext; // ASTContext creates these.
4330
4331 UnresolvedUsingTypenameDecl *Decl;
4332
4333 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4334 : Type(UnresolvedUsing, QualType(),
4335 TypeDependence::DependentInstantiation),
4336 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4337
4338public:
4339 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4340
4341 bool isSugared() const { return false; }
4342 QualType desugar() const { return QualType(this, 0); }
4343
4344 static bool classof(const Type *T) {
4345 return T->getTypeClass() == UnresolvedUsing;
4346 }
4347
4348 void Profile(llvm::FoldingSetNodeID &ID) {
4349 return Profile(ID, Decl);
4350 }
4351
4352 static void Profile(llvm::FoldingSetNodeID &ID,
4353 UnresolvedUsingTypenameDecl *D) {
4354 ID.AddPointer(D);
4355 }
4356};
4357
4358class TypedefType : public Type {
4359 TypedefNameDecl *Decl;
4360
4361protected:
4362 friend class ASTContext; // ASTContext creates these.
4363
4364 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType can);
4365
4366public:
4367 TypedefNameDecl *getDecl() const { return Decl; }
4368
4369 bool isSugared() const { return true; }
4370 QualType desugar() const;
4371
4372 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4373};
4374
4375/// Sugar type that represents a type that was qualified by a qualifier written
4376/// as a macro invocation.
4377class MacroQualifiedType : public Type {
4378 friend class ASTContext; // ASTContext creates these.
4379
4380 QualType UnderlyingTy;
4381 const IdentifierInfo *MacroII;
4382
4383 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4384 const IdentifierInfo *MacroII)
4385 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4386 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4387 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4388, __PRETTY_FUNCTION__))
4388 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4388, __PRETTY_FUNCTION__))
;
4389 }
4390
4391public:
4392 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4393 QualType getUnderlyingType() const { return UnderlyingTy; }
4394
4395 /// Return this attributed type's modified type with no qualifiers attached to
4396 /// it.
4397 QualType getModifiedType() const;
4398
4399 bool isSugared() const { return true; }
4400 QualType desugar() const;
4401
4402 static bool classof(const Type *T) {
4403 return T->getTypeClass() == MacroQualified;
4404 }
4405};
4406
4407/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4408class TypeOfExprType : public Type {
4409 Expr *TOExpr;
4410
4411protected:
4412 friend class ASTContext; // ASTContext creates these.
4413
4414 TypeOfExprType(Expr *E, QualType can = QualType());
4415
4416public:
4417 Expr *getUnderlyingExpr() const { return TOExpr; }
4418
4419 /// Remove a single level of sugar.
4420 QualType desugar() const;
4421
4422 /// Returns whether this type directly provides sugar.
4423 bool isSugared() const;
4424
4425 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4426};
4427
4428/// Internal representation of canonical, dependent
4429/// `typeof(expr)` types.
4430///
4431/// This class is used internally by the ASTContext to manage
4432/// canonical, dependent types, only. Clients will only see instances
4433/// of this class via TypeOfExprType nodes.
4434class DependentTypeOfExprType
4435 : public TypeOfExprType, public llvm::FoldingSetNode {
4436 const ASTContext &Context;
4437
4438public:
4439 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4440 : TypeOfExprType(E), Context(Context) {}
4441
4442 void Profile(llvm::FoldingSetNodeID &ID) {
4443 Profile(ID, Context, getUnderlyingExpr());
4444 }
4445
4446 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4447 Expr *E);
4448};
4449
4450/// Represents `typeof(type)`, a GCC extension.
4451class TypeOfType : public Type {
4452 friend class ASTContext; // ASTContext creates these.
4453
4454 QualType TOType;
4455
4456 TypeOfType(QualType T, QualType can)
4457 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4458 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4458, __PRETTY_FUNCTION__))
;
4459 }
4460
4461public:
4462 QualType getUnderlyingType() const { return TOType; }
4463
4464 /// Remove a single level of sugar.
4465 QualType desugar() const { return getUnderlyingType(); }
4466
4467 /// Returns whether this type directly provides sugar.
4468 bool isSugared() const { return true; }
4469
4470 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4471};
4472
4473/// Represents the type `decltype(expr)` (C++11).
4474class DecltypeType : public Type {
4475 Expr *E;
4476 QualType UnderlyingType;
4477
4478protected:
4479 friend class ASTContext; // ASTContext creates these.
4480
4481 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4482
4483public:
4484 Expr *getUnderlyingExpr() const { return E; }
4485 QualType getUnderlyingType() const { return UnderlyingType; }
4486
4487 /// Remove a single level of sugar.
4488 QualType desugar() const;
4489
4490 /// Returns whether this type directly provides sugar.
4491 bool isSugared() const;
4492
4493 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4494};
4495
4496/// Internal representation of canonical, dependent
4497/// decltype(expr) types.
4498///
4499/// This class is used internally by the ASTContext to manage
4500/// canonical, dependent types, only. Clients will only see instances
4501/// of this class via DecltypeType nodes.
4502class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4503 const ASTContext &Context;
4504
4505public:
4506 DependentDecltypeType(const ASTContext &Context, Expr *E);
4507
4508 void Profile(llvm::FoldingSetNodeID &ID) {
4509 Profile(ID, Context, getUnderlyingExpr());
4510 }
4511
4512 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4513 Expr *E);
4514};
4515
4516/// A unary type transform, which is a type constructed from another.
4517class UnaryTransformType : public Type {
4518public:
4519 enum UTTKind {
4520 EnumUnderlyingType
4521 };
4522
4523private:
4524 /// The untransformed type.
4525 QualType BaseType;
4526
4527 /// The transformed type if not dependent, otherwise the same as BaseType.
4528 QualType UnderlyingType;
4529
4530 UTTKind UKind;
4531
4532protected:
4533 friend class ASTContext;
4534
4535 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4536 QualType CanonicalTy);
4537
4538public:
4539 bool isSugared() const { return !isDependentType(); }
4540 QualType desugar() const { return UnderlyingType; }
4541
4542 QualType getUnderlyingType() const { return UnderlyingType; }
4543 QualType getBaseType() const { return BaseType; }
4544
4545 UTTKind getUTTKind() const { return UKind; }
4546
4547 static bool classof(const Type *T) {
4548 return T->getTypeClass() == UnaryTransform;
4549 }
4550};
4551
4552/// Internal representation of canonical, dependent
4553/// __underlying_type(type) types.
4554///
4555/// This class is used internally by the ASTContext to manage
4556/// canonical, dependent types, only. Clients will only see instances
4557/// of this class via UnaryTransformType nodes.
4558class DependentUnaryTransformType : public UnaryTransformType,
4559 public llvm::FoldingSetNode {
4560public:
4561 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4562 UTTKind UKind);
4563
4564 void Profile(llvm::FoldingSetNodeID &ID) {
4565 Profile(ID, getBaseType(), getUTTKind());
4566 }
4567
4568 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4569 UTTKind UKind) {
4570 ID.AddPointer(BaseType.getAsOpaquePtr());
4571 ID.AddInteger((unsigned)UKind);
4572 }
4573};
4574
4575class TagType : public Type {
4576 friend class ASTReader;
4577 template <class T> friend class serialization::AbstractTypeReader;
4578
4579 /// Stores the TagDecl associated with this type. The decl may point to any
4580 /// TagDecl that declares the entity.
4581 TagDecl *decl;
4582
4583protected:
4584 TagType(TypeClass TC, const TagDecl *D, QualType can);
4585
4586public:
4587 TagDecl *getDecl() const;
4588
4589 /// Determines whether this type is in the process of being defined.
4590 bool isBeingDefined() const;
4591
4592 static bool classof(const Type *T) {
4593 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4594 }
4595};
4596
4597/// A helper class that allows the use of isa/cast/dyncast
4598/// to detect TagType objects of structs/unions/classes.
4599class RecordType : public TagType {
4600protected:
4601 friend class ASTContext; // ASTContext creates these.
4602
4603 explicit RecordType(const RecordDecl *D)
4604 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4605 explicit RecordType(TypeClass TC, RecordDecl *D)
4606 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4607
4608public:
4609 RecordDecl *getDecl() const {
4610 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4611 }
4612
4613 /// Recursively check all fields in the record for const-ness. If any field
4614 /// is declared const, return true. Otherwise, return false.
4615 bool hasConstFields() const;
4616
4617 bool isSugared() const { return false; }
4618 QualType desugar() const { return QualType(this, 0); }
4619
4620 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4621};
4622
4623/// A helper class that allows the use of isa/cast/dyncast
4624/// to detect TagType objects of enums.
4625class EnumType : public TagType {
4626 friend class ASTContext; // ASTContext creates these.
4627
4628 explicit EnumType(const EnumDecl *D)
4629 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4630
4631public:
4632 EnumDecl *getDecl() const {
4633 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4634 }
4635
4636 bool isSugared() const { return false; }
4637 QualType desugar() const { return QualType(this, 0); }
4638
4639 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4640};
4641
4642/// An attributed type is a type to which a type attribute has been applied.
4643///
4644/// The "modified type" is the fully-sugared type to which the attributed
4645/// type was applied; generally it is not canonically equivalent to the
4646/// attributed type. The "equivalent type" is the minimally-desugared type
4647/// which the type is canonically equivalent to.
4648///
4649/// For example, in the following attributed type:
4650/// int32_t __attribute__((vector_size(16)))
4651/// - the modified type is the TypedefType for int32_t
4652/// - the equivalent type is VectorType(16, int32_t)
4653/// - the canonical type is VectorType(16, int)
4654class AttributedType : public Type, public llvm::FoldingSetNode {
4655public:
4656 using Kind = attr::Kind;
4657
4658private:
4659 friend class ASTContext; // ASTContext creates these
4660
4661 QualType ModifiedType;
4662 QualType EquivalentType;
4663
4664 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4665 QualType equivalent)
4666 : Type(Attributed, canon, equivalent->getDependence()),
4667 ModifiedType(modified), EquivalentType(equivalent) {
4668 AttributedTypeBits.AttrKind = attrKind;
4669 }
4670
4671public:
4672 Kind getAttrKind() const {
4673 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4674 }
4675
4676 QualType getModifiedType() const { return ModifiedType; }
4677 QualType getEquivalentType() const { return EquivalentType; }
4678
4679 bool isSugared() const { return true; }
4680 QualType desugar() const { return getEquivalentType(); }
4681
4682 /// Does this attribute behave like a type qualifier?
4683 ///
4684 /// A type qualifier adjusts a type to provide specialized rules for
4685 /// a specific object, like the standard const and volatile qualifiers.
4686 /// This includes attributes controlling things like nullability,
4687 /// address spaces, and ARC ownership. The value of the object is still
4688 /// largely described by the modified type.
4689 ///
4690 /// In contrast, many type attributes "rewrite" their modified type to
4691 /// produce a fundamentally different type, not necessarily related in any
4692 /// formalizable way to the original type. For example, calling convention
4693 /// and vector attributes are not simple type qualifiers.
4694 ///
4695 /// Type qualifiers are often, but not always, reflected in the canonical
4696 /// type.
4697 bool isQualifier() const;
4698
4699 bool isMSTypeSpec() const;
4700
4701 bool isCallingConv() const;
4702
4703 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4704
4705 /// Retrieve the attribute kind corresponding to the given
4706 /// nullability kind.
4707 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4708 switch (kind) {
4709 case NullabilityKind::NonNull:
4710 return attr::TypeNonNull;
4711
4712 case NullabilityKind::Nullable:
4713 return attr::TypeNullable;
4714
4715 case NullabilityKind::Unspecified:
4716 return attr::TypeNullUnspecified;
4717 }
4718 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 4718)
;
4719 }
4720
4721 /// Strip off the top-level nullability annotation on the given
4722 /// type, if it's there.
4723 ///
4724 /// \param T The type to strip. If the type is exactly an
4725 /// AttributedType specifying nullability (without looking through
4726 /// type sugar), the nullability is returned and this type changed
4727 /// to the underlying modified type.
4728 ///
4729 /// \returns the top-level nullability, if present.
4730 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4731
4732 void Profile(llvm::FoldingSetNodeID &ID) {
4733 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4734 }
4735
4736 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4737 QualType modified, QualType equivalent) {
4738 ID.AddInteger(attrKind);
4739 ID.AddPointer(modified.getAsOpaquePtr());
4740 ID.AddPointer(equivalent.getAsOpaquePtr());
4741 }
4742
4743 static bool classof(const Type *T) {
4744 return T->getTypeClass() == Attributed;
4745 }
4746};
4747
4748class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4749 friend class ASTContext; // ASTContext creates these
4750
4751 // Helper data collector for canonical types.
4752 struct CanonicalTTPTInfo {
4753 unsigned Depth : 15;
4754 unsigned ParameterPack : 1;
4755 unsigned Index : 16;
4756 };
4757
4758 union {
4759 // Info for the canonical type.
4760 CanonicalTTPTInfo CanTTPTInfo;
4761
4762 // Info for the non-canonical type.
4763 TemplateTypeParmDecl *TTPDecl;
4764 };
4765
4766 /// Build a non-canonical type.
4767 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4768 : Type(TemplateTypeParm, Canon,
4769 TypeDependence::DependentInstantiation |
4770 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4771 TTPDecl(TTPDecl) {}
4772
4773 /// Build the canonical type.
4774 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4775 : Type(TemplateTypeParm, QualType(this, 0),
4776 TypeDependence::DependentInstantiation |
4777 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4778 CanTTPTInfo.Depth = D;
4779 CanTTPTInfo.Index = I;
4780 CanTTPTInfo.ParameterPack = PP;
4781 }
4782
4783 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4784 QualType Can = getCanonicalTypeInternal();
4785 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4786 }
4787
4788public:
4789 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4790 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4791 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4792
4793 TemplateTypeParmDecl *getDecl() const {
4794 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4795 }
4796
4797 IdentifierInfo *getIdentifier() const;
4798
4799 bool isSugared() const { return false; }
4800 QualType desugar() const { return QualType(this, 0); }
4801
4802 void Profile(llvm::FoldingSetNodeID &ID) {
4803 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4804 }
4805
4806 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4807 unsigned Index, bool ParameterPack,
4808 TemplateTypeParmDecl *TTPDecl) {
4809 ID.AddInteger(Depth);
4810 ID.AddInteger(Index);
4811 ID.AddBoolean(ParameterPack);
4812 ID.AddPointer(TTPDecl);
4813 }
4814
4815 static bool classof(const Type *T) {
4816 return T->getTypeClass() == TemplateTypeParm;
4817 }
4818};
4819
4820/// Represents the result of substituting a type for a template
4821/// type parameter.
4822///
4823/// Within an instantiated template, all template type parameters have
4824/// been replaced with these. They are used solely to record that a
4825/// type was originally written as a template type parameter;
4826/// therefore they are never canonical.
4827class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4828 friend class ASTContext;
4829
4830 // The original type parameter.
4831 const TemplateTypeParmType *Replaced;
4832
4833 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4834 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4835 Replaced(Param) {}
4836
4837public:
4838 /// Gets the template parameter that was substituted for.
4839 const TemplateTypeParmType *getReplacedParameter() const {
4840 return Replaced;
4841 }
4842
4843 /// Gets the type that was substituted for the template
4844 /// parameter.
4845 QualType getReplacementType() const {
4846 return getCanonicalTypeInternal();
4847 }
4848
4849 bool isSugared() const { return true; }
4850 QualType desugar() const { return getReplacementType(); }
4851
4852 void Profile(llvm::FoldingSetNodeID &ID) {
4853 Profile(ID, getReplacedParameter(), getReplacementType());
4854 }
4855
4856 static void Profile(llvm::FoldingSetNodeID &ID,
4857 const TemplateTypeParmType *Replaced,
4858 QualType Replacement) {
4859 ID.AddPointer(Replaced);
4860 ID.AddPointer(Replacement.getAsOpaquePtr());
4861 }
4862
4863 static bool classof(const Type *T) {
4864 return T->getTypeClass() == SubstTemplateTypeParm;
4865 }
4866};
4867
4868/// Represents the result of substituting a set of types for a template
4869/// type parameter pack.
4870///
4871/// When a pack expansion in the source code contains multiple parameter packs
4872/// and those parameter packs correspond to different levels of template
4873/// parameter lists, this type node is used to represent a template type
4874/// parameter pack from an outer level, which has already had its argument pack
4875/// substituted but that still lives within a pack expansion that itself
4876/// could not be instantiated. When actually performing a substitution into
4877/// that pack expansion (e.g., when all template parameters have corresponding
4878/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4879/// at the current pack substitution index.
4880class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4881 friend class ASTContext;
4882
4883 /// The original type parameter.
4884 const TemplateTypeParmType *Replaced;
4885
4886 /// A pointer to the set of template arguments that this
4887 /// parameter pack is instantiated with.
4888 const TemplateArgument *Arguments;
4889
4890 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4891 QualType Canon,
4892 const TemplateArgument &ArgPack);
4893
4894public:
4895 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4896
4897 /// Gets the template parameter that was substituted for.
4898 const TemplateTypeParmType *getReplacedParameter() const {
4899 return Replaced;
4900 }
4901
4902 unsigned getNumArgs() const {
4903 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4904 }
4905
4906 bool isSugared() const { return false; }
4907 QualType desugar() const { return QualType(this, 0); }
4908
4909 TemplateArgument getArgumentPack() const;
4910
4911 void Profile(llvm::FoldingSetNodeID &ID);
4912 static void Profile(llvm::FoldingSetNodeID &ID,
4913 const TemplateTypeParmType *Replaced,
4914 const TemplateArgument &ArgPack);
4915
4916 static bool classof(const Type *T) {
4917 return T->getTypeClass() == SubstTemplateTypeParmPack;
4918 }
4919};
4920
4921/// Common base class for placeholders for types that get replaced by
4922/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4923/// class template types, and constrained type names.
4924///
4925/// These types are usually a placeholder for a deduced type. However, before
4926/// the initializer is attached, or (usually) if the initializer is
4927/// type-dependent, there is no deduced type and the type is canonical. In
4928/// the latter case, it is also a dependent type.
4929class DeducedType : public Type {
4930protected:
4931 DeducedType(TypeClass TC, QualType DeducedAsType,
4932 TypeDependence ExtraDependence)
4933 : Type(TC,
4934 // FIXME: Retain the sugared deduced type?
4935 DeducedAsType.isNull() ? QualType(this, 0)
4936 : DeducedAsType.getCanonicalType(),
4937 ExtraDependence | (DeducedAsType.isNull()
4938 ? TypeDependence::None
4939 : DeducedAsType->getDependence() &
4940 ~TypeDependence::VariablyModified)) {}
4941
4942public:
4943 bool isSugared() const { return !isCanonicalUnqualified(); }
4944 QualType desugar() const { return getCanonicalTypeInternal(); }
4945
4946 /// Get the type deduced for this placeholder type, or null if it's
4947 /// either not been deduced or was deduced to a dependent type.
4948 QualType getDeducedType() const {
4949 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4950 }
4951 bool isDeduced() const {
4952 return !isCanonicalUnqualified() || isDependentType();
4953 }
4954
4955 static bool classof(const Type *T) {
4956 return T->getTypeClass() == Auto ||
4957 T->getTypeClass() == DeducedTemplateSpecialization;
4958 }
4959};
4960
4961/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4962/// by a type-constraint.
4963class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4964 friend class ASTContext; // ASTContext creates these
4965
4966 ConceptDecl *TypeConstraintConcept;
4967
4968 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4969 TypeDependence ExtraDependence, ConceptDecl *CD,
4970 ArrayRef<TemplateArgument> TypeConstraintArgs);
4971
4972 const TemplateArgument *getArgBuffer() const {
4973 return reinterpret_cast<const TemplateArgument*>(this+1);
4974 }
4975
4976 TemplateArgument *getArgBuffer() {
4977 return reinterpret_cast<TemplateArgument*>(this+1);
4978 }
4979
4980public:
4981 /// Retrieve the template arguments.
4982 const TemplateArgument *getArgs() const {
4983 return getArgBuffer();
4984 }
4985
4986 /// Retrieve the number of template arguments.
4987 unsigned getNumArgs() const {
4988 return AutoTypeBits.NumArgs;
4989 }
4990
4991 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
4992
4993 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
4994 return {getArgs(), getNumArgs()};
4995 }
4996
4997 ConceptDecl *getTypeConstraintConcept() const {
4998 return TypeConstraintConcept;
4999 }
5000
5001 bool isConstrained() const {
5002 return TypeConstraintConcept != nullptr;
5003 }
5004
5005 bool isDecltypeAuto() const {
5006 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5007 }
5008
5009 AutoTypeKeyword getKeyword() const {
5010 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5011 }
5012
5013 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5014 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5015 getTypeConstraintConcept(), getTypeConstraintArguments());
5016 }
5017
5018 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5019 QualType Deduced, AutoTypeKeyword Keyword,
5020 bool IsDependent, ConceptDecl *CD,
5021 ArrayRef<TemplateArgument> Arguments);
5022
5023 static bool classof(const Type *T) {
5024 return T->getTypeClass() == Auto;
5025 }
5026};
5027
5028/// Represents a C++17 deduced template specialization type.
5029class DeducedTemplateSpecializationType : public DeducedType,
5030 public llvm::FoldingSetNode {
5031 friend class ASTContext; // ASTContext creates these
5032
5033 /// The name of the template whose arguments will be deduced.
5034 TemplateName Template;
5035
5036 DeducedTemplateSpecializationType(TemplateName Template,
5037 QualType DeducedAsType,
5038 bool IsDeducedAsDependent)
5039 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5040 toTypeDependence(Template.getDependence()) |
5041 (IsDeducedAsDependent
5042 ? TypeDependence::DependentInstantiation
5043 : TypeDependence::None)),
5044 Template(Template) {}
5045
5046public:
5047 /// Retrieve the name of the template that we are deducing.
5048 TemplateName getTemplateName() const { return Template;}
5049
5050 void Profile(llvm::FoldingSetNodeID &ID) {
5051 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5052 }
5053
5054 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5055 QualType Deduced, bool IsDependent) {
5056 Template.Profile(ID);
5057 ID.AddPointer(Deduced.getAsOpaquePtr());
5058 ID.AddBoolean(IsDependent);
5059 }
5060
5061 static bool classof(const Type *T) {
5062 return T->getTypeClass() == DeducedTemplateSpecialization;
5063 }
5064};
5065
5066/// Represents a type template specialization; the template
5067/// must be a class template, a type alias template, or a template
5068/// template parameter. A template which cannot be resolved to one of
5069/// these, e.g. because it is written with a dependent scope
5070/// specifier, is instead represented as a
5071/// @c DependentTemplateSpecializationType.
5072///
5073/// A non-dependent template specialization type is always "sugar",
5074/// typically for a \c RecordType. For example, a class template
5075/// specialization type of \c vector<int> will refer to a tag type for
5076/// the instantiation \c std::vector<int, std::allocator<int>>
5077///
5078/// Template specializations are dependent if either the template or
5079/// any of the template arguments are dependent, in which case the
5080/// type may also be canonical.
5081///
5082/// Instances of this type are allocated with a trailing array of
5083/// TemplateArguments, followed by a QualType representing the
5084/// non-canonical aliased type when the template is a type alias
5085/// template.
5086class alignas(8) TemplateSpecializationType
5087 : public Type,
5088 public llvm::FoldingSetNode {
5089 friend class ASTContext; // ASTContext creates these
5090
5091 /// The name of the template being specialized. This is
5092 /// either a TemplateName::Template (in which case it is a
5093 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5094 /// TypeAliasTemplateDecl*), a
5095 /// TemplateName::SubstTemplateTemplateParmPack, or a
5096 /// TemplateName::SubstTemplateTemplateParm (in which case the
5097 /// replacement must, recursively, be one of these).
5098 TemplateName Template;
5099
5100 TemplateSpecializationType(TemplateName T,
5101 ArrayRef<TemplateArgument> Args,
5102 QualType Canon,
5103 QualType Aliased);
5104
5105public:
5106 /// Determine whether any of the given template arguments are dependent.
5107 static bool anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5108 bool &InstantiationDependent);
5109
5110 static bool anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5111 bool &InstantiationDependent);
5112
5113 /// True if this template specialization type matches a current
5114 /// instantiation in the context in which it is found.
5115 bool isCurrentInstantiation() const {
5116 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5117 }
5118
5119 /// Determine if this template specialization type is for a type alias
5120 /// template that has been substituted.
5121 ///
5122 /// Nearly every template specialization type whose template is an alias
5123 /// template will be substituted. However, this is not the case when
5124 /// the specialization contains a pack expansion but the template alias
5125 /// does not have a corresponding parameter pack, e.g.,
5126 ///
5127 /// \code
5128 /// template<typename T, typename U, typename V> struct S;
5129 /// template<typename T, typename U> using A = S<T, int, U>;
5130 /// template<typename... Ts> struct X {
5131 /// typedef A<Ts...> type; // not a type alias
5132 /// };
5133 /// \endcode
5134 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5135
5136 /// Get the aliased type, if this is a specialization of a type alias
5137 /// template.
5138 QualType getAliasedType() const {
5139 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5139, __PRETTY_FUNCTION__))
;
5140 return *reinterpret_cast<const QualType*>(end());
5141 }
5142
5143 using iterator = const TemplateArgument *;
5144
5145 iterator begin() const { return getArgs(); }
5146 iterator end() const; // defined inline in TemplateBase.h
5147
5148 /// Retrieve the name of the template that we are specializing.
5149 TemplateName getTemplateName() const { return Template; }
5150
5151 /// Retrieve the template arguments.
5152 const TemplateArgument *getArgs() const {
5153 return reinterpret_cast<const TemplateArgument *>(this + 1);
5154 }
5155
5156 /// Retrieve the number of template arguments.
5157 unsigned getNumArgs() const {
5158 return TemplateSpecializationTypeBits.NumArgs;
5159 }
5160
5161 /// Retrieve a specific template argument as a type.
5162 /// \pre \c isArgType(Arg)
5163 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5164
5165 ArrayRef<TemplateArgument> template_arguments() const {
5166 return {getArgs(), getNumArgs()};
5167 }
5168
5169 bool isSugared() const {
5170 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5171 }
5172
5173 QualType desugar() const {
5174 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5175 }
5176
5177 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5178 Profile(ID, Template, template_arguments(), Ctx);
5179 if (isTypeAlias())
5180 getAliasedType().Profile(ID);
5181 }
5182
5183 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5184 ArrayRef<TemplateArgument> Args,
5185 const ASTContext &Context);
5186
5187 static bool classof(const Type *T) {
5188 return T->getTypeClass() == TemplateSpecialization;
5189 }
5190};
5191
5192/// Print a template argument list, including the '<' and '>'
5193/// enclosing the template arguments.
5194void printTemplateArgumentList(raw_ostream &OS,
5195 ArrayRef<TemplateArgument> Args,
5196 const PrintingPolicy &Policy);
5197
5198void printTemplateArgumentList(raw_ostream &OS,
5199 ArrayRef<TemplateArgumentLoc> Args,
5200 const PrintingPolicy &Policy);
5201
5202void printTemplateArgumentList(raw_ostream &OS,
5203 const TemplateArgumentListInfo &Args,
5204 const PrintingPolicy &Policy);
5205
5206/// The injected class name of a C++ class template or class
5207/// template partial specialization. Used to record that a type was
5208/// spelled with a bare identifier rather than as a template-id; the
5209/// equivalent for non-templated classes is just RecordType.
5210///
5211/// Injected class name types are always dependent. Template
5212/// instantiation turns these into RecordTypes.
5213///
5214/// Injected class name types are always canonical. This works
5215/// because it is impossible to compare an injected class name type
5216/// with the corresponding non-injected template type, for the same
5217/// reason that it is impossible to directly compare template
5218/// parameters from different dependent contexts: injected class name
5219/// types can only occur within the scope of a particular templated
5220/// declaration, and within that scope every template specialization
5221/// will canonicalize to the injected class name (when appropriate
5222/// according to the rules of the language).
5223class InjectedClassNameType : public Type {
5224 friend class ASTContext; // ASTContext creates these.
5225 friend class ASTNodeImporter;
5226 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5227 // currently suitable for AST reading, too much
5228 // interdependencies.
5229 template <class T> friend class serialization::AbstractTypeReader;
5230
5231 CXXRecordDecl *Decl;
5232
5233 /// The template specialization which this type represents.
5234 /// For example, in
5235 /// template <class T> class A { ... };
5236 /// this is A<T>, whereas in
5237 /// template <class X, class Y> class A<B<X,Y> > { ... };
5238 /// this is A<B<X,Y> >.
5239 ///
5240 /// It is always unqualified, always a template specialization type,
5241 /// and always dependent.
5242 QualType InjectedType;
5243
5244 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5245 : Type(InjectedClassName, QualType(),
5246 TypeDependence::DependentInstantiation),
5247 Decl(D), InjectedType(TST) {
5248 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5248, __PRETTY_FUNCTION__))
;
5249 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5249, __PRETTY_FUNCTION__))
;
5250 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5250, __PRETTY_FUNCTION__))
;
5251 }
5252
5253public:
5254 QualType getInjectedSpecializationType() const { return InjectedType; }
5255
5256 const TemplateSpecializationType *getInjectedTST() const {
5257 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5258 }
5259
5260 TemplateName getTemplateName() const {
5261 return getInjectedTST()->getTemplateName();
5262 }
5263
5264 CXXRecordDecl *getDecl() const;
5265
5266 bool isSugared() const { return false; }
5267 QualType desugar() const { return QualType(this, 0); }
5268
5269 static bool classof(const Type *T) {
5270 return T->getTypeClass() == InjectedClassName;
5271 }
5272};
5273
5274/// The kind of a tag type.
5275enum TagTypeKind {
5276 /// The "struct" keyword.
5277 TTK_Struct,
5278
5279 /// The "__interface" keyword.
5280 TTK_Interface,
5281
5282 /// The "union" keyword.
5283 TTK_Union,
5284
5285 /// The "class" keyword.
5286 TTK_Class,
5287
5288 /// The "enum" keyword.
5289 TTK_Enum
5290};
5291
5292/// The elaboration keyword that precedes a qualified type name or
5293/// introduces an elaborated-type-specifier.
5294enum ElaboratedTypeKeyword {
5295 /// The "struct" keyword introduces the elaborated-type-specifier.
5296 ETK_Struct,
5297
5298 /// The "__interface" keyword introduces the elaborated-type-specifier.
5299 ETK_Interface,
5300
5301 /// The "union" keyword introduces the elaborated-type-specifier.
5302 ETK_Union,
5303
5304 /// The "class" keyword introduces the elaborated-type-specifier.
5305 ETK_Class,
5306
5307 /// The "enum" keyword introduces the elaborated-type-specifier.
5308 ETK_Enum,
5309
5310 /// The "typename" keyword precedes the qualified type name, e.g.,
5311 /// \c typename T::type.
5312 ETK_Typename,
5313
5314 /// No keyword precedes the qualified type name.
5315 ETK_None
5316};
5317
5318/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5319/// The keyword in stored in the free bits of the base class.
5320/// Also provides a few static helpers for converting and printing
5321/// elaborated type keyword and tag type kind enumerations.
5322class TypeWithKeyword : public Type {
5323protected:
5324 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5325 QualType Canonical, TypeDependence Dependence)
5326 : Type(tc, Canonical, Dependence) {
5327 TypeWithKeywordBits.Keyword = Keyword;
5328 }
5329
5330public:
5331 ElaboratedTypeKeyword getKeyword() const {
5332 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5333 }
5334
5335 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5336 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5337
5338 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5339 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5340 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5341
5342 /// Converts a TagTypeKind into an elaborated type keyword.
5343 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5344
5345 /// Converts an elaborated type keyword into a TagTypeKind.
5346 /// It is an error to provide an elaborated type keyword
5347 /// which *isn't* a tag kind here.
5348 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5349
5350 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5351
5352 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5353
5354 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5355 return getKeywordName(getKeywordForTagTypeKind(Kind));
5356 }
5357
5358 class CannotCastToThisType {};
5359 static CannotCastToThisType classof(const Type *);
5360};
5361
5362/// Represents a type that was referred to using an elaborated type
5363/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5364/// or both.
5365///
5366/// This type is used to keep track of a type name as written in the
5367/// source code, including tag keywords and any nested-name-specifiers.
5368/// The type itself is always "sugar", used to express what was written
5369/// in the source code but containing no additional semantic information.
5370class ElaboratedType final
5371 : public TypeWithKeyword,
5372 public llvm::FoldingSetNode,
5373 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5374 friend class ASTContext; // ASTContext creates these
5375 friend TrailingObjects;
5376
5377 /// The nested name specifier containing the qualifier.
5378 NestedNameSpecifier *NNS;
5379
5380 /// The type that this qualified name refers to.
5381 QualType NamedType;
5382
5383 /// The (re)declaration of this tag type owned by this occurrence is stored
5384 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5385 /// it, or obtain a null pointer if there is none.
5386
5387 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5388 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5389 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5390 NamedType->getDependence()),
5391 NNS(NNS), NamedType(NamedType) {
5392 ElaboratedTypeBits.HasOwnedTagDecl = false;
5393 if (OwnedTagDecl) {
5394 ElaboratedTypeBits.HasOwnedTagDecl = true;
5395 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5396 }
5397 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5399, __PRETTY_FUNCTION__))
5398 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5399, __PRETTY_FUNCTION__))
5399 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5399, __PRETTY_FUNCTION__))
;
5400 }
5401
5402public:
5403 /// Retrieve the qualification on this type.
5404 NestedNameSpecifier *getQualifier() const { return NNS; }
5405
5406 /// Retrieve the type named by the qualified-id.
5407 QualType getNamedType() const { return NamedType; }
5408
5409 /// Remove a single level of sugar.
5410 QualType desugar() const { return getNamedType(); }
5411
5412 /// Returns whether this type directly provides sugar.
5413 bool isSugared() const { return true; }
5414
5415 /// Return the (re)declaration of this type owned by this occurrence of this
5416 /// type, or nullptr if there is none.
5417 TagDecl *getOwnedTagDecl() const {
5418 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5419 : nullptr;
5420 }
5421
5422 void Profile(llvm::FoldingSetNodeID &ID) {
5423 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5424 }
5425
5426 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5427 NestedNameSpecifier *NNS, QualType NamedType,
5428 TagDecl *OwnedTagDecl) {
5429 ID.AddInteger(Keyword);
5430 ID.AddPointer(NNS);
5431 NamedType.Profile(ID);
5432 ID.AddPointer(OwnedTagDecl);
5433 }
5434
5435 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5436};
5437
5438/// Represents a qualified type name for which the type name is
5439/// dependent.
5440///
5441/// DependentNameType represents a class of dependent types that involve a
5442/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5443/// name of a type. The DependentNameType may start with a "typename" (for a
5444/// typename-specifier), "class", "struct", "union", or "enum" (for a
5445/// dependent elaborated-type-specifier), or nothing (in contexts where we
5446/// know that we must be referring to a type, e.g., in a base class specifier).
5447/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5448/// mode, this type is used with non-dependent names to delay name lookup until
5449/// instantiation.
5450class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5451 friend class ASTContext; // ASTContext creates these
5452
5453 /// The nested name specifier containing the qualifier.
5454 NestedNameSpecifier *NNS;
5455
5456 /// The type that this typename specifier refers to.
5457 const IdentifierInfo *Name;
5458
5459 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5460 const IdentifierInfo *Name, QualType CanonType)
5461 : TypeWithKeyword(Keyword, DependentName, CanonType,
5462 TypeDependence::DependentInstantiation |
5463 toTypeDependence(NNS->getDependence())),
5464 NNS(NNS), Name(Name) {}
5465
5466public:
5467 /// Retrieve the qualification on this type.
5468 NestedNameSpecifier *getQualifier() const { return NNS; }
5469
5470 /// Retrieve the type named by the typename specifier as an identifier.
5471 ///
5472 /// This routine will return a non-NULL identifier pointer when the
5473 /// form of the original typename was terminated by an identifier,
5474 /// e.g., "typename T::type".
5475 const IdentifierInfo *getIdentifier() const {
5476 return Name;
5477 }
5478
5479 bool isSugared() const { return false; }
5480 QualType desugar() const { return QualType(this, 0); }
5481
5482 void Profile(llvm::FoldingSetNodeID &ID) {
5483 Profile(ID, getKeyword(), NNS, Name);
5484 }
5485
5486 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5487 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5488 ID.AddInteger(Keyword);
5489 ID.AddPointer(NNS);
5490 ID.AddPointer(Name);
5491 }
5492
5493 static bool classof(const Type *T) {
5494 return T->getTypeClass() == DependentName;
5495 }
5496};
5497
5498/// Represents a template specialization type whose template cannot be
5499/// resolved, e.g.
5500/// A<T>::template B<T>
5501class alignas(8) DependentTemplateSpecializationType
5502 : public TypeWithKeyword,
5503 public llvm::FoldingSetNode {
5504 friend class ASTContext; // ASTContext creates these
5505
5506 /// The nested name specifier containing the qualifier.
5507 NestedNameSpecifier *NNS;
5508
5509 /// The identifier of the template.
5510 const IdentifierInfo *Name;
5511
5512 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5513 NestedNameSpecifier *NNS,
5514 const IdentifierInfo *Name,
5515 ArrayRef<TemplateArgument> Args,
5516 QualType Canon);
5517
5518 const TemplateArgument *getArgBuffer() const {
5519 return reinterpret_cast<const TemplateArgument*>(this+1);
5520 }
5521
5522 TemplateArgument *getArgBuffer() {
5523 return reinterpret_cast<TemplateArgument*>(this+1);
5524 }
5525
5526public:
5527 NestedNameSpecifier *getQualifier() const { return NNS; }
5528 const IdentifierInfo *getIdentifier() const { return Name; }
5529
5530 /// Retrieve the template arguments.
5531 const TemplateArgument *getArgs() const {
5532 return getArgBuffer();
5533 }
5534
5535 /// Retrieve the number of template arguments.
5536 unsigned getNumArgs() const {
5537 return DependentTemplateSpecializationTypeBits.NumArgs;
5538 }
5539
5540 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5541
5542 ArrayRef<TemplateArgument> template_arguments() const {
5543 return {getArgs(), getNumArgs()};
5544 }
5545
5546 using iterator = const TemplateArgument *;
5547
5548 iterator begin() const { return getArgs(); }
5549 iterator end() const; // inline in TemplateBase.h
5550
5551 bool isSugared() const { return false; }
5552 QualType desugar() const { return QualType(this, 0); }
5553
5554 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5555 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5556 }
5557
5558 static void Profile(llvm::FoldingSetNodeID &ID,
5559 const ASTContext &Context,
5560 ElaboratedTypeKeyword Keyword,
5561 NestedNameSpecifier *Qualifier,
5562 const IdentifierInfo *Name,
5563 ArrayRef<TemplateArgument> Args);
5564
5565 static bool classof(const Type *T) {
5566 return T->getTypeClass() == DependentTemplateSpecialization;
5567 }
5568};
5569
5570/// Represents a pack expansion of types.
5571///
5572/// Pack expansions are part of C++11 variadic templates. A pack
5573/// expansion contains a pattern, which itself contains one or more
5574/// "unexpanded" parameter packs. When instantiated, a pack expansion
5575/// produces a series of types, each instantiated from the pattern of
5576/// the expansion, where the Ith instantiation of the pattern uses the
5577/// Ith arguments bound to each of the unexpanded parameter packs. The
5578/// pack expansion is considered to "expand" these unexpanded
5579/// parameter packs.
5580///
5581/// \code
5582/// template<typename ...Types> struct tuple;
5583///
5584/// template<typename ...Types>
5585/// struct tuple_of_references {
5586/// typedef tuple<Types&...> type;
5587/// };
5588/// \endcode
5589///
5590/// Here, the pack expansion \c Types&... is represented via a
5591/// PackExpansionType whose pattern is Types&.
5592class PackExpansionType : public Type, public llvm::FoldingSetNode {
5593 friend class ASTContext; // ASTContext creates these
5594
5595 /// The pattern of the pack expansion.
5596 QualType Pattern;
5597
5598 PackExpansionType(QualType Pattern, QualType Canon,
5599 Optional<unsigned> NumExpansions)
5600 : Type(PackExpansion, Canon,
5601 (Pattern->getDependence() | TypeDependence::Dependent |
5602 TypeDependence::Instantiation) &
5603 ~TypeDependence::UnexpandedPack),
5604 Pattern(Pattern) {
5605 PackExpansionTypeBits.NumExpansions =
5606 NumExpansions ? *NumExpansions + 1 : 0;
5607 }
5608
5609public:
5610 /// Retrieve the pattern of this pack expansion, which is the
5611 /// type that will be repeatedly instantiated when instantiating the
5612 /// pack expansion itself.
5613 QualType getPattern() const { return Pattern; }
5614
5615 /// Retrieve the number of expansions that this pack expansion will
5616 /// generate, if known.
5617 Optional<unsigned> getNumExpansions() const {
5618 if (PackExpansionTypeBits.NumExpansions)
5619 return PackExpansionTypeBits.NumExpansions - 1;
5620 return None;
5621 }
5622
5623 bool isSugared() const { return false; }
5624 QualType desugar() const { return QualType(this, 0); }
5625
5626 void Profile(llvm::FoldingSetNodeID &ID) {
5627 Profile(ID, getPattern(), getNumExpansions());
5628 }
5629
5630 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5631 Optional<unsigned> NumExpansions) {
5632 ID.AddPointer(Pattern.getAsOpaquePtr());
5633 ID.AddBoolean(NumExpansions.hasValue());
5634 if (NumExpansions)
5635 ID.AddInteger(*NumExpansions);
5636 }
5637
5638 static bool classof(const Type *T) {
5639 return T->getTypeClass() == PackExpansion;
5640 }
5641};
5642
5643/// This class wraps the list of protocol qualifiers. For types that can
5644/// take ObjC protocol qualifers, they can subclass this class.
5645template <class T>
5646class ObjCProtocolQualifiers {
5647protected:
5648 ObjCProtocolQualifiers() = default;
5649
5650 ObjCProtocolDecl * const *getProtocolStorage() const {
5651 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5652 }
5653
5654 ObjCProtocolDecl **getProtocolStorage() {
5655 return static_cast<T*>(this)->getProtocolStorageImpl();
5656 }
5657
5658 void setNumProtocols(unsigned N) {
5659 static_cast<T*>(this)->setNumProtocolsImpl(N);
5660 }
5661
5662 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5663 setNumProtocols(protocols.size());
5664 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5665, __PRETTY_FUNCTION__))
5665 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5665, __PRETTY_FUNCTION__))
;
5666 if (!protocols.empty())
5667 memcpy(getProtocolStorage(), protocols.data(),
5668 protocols.size() * sizeof(ObjCProtocolDecl*));
5669 }
5670
5671public:
5672 using qual_iterator = ObjCProtocolDecl * const *;
5673 using qual_range = llvm::iterator_range<qual_iterator>;
5674
5675 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5676 qual_iterator qual_begin() const { return getProtocolStorage(); }
5677 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5678
5679 bool qual_empty() const { return getNumProtocols() == 0; }
5680
5681 /// Return the number of qualifying protocols in this type, or 0 if
5682 /// there are none.
5683 unsigned getNumProtocols() const {
5684 return static_cast<const T*>(this)->getNumProtocolsImpl();
5685 }
5686
5687 /// Fetch a protocol by index.
5688 ObjCProtocolDecl *getProtocol(unsigned I) const {
5689 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5689, __PRETTY_FUNCTION__))
;
5690 return qual_begin()[I];
5691 }
5692
5693 /// Retrieve all of the protocol qualifiers.
5694 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5695 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5696 }
5697};
5698
5699/// Represents a type parameter type in Objective C. It can take
5700/// a list of protocols.
5701class ObjCTypeParamType : public Type,
5702 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5703 public llvm::FoldingSetNode {
5704 friend class ASTContext;
5705 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5706
5707 /// The number of protocols stored on this type.
5708 unsigned NumProtocols : 6;
5709
5710 ObjCTypeParamDecl *OTPDecl;
5711
5712 /// The protocols are stored after the ObjCTypeParamType node. In the
5713 /// canonical type, the list of protocols are sorted alphabetically
5714 /// and uniqued.
5715 ObjCProtocolDecl **getProtocolStorageImpl();
5716
5717 /// Return the number of qualifying protocols in this interface type,
5718 /// or 0 if there are none.
5719 unsigned getNumProtocolsImpl() const {
5720 return NumProtocols;
5721 }
5722
5723 void setNumProtocolsImpl(unsigned N) {
5724 NumProtocols = N;
5725 }
5726
5727 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5728 QualType can,
5729 ArrayRef<ObjCProtocolDecl *> protocols);
5730
5731public:
5732 bool isSugared() const { return true; }
5733 QualType desugar() const { return getCanonicalTypeInternal(); }
5734
5735 static bool classof(const Type *T) {
5736 return T->getTypeClass() == ObjCTypeParam;
5737 }
5738
5739 void Profile(llvm::FoldingSetNodeID &ID);
5740 static void Profile(llvm::FoldingSetNodeID &ID,
5741 const ObjCTypeParamDecl *OTPDecl,
5742 QualType CanonicalType,
5743 ArrayRef<ObjCProtocolDecl *> protocols);
5744
5745 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5746};
5747
5748/// Represents a class type in Objective C.
5749///
5750/// Every Objective C type is a combination of a base type, a set of
5751/// type arguments (optional, for parameterized classes) and a list of
5752/// protocols.
5753///
5754/// Given the following declarations:
5755/// \code
5756/// \@class C<T>;
5757/// \@protocol P;
5758/// \endcode
5759///
5760/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5761/// with base C and no protocols.
5762///
5763/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5764/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5765/// protocol list.
5766/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5767/// and protocol list [P].
5768///
5769/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5770/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5771/// and no protocols.
5772///
5773/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5774/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5775/// this should get its own sugar class to better represent the source.
5776class ObjCObjectType : public Type,
5777 public ObjCProtocolQualifiers<ObjCObjectType> {
5778 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5779
5780 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5781 // after the ObjCObjectPointerType node.
5782 // ObjCObjectType.NumProtocols - the number of protocols stored
5783 // after the type arguments of ObjCObjectPointerType node.
5784 //
5785 // These protocols are those written directly on the type. If
5786 // protocol qualifiers ever become additive, the iterators will need
5787 // to get kindof complicated.
5788 //
5789 // In the canonical object type, these are sorted alphabetically
5790 // and uniqued.
5791
5792 /// Either a BuiltinType or an InterfaceType or sugar for either.
5793 QualType BaseType;
5794
5795 /// Cached superclass type.
5796 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5797 CachedSuperClassType;
5798
5799 QualType *getTypeArgStorage();
5800 const QualType *getTypeArgStorage() const {
5801 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5802 }
5803
5804 ObjCProtocolDecl **getProtocolStorageImpl();
5805 /// Return the number of qualifying protocols in this interface type,
5806 /// or 0 if there are none.
5807 unsigned getNumProtocolsImpl() const {
5808 return ObjCObjectTypeBits.NumProtocols;
5809 }
5810 void setNumProtocolsImpl(unsigned N) {
5811 ObjCObjectTypeBits.NumProtocols = N;
5812 }
5813
5814protected:
5815 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5816
5817 ObjCObjectType(QualType Canonical, QualType Base,
5818 ArrayRef<QualType> typeArgs,
5819 ArrayRef<ObjCProtocolDecl *> protocols,
5820 bool isKindOf);
5821
5822 ObjCObjectType(enum Nonce_ObjCInterface)
5823 : Type(ObjCInterface, QualType(), TypeDependence::None),
5824 BaseType(QualType(this_(), 0)) {
5825 ObjCObjectTypeBits.NumProtocols = 0;
5826 ObjCObjectTypeBits.NumTypeArgs = 0;
5827 ObjCObjectTypeBits.IsKindOf = 0;
5828 }
5829
5830 void computeSuperClassTypeSlow() const;
5831
5832public:
5833 /// Gets the base type of this object type. This is always (possibly
5834 /// sugar for) one of:
5835 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5836 /// user, which is a typedef for an ObjCObjectPointerType)
5837 /// - the 'Class' builtin type (same caveat)
5838 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5839 QualType getBaseType() const { return BaseType; }
5840
5841 bool isObjCId() const {
5842 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5843 }
5844
5845 bool isObjCClass() const {
5846 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5847 }
5848
5849 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5850 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5851 bool isObjCUnqualifiedIdOrClass() const {
5852 if (!qual_empty()) return false;
5853 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5854 return T->getKind() == BuiltinType::ObjCId ||
5855 T->getKind() == BuiltinType::ObjCClass;
5856 return false;
5857 }
5858 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5859 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5860
5861 /// Gets the interface declaration for this object type, if the base type
5862 /// really is an interface.
5863 ObjCInterfaceDecl *getInterface() const;
5864
5865 /// Determine whether this object type is "specialized", meaning
5866 /// that it has type arguments.
5867 bool isSpecialized() const;
5868
5869 /// Determine whether this object type was written with type arguments.
5870 bool isSpecializedAsWritten() const {
5871 return ObjCObjectTypeBits.NumTypeArgs > 0;
5872 }
5873
5874 /// Determine whether this object type is "unspecialized", meaning
5875 /// that it has no type arguments.
5876 bool isUnspecialized() const { return !isSpecialized(); }
5877
5878 /// Determine whether this object type is "unspecialized" as
5879 /// written, meaning that it has no type arguments.
5880 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5881
5882 /// Retrieve the type arguments of this object type (semantically).
5883 ArrayRef<QualType> getTypeArgs() const;
5884
5885 /// Retrieve the type arguments of this object type as they were
5886 /// written.
5887 ArrayRef<QualType> getTypeArgsAsWritten() const {
5888 return llvm::makeArrayRef(getTypeArgStorage(),
5889 ObjCObjectTypeBits.NumTypeArgs);
5890 }
5891
5892 /// Whether this is a "__kindof" type as written.
5893 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5894
5895 /// Whether this ia a "__kindof" type (semantically).
5896 bool isKindOfType() const;
5897
5898 /// Retrieve the type of the superclass of this object type.
5899 ///
5900 /// This operation substitutes any type arguments into the
5901 /// superclass of the current class type, potentially producing a
5902 /// specialization of the superclass type. Produces a null type if
5903 /// there is no superclass.
5904 QualType getSuperClassType() const {
5905 if (!CachedSuperClassType.getInt())
5906 computeSuperClassTypeSlow();
5907
5908 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 5908, __PRETTY_FUNCTION__))
;
5909 return QualType(CachedSuperClassType.getPointer(), 0);
5910 }
5911
5912 /// Strip off the Objective-C "kindof" type and (with it) any
5913 /// protocol qualifiers.
5914 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5915
5916 bool isSugared() const { return false; }
5917 QualType desugar() const { return QualType(this, 0); }
5918
5919 static bool classof(const Type *T) {
5920 return T->getTypeClass() == ObjCObject ||
5921 T->getTypeClass() == ObjCInterface;
5922 }
5923};
5924
5925/// A class providing a concrete implementation
5926/// of ObjCObjectType, so as to not increase the footprint of
5927/// ObjCInterfaceType. Code outside of ASTContext and the core type
5928/// system should not reference this type.
5929class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5930 friend class ASTContext;
5931
5932 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5933 // will need to be modified.
5934
5935 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5936 ArrayRef<QualType> typeArgs,
5937 ArrayRef<ObjCProtocolDecl *> protocols,
5938 bool isKindOf)
5939 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5940
5941public:
5942 void Profile(llvm::FoldingSetNodeID &ID);
5943 static void Profile(llvm::FoldingSetNodeID &ID,
5944 QualType Base,
5945 ArrayRef<QualType> typeArgs,
5946 ArrayRef<ObjCProtocolDecl *> protocols,
5947 bool isKindOf);
5948};
5949
5950inline QualType *ObjCObjectType::getTypeArgStorage() {
5951 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5952}
5953
5954inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5955 return reinterpret_cast<ObjCProtocolDecl**>(
5956 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5957}
5958
5959inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5960 return reinterpret_cast<ObjCProtocolDecl**>(
5961 static_cast<ObjCTypeParamType*>(this)+1);
5962}
5963
5964/// Interfaces are the core concept in Objective-C for object oriented design.
5965/// They basically correspond to C++ classes. There are two kinds of interface
5966/// types: normal interfaces like `NSString`, and qualified interfaces, which
5967/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
5968///
5969/// ObjCInterfaceType guarantees the following properties when considered
5970/// as a subtype of its superclass, ObjCObjectType:
5971/// - There are no protocol qualifiers. To reinforce this, code which
5972/// tries to invoke the protocol methods via an ObjCInterfaceType will
5973/// fail to compile.
5974/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
5975/// T->getBaseType() == QualType(T, 0).
5976class ObjCInterfaceType : public ObjCObjectType {
5977 friend class ASTContext; // ASTContext creates these.
5978 friend class ASTReader;
5979 friend class ObjCInterfaceDecl;
5980 template <class T> friend class serialization::AbstractTypeReader;
5981
5982 mutable ObjCInterfaceDecl *Decl;
5983
5984 ObjCInterfaceType(const ObjCInterfaceDecl *D)
5985 : ObjCObjectType(Nonce_ObjCInterface),
5986 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
5987
5988public:
5989 /// Get the declaration of this interface.
5990 ObjCInterfaceDecl *getDecl() const { return Decl; }
5991
5992 bool isSugared() const { return false; }
5993 QualType desugar() const { return QualType(this, 0); }
5994
5995 static bool classof(const Type *T) {
5996 return T->getTypeClass() == ObjCInterface;
5997 }
5998
5999 // Nonsense to "hide" certain members of ObjCObjectType within this
6000 // class. People asking for protocols on an ObjCInterfaceType are
6001 // not going to get what they want: ObjCInterfaceTypes are
6002 // guaranteed to have no protocols.
6003 enum {
6004 qual_iterator,
6005 qual_begin,
6006 qual_end,
6007 getNumProtocols,
6008 getProtocol
6009 };
6010};
6011
6012inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6013 QualType baseType = getBaseType();
6014 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6015 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6016 return T->getDecl();
6017
6018 baseType = ObjT->getBaseType();
6019 }
6020
6021 return nullptr;
6022}
6023
6024/// Represents a pointer to an Objective C object.
6025///
6026/// These are constructed from pointer declarators when the pointee type is
6027/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6028/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6029/// and 'Class<P>' are translated into these.
6030///
6031/// Pointers to pointers to Objective C objects are still PointerTypes;
6032/// only the first level of pointer gets it own type implementation.
6033class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6034 friend class ASTContext; // ASTContext creates these.
6035
6036 QualType PointeeType;
6037
6038 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6039 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6040 PointeeType(Pointee) {}
6041
6042public:
6043 /// Gets the type pointed to by this ObjC pointer.
6044 /// The result will always be an ObjCObjectType or sugar thereof.
6045 QualType getPointeeType() const { return PointeeType; }
6046
6047 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6048 ///
6049 /// This method is equivalent to getPointeeType() except that
6050 /// it discards any typedefs (or other sugar) between this
6051 /// type and the "outermost" object type. So for:
6052 /// \code
6053 /// \@class A; \@protocol P; \@protocol Q;
6054 /// typedef A<P> AP;
6055 /// typedef A A1;
6056 /// typedef A1<P> A1P;
6057 /// typedef A1P<Q> A1PQ;
6058 /// \endcode
6059 /// For 'A*', getObjectType() will return 'A'.
6060 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6061 /// For 'AP*', getObjectType() will return 'A<P>'.
6062 /// For 'A1*', getObjectType() will return 'A'.
6063 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6064 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6065 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6066 /// adding protocols to a protocol-qualified base discards the
6067 /// old qualifiers (for now). But if it didn't, getObjectType()
6068 /// would return 'A1P<Q>' (and we'd have to make iterating over
6069 /// qualifiers more complicated).
6070 const ObjCObjectType *getObjectType() const {
6071 return PointeeType->castAs<ObjCObjectType>();
6072 }
6073
6074 /// If this pointer points to an Objective C
6075 /// \@interface type, gets the type for that interface. Any protocol
6076 /// qualifiers on the interface are ignored.
6077 ///
6078 /// \return null if the base type for this pointer is 'id' or 'Class'
6079 const ObjCInterfaceType *getInterfaceType() const;
6080
6081 /// If this pointer points to an Objective \@interface
6082 /// type, gets the declaration for that interface.
6083 ///
6084 /// \return null if the base type for this pointer is 'id' or 'Class'
6085 ObjCInterfaceDecl *getInterfaceDecl() const {
6086 return getObjectType()->getInterface();
6087 }
6088
6089 /// True if this is equivalent to the 'id' type, i.e. if
6090 /// its object type is the primitive 'id' type with no protocols.
6091 bool isObjCIdType() const {
6092 return getObjectType()->isObjCUnqualifiedId();
6093 }
6094
6095 /// True if this is equivalent to the 'Class' type,
6096 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6097 bool isObjCClassType() const {
6098 return getObjectType()->isObjCUnqualifiedClass();
6099 }
6100
6101 /// True if this is equivalent to the 'id' or 'Class' type,
6102 bool isObjCIdOrClassType() const {
6103 return getObjectType()->isObjCUnqualifiedIdOrClass();
6104 }
6105
6106 /// True if this is equivalent to 'id<P>' for some non-empty set of
6107 /// protocols.
6108 bool isObjCQualifiedIdType() const {
6109 return getObjectType()->isObjCQualifiedId();
6110 }
6111
6112 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6113 /// protocols.
6114 bool isObjCQualifiedClassType() const {
6115 return getObjectType()->isObjCQualifiedClass();
6116 }
6117
6118 /// Whether this is a "__kindof" type.
6119 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6120
6121 /// Whether this type is specialized, meaning that it has type arguments.
6122 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6123
6124 /// Whether this type is specialized, meaning that it has type arguments.
6125 bool isSpecializedAsWritten() const {
6126 return getObjectType()->isSpecializedAsWritten();
6127 }
6128
6129 /// Whether this type is unspecialized, meaning that is has no type arguments.
6130 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6131
6132 /// Determine whether this object type is "unspecialized" as
6133 /// written, meaning that it has no type arguments.
6134 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6135
6136 /// Retrieve the type arguments for this type.
6137 ArrayRef<QualType> getTypeArgs() const {
6138 return getObjectType()->getTypeArgs();
6139 }
6140
6141 /// Retrieve the type arguments for this type.
6142 ArrayRef<QualType> getTypeArgsAsWritten() const {
6143 return getObjectType()->getTypeArgsAsWritten();
6144 }
6145
6146 /// An iterator over the qualifiers on the object type. Provided
6147 /// for convenience. This will always iterate over the full set of
6148 /// protocols on a type, not just those provided directly.
6149 using qual_iterator = ObjCObjectType::qual_iterator;
6150 using qual_range = llvm::iterator_range<qual_iterator>;
6151
6152 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6153
6154 qual_iterator qual_begin() const {
6155 return getObjectType()->qual_begin();
6156 }
6157
6158 qual_iterator qual_end() const {
6159 return getObjectType()->qual_end();
6160 }
6161
6162 bool qual_empty() const { return getObjectType()->qual_empty(); }
6163
6164 /// Return the number of qualifying protocols on the object type.
6165 unsigned getNumProtocols() const {
6166 return getObjectType()->getNumProtocols();
6167 }
6168
6169 /// Retrieve a qualifying protocol by index on the object type.
6170 ObjCProtocolDecl *getProtocol(unsigned I) const {
6171 return getObjectType()->getProtocol(I);
6172 }
6173
6174 bool isSugared() const { return false; }
6175 QualType desugar() const { return QualType(this, 0); }
6176
6177 /// Retrieve the type of the superclass of this object pointer type.
6178 ///
6179 /// This operation substitutes any type arguments into the
6180 /// superclass of the current class type, potentially producing a
6181 /// pointer to a specialization of the superclass type. Produces a
6182 /// null type if there is no superclass.
6183 QualType getSuperClassType() const;
6184
6185 /// Strip off the Objective-C "kindof" type and (with it) any
6186 /// protocol qualifiers.
6187 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6188 const ASTContext &ctx) const;
6189
6190 void Profile(llvm::FoldingSetNodeID &ID) {
6191 Profile(ID, getPointeeType());
6192 }
6193
6194 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6195 ID.AddPointer(T.getAsOpaquePtr());
6196 }
6197
6198 static bool classof(const Type *T) {
6199 return T->getTypeClass() == ObjCObjectPointer;
6200 }
6201};
6202
6203class AtomicType : public Type, public llvm::FoldingSetNode {
6204 friend class ASTContext; // ASTContext creates these.
6205
6206 QualType ValueType;
6207
6208 AtomicType(QualType ValTy, QualType Canonical)
6209 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6210
6211public:
6212 /// Gets the type contained by this atomic type, i.e.
6213 /// the type returned by performing an atomic load of this atomic type.
6214 QualType getValueType() const { return ValueType; }
6215
6216 bool isSugared() const { return false; }
6217 QualType desugar() const { return QualType(this, 0); }
6218
6219 void Profile(llvm::FoldingSetNodeID &ID) {
6220 Profile(ID, getValueType());
6221 }
6222
6223 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6224 ID.AddPointer(T.getAsOpaquePtr());
6225 }
6226
6227 static bool classof(const Type *T) {
6228 return T->getTypeClass() == Atomic;
6229 }
6230};
6231
6232/// PipeType - OpenCL20.
6233class PipeType : public Type, public llvm::FoldingSetNode {
6234 friend class ASTContext; // ASTContext creates these.
6235
6236 QualType ElementType;
6237 bool isRead;
6238
6239 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6240 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6241 ElementType(elemType), isRead(isRead) {}
6242
6243public:
6244 QualType getElementType() const { return ElementType; }
6245
6246 bool isSugared() const { return false; }
6247
6248 QualType desugar() const { return QualType(this, 0); }
6249
6250 void Profile(llvm::FoldingSetNodeID &ID) {
6251 Profile(ID, getElementType(), isReadOnly());
6252 }
6253
6254 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6255 ID.AddPointer(T.getAsOpaquePtr());
6256 ID.AddBoolean(isRead);
6257 }
6258
6259 static bool classof(const Type *T) {
6260 return T->getTypeClass() == Pipe;
6261 }
6262
6263 bool isReadOnly() const { return isRead; }
6264};
6265
6266/// A fixed int type of a specified bitwidth.
6267class ExtIntType final : public Type, public llvm::FoldingSetNode {
6268 friend class ASTContext;
6269 unsigned IsUnsigned : 1;
6270 unsigned NumBits : 24;
6271
6272protected:
6273 ExtIntType(bool isUnsigned, unsigned NumBits);
6274
6275public:
6276 bool isUnsigned() const { return IsUnsigned; }
6277 bool isSigned() const { return !IsUnsigned; }
6278 unsigned getNumBits() const { return NumBits; }
6279
6280 bool isSugared() const { return false; }
6281 QualType desugar() const { return QualType(this, 0); }
6282
6283 void Profile(llvm::FoldingSetNodeID &ID) {
6284 Profile(ID, isUnsigned(), getNumBits());
6285 }
6286
6287 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6288 unsigned NumBits) {
6289 ID.AddBoolean(IsUnsigned);
6290 ID.AddInteger(NumBits);
6291 }
6292
6293 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; }
6294};
6295
6296class DependentExtIntType final : public Type, public llvm::FoldingSetNode {
6297 friend class ASTContext;
6298 const ASTContext &Context;
6299 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6300
6301protected:
6302 DependentExtIntType(const ASTContext &Context, bool IsUnsigned,
6303 Expr *NumBits);
6304
6305public:
6306 bool isUnsigned() const;
6307 bool isSigned() const { return !isUnsigned(); }
6308 Expr *getNumBitsExpr() const;
6309
6310 bool isSugared() const { return false; }
6311 QualType desugar() const { return QualType(this, 0); }
6312
6313 void Profile(llvm::FoldingSetNodeID &ID) {
6314 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6315 }
6316 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6317 bool IsUnsigned, Expr *NumBitsExpr);
6318
6319 static bool classof(const Type *T) {
6320 return T->getTypeClass() == DependentExtInt;
6321 }
6322};
6323
6324/// A qualifier set is used to build a set of qualifiers.
6325class QualifierCollector : public Qualifiers {
6326public:
6327 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6328
6329 /// Collect any qualifiers on the given type and return an
6330 /// unqualified type. The qualifiers are assumed to be consistent
6331 /// with those already in the type.
6332 const Type *strip(QualType type) {
6333 addFastQualifiers(type.getLocalFastQualifiers());
6334 if (!type.hasLocalNonFastQualifiers())
6335 return type.getTypePtrUnsafe();
6336
6337 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6338 addConsistentQualifiers(extQuals->getQualifiers());
6339 return extQuals->getBaseType();
6340 }
6341
6342 /// Apply the collected qualifiers to the given type.
6343 QualType apply(const ASTContext &Context, QualType QT) const;
6344
6345 /// Apply the collected qualifiers to the given type.
6346 QualType apply(const ASTContext &Context, const Type* T) const;
6347};
6348
6349/// A container of type source information.
6350///
6351/// A client can read the relevant info using TypeLoc wrappers, e.g:
6352/// @code
6353/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6354/// TL.getBeginLoc().print(OS, SrcMgr);
6355/// @endcode
6356class alignas(8) TypeSourceInfo {
6357 // Contains a memory block after the class, used for type source information,
6358 // allocated by ASTContext.
6359 friend class ASTContext;
6360
6361 QualType Ty;
6362
6363 TypeSourceInfo(QualType ty) : Ty(ty) {}
6364
6365public:
6366 /// Return the type wrapped by this type source info.
6367 QualType getType() const { return Ty; }
6368
6369 /// Return the TypeLoc wrapper for the type source info.
6370 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6371
6372 /// Override the type stored in this TypeSourceInfo. Use with caution!
6373 void overrideType(QualType T) { Ty = T; }
6374};
6375
6376// Inline function definitions.
6377
6378inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6379 SplitQualType desugar =
6380 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6381 desugar.Quals.addConsistentQualifiers(Quals);
6382 return desugar;
6383}
6384
6385inline const Type *QualType::getTypePtr() const {
6386 return getCommonPtr()->BaseType;
6387}
6388
6389inline const Type *QualType::getTypePtrOrNull() const {
6390 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6391}
6392
6393inline SplitQualType QualType::split() const {
6394 if (!hasLocalNonFastQualifiers())
6395 return SplitQualType(getTypePtrUnsafe(),
6396 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6397
6398 const ExtQuals *eq = getExtQualsUnsafe();
6399 Qualifiers qs = eq->getQualifiers();
6400 qs.addFastQualifiers(getLocalFastQualifiers());
6401 return SplitQualType(eq->getBaseType(), qs);
6402}
6403
6404inline Qualifiers QualType::getLocalQualifiers() const {
6405 Qualifiers Quals;
6406 if (hasLocalNonFastQualifiers())
6407 Quals = getExtQualsUnsafe()->getQualifiers();
6408 Quals.addFastQualifiers(getLocalFastQualifiers());
6409 return Quals;
6410}
6411
6412inline Qualifiers QualType::getQualifiers() const {
6413 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6414 quals.addFastQualifiers(getLocalFastQualifiers());
6415 return quals;
6416}
6417
6418inline unsigned QualType::getCVRQualifiers() const {
6419 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6420 cvr |= getLocalCVRQualifiers();
6421 return cvr;
6422}
6423
6424inline QualType QualType::getCanonicalType() const {
6425 QualType canon = getCommonPtr()->CanonicalType;
6426 return canon.withFastQualifiers(getLocalFastQualifiers());
6427}
6428
6429inline bool QualType::isCanonical() const {
6430 return getTypePtr()->isCanonicalUnqualified();
6431}
6432
6433inline bool QualType::isCanonicalAsParam() const {
6434 if (!isCanonical()) return false;
6435 if (hasLocalQualifiers()) return false;
6436
6437 const Type *T = getTypePtr();
6438 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6439 return false;
6440
6441 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6442}
6443
6444inline bool QualType::isConstQualified() const {
6445 return isLocalConstQualified() ||
6446 getCommonPtr()->CanonicalType.isLocalConstQualified();
6447}
6448
6449inline bool QualType::isRestrictQualified() const {
6450 return isLocalRestrictQualified() ||
6451 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6452}
6453
6454
6455inline bool QualType::isVolatileQualified() const {
6456 return isLocalVolatileQualified() ||
6457 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6458}
6459
6460inline bool QualType::hasQualifiers() const {
6461 return hasLocalQualifiers() ||
6462 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6463}
6464
6465inline QualType QualType::getUnqualifiedType() const {
6466 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6467 return QualType(getTypePtr(), 0);
6468
6469 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6470}
6471
6472inline SplitQualType QualType::getSplitUnqualifiedType() const {
6473 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6474 return split();
6475
6476 return getSplitUnqualifiedTypeImpl(*this);
6477}
6478
6479inline void QualType::removeLocalConst() {
6480 removeLocalFastQualifiers(Qualifiers::Const);
6481}
6482
6483inline void QualType::removeLocalRestrict() {
6484 removeLocalFastQualifiers(Qualifiers::Restrict);
6485}
6486
6487inline void QualType::removeLocalVolatile() {
6488 removeLocalFastQualifiers(Qualifiers::Volatile);
6489}
6490
6491inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6492 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 6492, __PRETTY_FUNCTION__))
;
6493 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6494 "Fast bits differ from CVR bits!");
6495
6496 // Fast path: we don't need to touch the slow qualifiers.
6497 removeLocalFastQualifiers(Mask);
6498}
6499
6500/// Check if this type has any address space qualifier.
6501inline bool QualType::hasAddressSpace() const {
6502 return getQualifiers().hasAddressSpace();
6503}
6504
6505/// Return the address space of this type.
6506inline LangAS QualType::getAddressSpace() const {
6507 return getQualifiers().getAddressSpace();
6508}
6509
6510/// Return the gc attribute of this type.
6511inline Qualifiers::GC QualType::getObjCGCAttr() const {
6512 return getQualifiers().getObjCGCAttr();
6513}
6514
6515inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6516 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6517 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6518 return false;
6519}
6520
6521inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6522 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6523 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6524 return false;
6525}
6526
6527inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6528 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6529 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6530 return false;
6531}
6532
6533inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6534 if (const auto *PT = t.getAs<PointerType>()) {
6535 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6536 return FT->getExtInfo();
6537 } else if (const auto *FT = t.getAs<FunctionType>())
6538 return FT->getExtInfo();
6539
6540 return FunctionType::ExtInfo();
6541}
6542
6543inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6544 return getFunctionExtInfo(*t);
6545}
6546
6547/// Determine whether this type is more
6548/// qualified than the Other type. For example, "const volatile int"
6549/// is more qualified than "const int", "volatile int", and
6550/// "int". However, it is not more qualified than "const volatile
6551/// int".
6552inline bool QualType::isMoreQualifiedThan(QualType other) const {
6553 Qualifiers MyQuals = getQualifiers();
6554 Qualifiers OtherQuals = other.getQualifiers();
6555 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6556}
6557
6558/// Determine whether this type is at last
6559/// as qualified as the Other type. For example, "const volatile
6560/// int" is at least as qualified as "const int", "volatile int",
6561/// "int", and "const volatile int".
6562inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6563 Qualifiers OtherQuals = other.getQualifiers();
6564
6565 // Ignore __unaligned qualifier if this type is a void.
6566 if (getUnqualifiedType()->isVoidType())
6567 OtherQuals.removeUnaligned();
6568
6569 return getQualifiers().compatiblyIncludes(OtherQuals);
6570}
6571
6572/// If Type is a reference type (e.g., const
6573/// int&), returns the type that the reference refers to ("const
6574/// int"). Otherwise, returns the type itself. This routine is used
6575/// throughout Sema to implement C++ 5p6:
6576///
6577/// If an expression initially has the type "reference to T" (8.3.2,
6578/// 8.5.3), the type is adjusted to "T" prior to any further
6579/// analysis, the expression designates the object or function
6580/// denoted by the reference, and the expression is an lvalue.
6581inline QualType QualType::getNonReferenceType() const {
6582 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6583 return RefType->getPointeeType();
6584 else
6585 return *this;
6586}
6587
6588inline bool QualType::isCForbiddenLValueType() const {
6589 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6590 getTypePtr()->isFunctionType());
6591}
6592
6593/// Tests whether the type is categorized as a fundamental type.
6594///
6595/// \returns True for types specified in C++0x [basic.fundamental].
6596inline bool Type::isFundamentalType() const {
6597 return isVoidType() ||
6598 isNullPtrType() ||
6599 // FIXME: It's really annoying that we don't have an
6600 // 'isArithmeticType()' which agrees with the standard definition.
6601 (isArithmeticType() && !isEnumeralType());
6602}
6603
6604/// Tests whether the type is categorized as a compound type.
6605///
6606/// \returns True for types specified in C++0x [basic.compound].
6607inline bool Type::isCompoundType() const {
6608 // C++0x [basic.compound]p1:
6609 // Compound types can be constructed in the following ways:
6610 // -- arrays of objects of a given type [...];
6611 return isArrayType() ||
6612 // -- functions, which have parameters of given types [...];
6613 isFunctionType() ||
6614 // -- pointers to void or objects or functions [...];
6615 isPointerType() ||
6616 // -- references to objects or functions of a given type. [...]
6617 isReferenceType() ||
6618 // -- classes containing a sequence of objects of various types, [...];
6619 isRecordType() ||
6620 // -- unions, which are classes capable of containing objects of different
6621 // types at different times;
6622 isUnionType() ||
6623 // -- enumerations, which comprise a set of named constant values. [...];
6624 isEnumeralType() ||
6625 // -- pointers to non-static class members, [...].
6626 isMemberPointerType();
6627}
6628
6629inline bool Type::isFunctionType() const {
6630 return isa<FunctionType>(CanonicalType);
6631}
6632
6633inline bool Type::isPointerType() const {
6634 return isa<PointerType>(CanonicalType);
6635}
6636
6637inline bool Type::isAnyPointerType() const {
6638 return isPointerType() || isObjCObjectPointerType();
6639}
6640
6641inline bool Type::isBlockPointerType() const {
6642 return isa<BlockPointerType>(CanonicalType);
6643}
6644
6645inline bool Type::isReferenceType() const {
6646 return isa<ReferenceType>(CanonicalType);
6647}
6648
6649inline bool Type::isLValueReferenceType() const {
6650 return isa<LValueReferenceType>(CanonicalType);
6651}
6652
6653inline bool Type::isRValueReferenceType() const {
6654 return isa<RValueReferenceType>(CanonicalType);
6655}
6656
6657inline bool Type::isObjectPointerType() const {
6658 // Note: an "object pointer type" is not the same thing as a pointer to an
6659 // object type; rather, it is a pointer to an object type or a pointer to cv
6660 // void.
6661 if (const auto *T = getAs<PointerType>())
6662 return !T->getPointeeType()->isFunctionType();
6663 else
6664 return false;
6665}
6666
6667inline bool Type::isFunctionPointerType() const {
6668 if (const auto *T = getAs<PointerType>())
6669 return T->getPointeeType()->isFunctionType();
6670 else
6671 return false;
6672}
6673
6674inline bool Type::isFunctionReferenceType() const {
6675 if (const auto *T = getAs<ReferenceType>())
6676 return T->getPointeeType()->isFunctionType();
6677 else
6678 return false;
6679}
6680
6681inline bool Type::isMemberPointerType() const {
6682 return isa<MemberPointerType>(CanonicalType);
6683}
6684
6685inline bool Type::isMemberFunctionPointerType() const {
6686 if (const auto *T = getAs<MemberPointerType>())
6687 return T->isMemberFunctionPointer();
6688 else
6689 return false;
6690}
6691
6692inline bool Type::isMemberDataPointerType() const {
6693 if (const auto *T = getAs<MemberPointerType>())
6694 return T->isMemberDataPointer();
6695 else
6696 return false;
6697}
6698
6699inline bool Type::isArrayType() const {
6700 return isa<ArrayType>(CanonicalType);
6701}
6702
6703inline bool Type::isConstantArrayType() const {
6704 return isa<ConstantArrayType>(CanonicalType);
6705}
6706
6707inline bool Type::isIncompleteArrayType() const {
6708 return isa<IncompleteArrayType>(CanonicalType);
6709}
6710
6711inline bool Type::isVariableArrayType() const {
6712 return isa<VariableArrayType>(CanonicalType);
6713}
6714
6715inline bool Type::isDependentSizedArrayType() const {
6716 return isa<DependentSizedArrayType>(CanonicalType);
6717}
6718
6719inline bool Type::isBuiltinType() const {
6720 return isa<BuiltinType>(CanonicalType);
6721}
6722
6723inline bool Type::isRecordType() const {
6724 return isa<RecordType>(CanonicalType);
6725}
6726
6727inline bool Type::isEnumeralType() const {
6728 return isa<EnumType>(CanonicalType);
6729}
6730
6731inline bool Type::isAnyComplexType() const {
6732 return isa<ComplexType>(CanonicalType);
6733}
6734
6735inline bool Type::isVectorType() const {
6736 return isa<VectorType>(CanonicalType);
6737}
6738
6739inline bool Type::isExtVectorType() const {
6740 return isa<ExtVectorType>(CanonicalType);
6741}
6742
6743inline bool Type::isMatrixType() const {
6744 return isa<MatrixType>(CanonicalType);
6745}
6746
6747inline bool Type::isConstantMatrixType() const {
6748 return isa<ConstantMatrixType>(CanonicalType);
6749}
6750
6751inline bool Type::isDependentAddressSpaceType() const {
6752 return isa<DependentAddressSpaceType>(CanonicalType);
6753}
6754
6755inline bool Type::isObjCObjectPointerType() const {
6756 return isa<ObjCObjectPointerType>(CanonicalType);
6757}
6758
6759inline bool Type::isObjCObjectType() const {
6760 return isa<ObjCObjectType>(CanonicalType);
6761}
6762
6763inline bool Type::isObjCObjectOrInterfaceType() const {
6764 return isa<ObjCInterfaceType>(CanonicalType) ||
6765 isa<ObjCObjectType>(CanonicalType);
6766}
6767
6768inline bool Type::isAtomicType() const {
6769 return isa<AtomicType>(CanonicalType);
6770}
6771
6772inline bool Type::isUndeducedAutoType() const {
6773 return isa<AutoType>(CanonicalType);
6774}
6775
6776inline bool Type::isObjCQualifiedIdType() const {
6777 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6778 return OPT->isObjCQualifiedIdType();
6779 return false;
6780}
6781
6782inline bool Type::isObjCQualifiedClassType() const {
6783 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6784 return OPT->isObjCQualifiedClassType();
6785 return false;
6786}
6787
6788inline bool Type::isObjCIdType() const {
6789 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6790 return OPT->isObjCIdType();
6791 return false;
6792}
6793
6794inline bool Type::isObjCClassType() const {
6795 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6796 return OPT->isObjCClassType();
6797 return false;
6798}
6799
6800inline bool Type::isObjCSelType() const {
6801 if (const auto *OPT = getAs<PointerType>())
6802 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6803 return false;
6804}
6805
6806inline bool Type::isObjCBuiltinType() const {
6807 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6808}
6809
6810inline bool Type::isDecltypeType() const {
6811 return isa<DecltypeType>(this);
6812}
6813
6814#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6815 inline bool Type::is##Id##Type() const { \
6816 return isSpecificBuiltinType(BuiltinType::Id); \
6817 }
6818#include "clang/Basic/OpenCLImageTypes.def"
6819
6820inline bool Type::isSamplerT() const {
6821 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6822}
6823
6824inline bool Type::isEventT() const {
6825 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6826}
6827
6828inline bool Type::isClkEventT() const {
6829 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6830}
6831
6832inline bool Type::isQueueT() const {
6833 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6834}
6835
6836inline bool Type::isReserveIDT() const {
6837 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6838}
6839
6840inline bool Type::isImageType() const {
6841#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6842 return
6843#include "clang/Basic/OpenCLImageTypes.def"
6844 false; // end boolean or operation
6845}
6846
6847inline bool Type::isPipeType() const {
6848 return isa<PipeType>(CanonicalType);
6849}
6850
6851inline bool Type::isExtIntType() const {
6852 return isa<ExtIntType>(CanonicalType);
6853}
6854
6855#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6856 inline bool Type::is##Id##Type() const { \
6857 return isSpecificBuiltinType(BuiltinType::Id); \
6858 }
6859#include "clang/Basic/OpenCLExtensionTypes.def"
6860
6861inline bool Type::isOCLIntelSubgroupAVCType() const {
6862#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6863 isOCLIntelSubgroupAVC##Id##Type() ||
6864 return
6865#include "clang/Basic/OpenCLExtensionTypes.def"
6866 false; // end of boolean or operation
6867}
6868
6869inline bool Type::isOCLExtOpaqueType() const {
6870#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6871 return
6872#include "clang/Basic/OpenCLExtensionTypes.def"
6873 false; // end of boolean or operation
6874}
6875
6876inline bool Type::isOpenCLSpecificType() const {
6877 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6878 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6879}
6880
6881inline bool Type::isTemplateTypeParmType() const {
6882 return isa<TemplateTypeParmType>(CanonicalType);
6883}
6884
6885inline bool Type::isSpecificBuiltinType(unsigned K) const {
6886 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6887 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6888 }
6889 return false;
6890}
6891
6892inline bool Type::isPlaceholderType() const {
6893 if (const auto *BT = dyn_cast<BuiltinType>(this))
6894 return BT->isPlaceholderType();
6895 return false;
6896}
6897
6898inline const BuiltinType *Type::getAsPlaceholderType() const {
6899 if (const auto *BT = dyn_cast<BuiltinType>(this))
6900 if (BT->isPlaceholderType())
6901 return BT;
6902 return nullptr;
6903}
6904
6905inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6906 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 6906, __PRETTY_FUNCTION__))
;
6907 return isSpecificBuiltinType(K);
6908}
6909
6910inline bool Type::isNonOverloadPlaceholderType() const {
6911 if (const auto *BT = dyn_cast<BuiltinType>(this))
6912 return BT->isNonOverloadPlaceholderType();
6913 return false;
6914}
6915
6916inline bool Type::isVoidType() const {
6917 return isSpecificBuiltinType(BuiltinType::Void);
6918}
6919
6920inline bool Type::isHalfType() const {
6921 // FIXME: Should we allow complex __fp16? Probably not.
6922 return isSpecificBuiltinType(BuiltinType::Half);
6923}
6924
6925inline bool Type::isFloat16Type() const {
6926 return isSpecificBuiltinType(BuiltinType::Float16);
6927}
6928
6929inline bool Type::isBFloat16Type() const {
6930 return isSpecificBuiltinType(BuiltinType::BFloat16);
6931}
6932
6933inline bool Type::isFloat128Type() const {
6934 return isSpecificBuiltinType(BuiltinType::Float128);
6935}
6936
6937inline bool Type::isNullPtrType() const {
6938 return isSpecificBuiltinType(BuiltinType::NullPtr);
6939}
6940
6941bool IsEnumDeclComplete(EnumDecl *);
6942bool IsEnumDeclScoped(EnumDecl *);
6943
6944inline bool Type::isIntegerType() const {
6945 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6946 return BT->getKind() >= BuiltinType::Bool &&
6947 BT->getKind() <= BuiltinType::Int128;
6948 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6949 // Incomplete enum types are not treated as integer types.
6950 // FIXME: In C++, enum types are never integer types.
6951 return IsEnumDeclComplete(ET->getDecl()) &&
6952 !IsEnumDeclScoped(ET->getDecl());
6953 }
6954 return isExtIntType();
6955}
6956
6957inline bool Type::isFixedPointType() const {
6958 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6959 return BT->getKind() >= BuiltinType::ShortAccum &&
6960 BT->getKind() <= BuiltinType::SatULongFract;
6961 }
6962 return false;
6963}
6964
6965inline bool Type::isFixedPointOrIntegerType() const {
6966 return isFixedPointType() || isIntegerType();
6967}
6968
6969inline bool Type::isSaturatedFixedPointType() const {
6970 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6971 return BT->getKind() >= BuiltinType::SatShortAccum &&
6972 BT->getKind() <= BuiltinType::SatULongFract;
6973 }
6974 return false;
6975}
6976
6977inline bool Type::isUnsaturatedFixedPointType() const {
6978 return isFixedPointType() && !isSaturatedFixedPointType();
6979}
6980
6981inline bool Type::isSignedFixedPointType() const {
6982 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6983 return ((BT->getKind() >= BuiltinType::ShortAccum &&
6984 BT->getKind() <= BuiltinType::LongAccum) ||
6985 (BT->getKind() >= BuiltinType::ShortFract &&
6986 BT->getKind() <= BuiltinType::LongFract) ||
6987 (BT->getKind() >= BuiltinType::SatShortAccum &&
6988 BT->getKind() <= BuiltinType::SatLongAccum) ||
6989 (BT->getKind() >= BuiltinType::SatShortFract &&
6990 BT->getKind() <= BuiltinType::SatLongFract));
6991 }
6992 return false;
6993}
6994
6995inline bool Type::isUnsignedFixedPointType() const {
6996 return isFixedPointType() && !isSignedFixedPointType();
6997}
6998
6999inline bool Type::isScalarType() const {
7000 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7001 return BT->getKind() > BuiltinType::Void &&
7002 BT->getKind() <= BuiltinType::NullPtr;
7003 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7004 // Enums are scalar types, but only if they are defined. Incomplete enums
7005 // are not treated as scalar types.
7006 return IsEnumDeclComplete(ET->getDecl());
7007 return isa<PointerType>(CanonicalType) ||
7008 isa<BlockPointerType>(CanonicalType) ||
7009 isa<MemberPointerType>(CanonicalType) ||
7010 isa<ComplexType>(CanonicalType) ||
7011 isa<ObjCObjectPointerType>(CanonicalType) ||
7012 isExtIntType();
7013}
7014
7015inline bool Type::isIntegralOrEnumerationType() const {
7016 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7017 return BT->getKind() >= BuiltinType::Bool &&
7018 BT->getKind() <= BuiltinType::Int128;
7019
7020 // Check for a complete enum type; incomplete enum types are not properly an
7021 // enumeration type in the sense required here.
7022 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7023 return IsEnumDeclComplete(ET->getDecl());
7024
7025 return isExtIntType();
7026}
7027
7028inline bool Type::isBooleanType() const {
7029 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7030 return BT->getKind() == BuiltinType::Bool;
7031 return false;
7032}
7033
7034inline bool Type::isUndeducedType() const {
7035 auto *DT = getContainedDeducedType();
7036 return DT && !DT->isDeduced();
9
Assuming 'DT' is non-null
10
Assuming the condition is true
11
Returning the value 1, which participates in a condition later
7037}
7038
7039/// Determines whether this is a type for which one can define
7040/// an overloaded operator.
7041inline bool Type::isOverloadableType() const {
7042 return isDependentType() || isRecordType() || isEnumeralType();
7043}
7044
7045/// Determines whether this type can decay to a pointer type.
7046inline bool Type::canDecayToPointerType() const {
7047 return isFunctionType() || isArrayType();
7048}
7049
7050inline bool Type::hasPointerRepresentation() const {
7051 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7052 isObjCObjectPointerType() || isNullPtrType());
7053}
7054
7055inline bool Type::hasObjCPointerRepresentation() const {
7056 return isObjCObjectPointerType();
7057}
7058
7059inline const Type *Type::getBaseElementTypeUnsafe() const {
7060 const Type *type = this;
7061 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7062 type = arrayType->getElementType().getTypePtr();
7063 return type;
7064}
7065
7066inline const Type *Type::getPointeeOrArrayElementType() const {
7067 const Type *type = this;
7068 if (type->isAnyPointerType())
7069 return type->getPointeeType().getTypePtr();
7070 else if (type->isArrayType())
7071 return type->getBaseElementTypeUnsafe();
7072 return type;
7073}
7074/// Insertion operator for diagnostics. This allows sending address spaces into
7075/// a diagnostic with <<.
7076inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
7077 LangAS AS) {
7078 DB.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7079 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7080 return DB;
7081}
7082
7083/// Insertion operator for partial diagnostics. This allows sending adress
7084/// spaces into a diagnostic with <<.
7085inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
7086 LangAS AS) {
7087 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7088 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7089 return PD;
7090}
7091
7092/// Insertion operator for diagnostics. This allows sending Qualifiers into a
7093/// diagnostic with <<.
7094inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
7095 Qualifiers Q) {
7096 DB.AddTaggedVal(Q.getAsOpaqueValue(),
7097 DiagnosticsEngine::ArgumentKind::ak_qual);
7098 return DB;
7099}
7100
7101/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7102/// into a diagnostic with <<.
7103inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
7104 Qualifiers Q) {
7105 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7106 DiagnosticsEngine::ArgumentKind::ak_qual);
7107 return PD;
7108}
7109
7110/// Insertion operator for diagnostics. This allows sending QualType's into a
7111/// diagnostic with <<.
7112inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
7113 QualType T) {
7114 DB.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7115 DiagnosticsEngine::ak_qualtype);
7116 return DB;
7117}
7118
7119/// Insertion operator for partial diagnostics. This allows sending QualType's
7120/// into a diagnostic with <<.
7121inline const PartialDiagnostic &operator<<(const PartialDiagnostic &PD,
7122 QualType T) {
7123 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7124 DiagnosticsEngine::ak_qualtype);
7125 return PD;
7126}
7127
7128// Helper class template that is used by Type::getAs to ensure that one does
7129// not try to look through a qualified type to get to an array type.
7130template <typename T>
7131using TypeIsArrayType =
7132 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7133 std::is_base_of<ArrayType, T>::value>;
7134
7135// Member-template getAs<specific type>'.
7136template <typename T> const T *Type::getAs() const {
7137 static_assert(!TypeIsArrayType<T>::value,
7138 "ArrayType cannot be used with getAs!");
7139
7140 // If this is directly a T type, return it.
7141 if (const auto *Ty = dyn_cast<T>(this))
7142 return Ty;
7143
7144 // If the canonical form of this type isn't the right kind, reject it.
7145 if (!isa<T>(CanonicalType))
7146 return nullptr;
7147
7148 // If this is a typedef for the type, strip the typedef off without
7149 // losing all typedef information.
7150 return cast<T>(getUnqualifiedDesugaredType());
7151}
7152
7153template <typename T> const T *Type::getAsAdjusted() const {
7154 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7155
7156 // If this is directly a T type, return it.
7157 if (const auto *Ty = dyn_cast<T>(this))
7158 return Ty;
7159
7160 // If the canonical form of this type isn't the right kind, reject it.
7161 if (!isa<T>(CanonicalType))
7162 return nullptr;
7163
7164 // Strip off type adjustments that do not modify the underlying nature of the
7165 // type.
7166 const Type *Ty = this;
7167 while (Ty) {
7168 if (const auto *A = dyn_cast<AttributedType>(Ty))
7169 Ty = A->getModifiedType().getTypePtr();
7170 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7171 Ty = E->desugar().getTypePtr();
7172 else if (const auto *P = dyn_cast<ParenType>(Ty))
7173 Ty = P->desugar().getTypePtr();
7174 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7175 Ty = A->desugar().getTypePtr();
7176 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7177 Ty = M->desugar().getTypePtr();
7178 else
7179 break;
7180 }
7181
7182 // Just because the canonical type is correct does not mean we can use cast<>,
7183 // since we may not have stripped off all the sugar down to the base type.
7184 return dyn_cast<T>(Ty);
7185}
7186
7187inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7188 // If this is directly an array type, return it.
7189 if (const auto *arr = dyn_cast<ArrayType>(this))
7190 return arr;
7191
7192 // If the canonical form of this type isn't the right kind, reject it.
7193 if (!isa<ArrayType>(CanonicalType))
7194 return nullptr;
7195
7196 // If this is a typedef for the type, strip the typedef off without
7197 // losing all typedef information.
7198 return cast<ArrayType>(getUnqualifiedDesugaredType());
7199}
7200
7201template <typename T> const T *Type::castAs() const {
7202 static_assert(!TypeIsArrayType<T>::value,
7203 "ArrayType cannot be used with castAs!");
7204
7205 if (const auto *ty = dyn_cast<T>(this)) return ty;
7206 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 7206, __PRETTY_FUNCTION__))
;
7207 return cast<T>(getUnqualifiedDesugaredType());
7208}
7209
7210inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7211 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 7211, __PRETTY_FUNCTION__))
;
7212 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7213 return cast<ArrayType>(getUnqualifiedDesugaredType());
7214}
7215
7216DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7217 QualType CanonicalPtr)
7218 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7219#ifndef NDEBUG
7220 QualType Adjusted = getAdjustedType();
7221 (void)AttributedType::stripOuterNullability(Adjusted);
7222 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/AST/Type.h"
, 7222, __PRETTY_FUNCTION__))
;
7223#endif
7224}
7225
7226QualType DecayedType::getPointeeType() const {
7227 QualType Decayed = getDecayedType();
7228 (void)AttributedType::stripOuterNullability(Decayed);
7229 return cast<PointerType>(Decayed)->getPointeeType();
7230}
7231
7232// Get the decimal string representation of a fixed point type, represented
7233// as a scaled integer.
7234// TODO: At some point, we should change the arguments to instead just accept an
7235// APFixedPoint instead of APSInt and scale.
7236void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7237 unsigned Scale);
7238
7239} // namespace clang
7240
7241#endif // LLVM_CLANG_AST_TYPE_H

/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/Sema/Ownership.h

1//===- Ownership.h - Parser ownership helpers -------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file contains classes for managing ownership of Stmt and Expr nodes.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_SEMA_OWNERSHIP_H
14#define LLVM_CLANG_SEMA_OWNERSHIP_H
15
16#include "clang/AST/Expr.h"
17#include "clang/Basic/LLVM.h"
18#include "llvm/ADT/ArrayRef.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include "llvm/Support/type_traits.h"
21#include <cassert>
22#include <cstddef>
23#include <cstdint>
24
25//===----------------------------------------------------------------------===//
26// OpaquePtr
27//===----------------------------------------------------------------------===//
28
29namespace clang {
30
31class CXXBaseSpecifier;
32class CXXCtorInitializer;
33class Decl;
34class Expr;
35class ParsedTemplateArgument;
36class QualType;
37class Stmt;
38class TemplateName;
39class TemplateParameterList;
40
41 /// Wrapper for void* pointer.
42 /// \tparam PtrTy Either a pointer type like 'T*' or a type that behaves like
43 /// a pointer.
44 ///
45 /// This is a very simple POD type that wraps a pointer that the Parser
46 /// doesn't know about but that Sema or another client does. The PtrTy
47 /// template argument is used to make sure that "Decl" pointers are not
48 /// compatible with "Type" pointers for example.
49 template <class PtrTy>
50 class OpaquePtr {
51 void *Ptr = nullptr;
52
53 explicit OpaquePtr(void *Ptr) : Ptr(Ptr) {}
54
55 using Traits = llvm::PointerLikeTypeTraits<PtrTy>;
56
57 public:
58 OpaquePtr(std::nullptr_t = nullptr) {}
59
60 static OpaquePtr make(PtrTy P) { OpaquePtr OP; OP.set(P); return OP; }
61
62 /// Returns plain pointer to the entity pointed by this wrapper.
63 /// \tparam PointeeT Type of pointed entity.
64 ///
65 /// It is identical to getPtrAs<PointeeT*>.
66 template <typename PointeeT> PointeeT* getPtrTo() const {
67 return get();
68 }
69
70 /// Returns pointer converted to the specified type.
71 /// \tparam PtrT Result pointer type. There must be implicit conversion
72 /// from PtrTy to PtrT.
73 ///
74 /// In contrast to getPtrTo, this method allows the return type to be
75 /// a smart pointer.
76 template <typename PtrT> PtrT getPtrAs() const {
77 return get();
78 }
79
80 PtrTy get() const {
81 return Traits::getFromVoidPointer(Ptr);
82 }
83
84 void set(PtrTy P) {
85 Ptr = Traits::getAsVoidPointer(P);
86 }
87
88 explicit operator bool() const { return Ptr != nullptr; }
89
90 void *getAsOpaquePtr() const { return Ptr; }
91 static OpaquePtr getFromOpaquePtr(void *P) { return OpaquePtr(P); }
92 };
93
94 /// UnionOpaquePtr - A version of OpaquePtr suitable for membership
95 /// in a union.
96 template <class T> struct UnionOpaquePtr {
97 void *Ptr;
98
99 static UnionOpaquePtr make(OpaquePtr<T> P) {
100 UnionOpaquePtr OP = { P.getAsOpaquePtr() };
101 return OP;
102 }
103
104 OpaquePtr<T> get() const { return OpaquePtr<T>::getFromOpaquePtr(Ptr); }
105 operator OpaquePtr<T>() const { return get(); }
106
107 UnionOpaquePtr &operator=(OpaquePtr<T> P) {
108 Ptr = P.getAsOpaquePtr();
109 return *this;
110 }
111 };
112
113} // namespace clang
114
115namespace llvm {
116
117 template <class T>
118 struct PointerLikeTypeTraits<clang::OpaquePtr<T>> {
119 static constexpr int NumLowBitsAvailable = 0;
120
121 static inline void *getAsVoidPointer(clang::OpaquePtr<T> P) {
122 // FIXME: Doesn't work? return P.getAs< void >();
123 return P.getAsOpaquePtr();
124 }
125
126 static inline clang::OpaquePtr<T> getFromVoidPointer(void *P) {
127 return clang::OpaquePtr<T>::getFromOpaquePtr(P);
128 }
129 };
130
131} // namespace llvm
132
133namespace clang {
134
135 // Basic
136 class DiagnosticBuilder;
137
138 // Determines whether the low bit of the result pointer for the
139 // given UID is always zero. If so, ActionResult will use that bit
140 // for it's "invalid" flag.
141 template<class Ptr>
142 struct IsResultPtrLowBitFree {
143 static const bool value = false;
144 };
145
146 /// ActionResult - This structure is used while parsing/acting on
147 /// expressions, stmts, etc. It encapsulates both the object returned by
148 /// the action, plus a sense of whether or not it is valid.
149 /// When CompressInvalid is true, the "invalid" flag will be
150 /// stored in the low bit of the Val pointer.
151 template<class PtrTy,
152 bool CompressInvalid = IsResultPtrLowBitFree<PtrTy>::value>
153 class ActionResult {
154 PtrTy Val;
155 bool Invalid;
156
157 public:
158 ActionResult(bool Invalid = false) : Val(PtrTy()), Invalid(Invalid) {}
159 ActionResult(PtrTy val) : Val(val), Invalid(false) {}
160 ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
161
162 // These two overloads prevent void* -> bool conversions.
163 ActionResult(const void *) = delete;
164 ActionResult(volatile void *) = delete;
165
166 bool isInvalid() const { return Invalid; }
167 bool isUsable() const { return !Invalid && Val; }
168 bool isUnset() const { return !Invalid && !Val; }
169
170 PtrTy get() const { return Val; }
171 template <typename T> T *getAs() { return static_cast<T*>(get()); }
172
173 void set(PtrTy V) { Val = V; }
174
175 const ActionResult &operator=(PtrTy RHS) {
176 Val = RHS;
177 Invalid = false;
178 return *this;
179 }
180 };
181
182 // This ActionResult partial specialization places the "invalid"
183 // flag into the low bit of the pointer.
184 template<typename PtrTy>
185 class ActionResult<PtrTy, true> {
186 // A pointer whose low bit is 1 if this result is invalid, 0
187 // otherwise.
188 uintptr_t PtrWithInvalid;
189
190 using PtrTraits = llvm::PointerLikeTypeTraits<PtrTy>;
191
192 public:
193 ActionResult(bool Invalid = false)
194 : PtrWithInvalid(static_cast<uintptr_t>(Invalid)) {}
195
196 ActionResult(PtrTy V) {
197 void *VP = PtrTraits::getAsVoidPointer(V);
198 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
199 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"
) ? static_cast<void> (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/Sema/Ownership.h"
, 199, __PRETTY_FUNCTION__))
;
200 }
201
202 ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) {}
203
204 // These two overloads prevent void* -> bool conversions.
205 ActionResult(const void *) = delete;
206 ActionResult(volatile void *) = delete;
207
208 bool isInvalid() const { return PtrWithInvalid & 0x01; }
209 bool isUsable() const { return PtrWithInvalid > 0x01; }
15
Assuming field 'PtrWithInvalid' is > 1
16
Returning the value 1, which participates in a condition later
210 bool isUnset() const { return PtrWithInvalid == 0; }
211
212 PtrTy get() const {
213 void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01);
214 return PtrTraits::getFromVoidPointer(VP);
215 }
216
217 template <typename T> T *getAs() { return static_cast<T*>(get()); }
218
219 void set(PtrTy V) {
220 void *VP = PtrTraits::getAsVoidPointer(V);
221 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
222 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"
) ? static_cast<void> (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/Sema/Ownership.h"
, 222, __PRETTY_FUNCTION__))
;
223 }
224
225 const ActionResult &operator=(PtrTy RHS) {
226 void *VP = PtrTraits::getAsVoidPointer(RHS);
227 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
228 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")(((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer"
) ? static_cast<void> (0) : __assert_fail ("(PtrWithInvalid & 0x01) == 0 && \"Badly aligned pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/Sema/Ownership.h"
, 228, __PRETTY_FUNCTION__))
;
229 return *this;
230 }
231
232 // For types where we can fit a flag in with the pointer, provide
233 // conversions to/from pointer type.
234 static ActionResult getFromOpaquePointer(void *P) {
235 ActionResult Result;
236 Result.PtrWithInvalid = (uintptr_t)P;
237 return Result;
238 }
239 void *getAsOpaquePointer() const { return (void*)PtrWithInvalid; }
240 };
241
242 /// An opaque type for threading parsed type information through the
243 /// parser.
244 using ParsedType = OpaquePtr<QualType>;
245 using UnionParsedType = UnionOpaquePtr<QualType>;
246
247 // We can re-use the low bit of expression, statement, base, and
248 // member-initializer pointers for the "invalid" flag of
249 // ActionResult.
250 template<> struct IsResultPtrLowBitFree<Expr*> {
251 static const bool value = true;
252 };
253 template<> struct IsResultPtrLowBitFree<Stmt*> {
254 static const bool value = true;
255 };
256 template<> struct IsResultPtrLowBitFree<CXXBaseSpecifier*> {
257 static const bool value = true;
258 };
259 template<> struct IsResultPtrLowBitFree<CXXCtorInitializer*> {
260 static const bool value = true;
261 };
262
263 using ExprResult = ActionResult<Expr *>;
264 using StmtResult = ActionResult<Stmt *>;
265 using TypeResult = ActionResult<ParsedType>;
266 using BaseResult = ActionResult<CXXBaseSpecifier *>;
267 using MemInitResult = ActionResult<CXXCtorInitializer *>;
268
269 using DeclResult = ActionResult<Decl *>;
270 using ParsedTemplateTy = OpaquePtr<TemplateName>;
271 using UnionParsedTemplateTy = UnionOpaquePtr<TemplateName>;
272
273 using MultiExprArg = MutableArrayRef<Expr *>;
274 using MultiStmtArg = MutableArrayRef<Stmt *>;
275 using ASTTemplateArgsPtr = MutableArrayRef<ParsedTemplateArgument>;
276 using MultiTypeArg = MutableArrayRef<ParsedType>;
277 using MultiTemplateParamsArg = MutableArrayRef<TemplateParameterList *>;
278
279 inline ExprResult ExprError() { return ExprResult(true); }
280 inline StmtResult StmtError() { return StmtResult(true); }
281 inline TypeResult TypeError() { return TypeResult(true); }
282
283 inline ExprResult ExprError(const DiagnosticBuilder&) { return ExprError(); }
284 inline StmtResult StmtError(const DiagnosticBuilder&) { return StmtError(); }
285
286 inline ExprResult ExprEmpty() { return ExprResult(false); }
287 inline StmtResult StmtEmpty() { return StmtResult(false); }
288
289 inline Expr *AssertSuccess(ExprResult R) {
290 assert(!R.isInvalid() && "operation was asserted to never fail!")((!R.isInvalid() && "operation was asserted to never fail!"
) ? static_cast<void> (0) : __assert_fail ("!R.isInvalid() && \"operation was asserted to never fail!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/Sema/Ownership.h"
, 290, __PRETTY_FUNCTION__))
;
291 return R.get();
292 }
293
294 inline Stmt *AssertSuccess(StmtResult R) {
295 assert(!R.isInvalid() && "operation was asserted to never fail!")((!R.isInvalid() && "operation was asserted to never fail!"
) ? static_cast<void> (0) : __assert_fail ("!R.isInvalid() && \"operation was asserted to never fail!\""
, "/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include/clang/Sema/Ownership.h"
, 295, __PRETTY_FUNCTION__))
;
296 return R.get();
297 }
298
299} // namespace clang
300
301#endif // LLVM_CLANG_SEMA_OWNERSHIP_H