Bug Summary

File:src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaDecl.cpp
Warning:line 11785, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -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 -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include/clang/Sema -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangSema/../include -I /usr/src/gnu/usr.bin/clang/libclangSema/obj -I /usr/src/gnu/usr.bin/clang/libclangSema/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangSema/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaDecl.cpp

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/clang/lib/Sema/SemaDecl.cpp

1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/NonTrivialTypeVisitor.h"
27#include "clang/AST/StmtCXX.h"
28#include "clang/Basic/Builtins.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/DelayedDiagnostic.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/ParsedTemplate.h"
42#include "clang/Sema/Scope.h"
43#include "clang/Sema/ScopeInfo.h"
44#include "clang/Sema/SemaInternal.h"
45#include "clang/Sema/Template.h"
46#include "llvm/ADT/SmallString.h"
47#include "llvm/ADT/Triple.h"
48#include <algorithm>
49#include <cstring>
50#include <functional>
51#include <unordered_map>
52
53using namespace clang;
54using namespace sema;
55
56Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
57 if (OwnedType) {
58 Decl *Group[2] = { OwnedType, Ptr };
59 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60 }
61
62 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63}
64
65namespace {
66
67class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68 public:
69 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70 bool AllowTemplates = false,
71 bool AllowNonTemplates = true)
72 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74 WantExpressionKeywords = false;
75 WantCXXNamedCasts = false;
76 WantRemainingKeywords = false;
77 }
78
79 bool ValidateCandidate(const TypoCorrection &candidate) override {
80 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81 if (!AllowInvalidDecl && ND->isInvalidDecl())
82 return false;
83
84 if (getAsTypeTemplateDecl(ND))
85 return AllowTemplates;
86
87 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88 if (!IsType)
89 return false;
90
91 if (AllowNonTemplates)
92 return true;
93
94 // An injected-class-name of a class template (specialization) is valid
95 // as a template or as a non-template.
96 if (AllowTemplates) {
97 auto *RD = dyn_cast<CXXRecordDecl>(ND);
98 if (!RD || !RD->isInjectedClassName())
99 return false;
100 RD = cast<CXXRecordDecl>(RD->getDeclContext());
101 return RD->getDescribedClassTemplate() ||
102 isa<ClassTemplateSpecializationDecl>(RD);
103 }
104
105 return false;
106 }
107
108 return !WantClassName && candidate.isKeyword();
109 }
110
111 std::unique_ptr<CorrectionCandidateCallback> clone() override {
112 return std::make_unique<TypeNameValidatorCCC>(*this);
113 }
114
115 private:
116 bool AllowInvalidDecl;
117 bool WantClassName;
118 bool AllowTemplates;
119 bool AllowNonTemplates;
120};
121
122} // end anonymous namespace
123
124/// Determine whether the token kind starts a simple-type-specifier.
125bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
126 switch (Kind) {
127 // FIXME: Take into account the current language when deciding whether a
128 // token kind is a valid type specifier
129 case tok::kw_short:
130 case tok::kw_long:
131 case tok::kw___int64:
132 case tok::kw___int128:
133 case tok::kw_signed:
134 case tok::kw_unsigned:
135 case tok::kw_void:
136 case tok::kw_char:
137 case tok::kw_int:
138 case tok::kw_half:
139 case tok::kw_float:
140 case tok::kw_double:
141 case tok::kw___bf16:
142 case tok::kw__Float16:
143 case tok::kw___float128:
144 case tok::kw_wchar_t:
145 case tok::kw_bool:
146 case tok::kw___underlying_type:
147 case tok::kw___auto_type:
148 return true;
149
150 case tok::annot_typename:
151 case tok::kw_char16_t:
152 case tok::kw_char32_t:
153 case tok::kw_typeof:
154 case tok::annot_decltype:
155 case tok::kw_decltype:
156 return getLangOpts().CPlusPlus;
157
158 case tok::kw_char8_t:
159 return getLangOpts().Char8;
160
161 default:
162 break;
163 }
164
165 return false;
166}
167
168namespace {
169enum class UnqualifiedTypeNameLookupResult {
170 NotFound,
171 FoundNonType,
172 FoundType
173};
174} // end anonymous namespace
175
176/// Tries to perform unqualified lookup of the type decls in bases for
177/// dependent class.
178/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
179/// type decl, \a FoundType if only type decls are found.
180static UnqualifiedTypeNameLookupResult
181lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
182 SourceLocation NameLoc,
183 const CXXRecordDecl *RD) {
184 if (!RD->hasDefinition())
185 return UnqualifiedTypeNameLookupResult::NotFound;
186 // Look for type decls in base classes.
187 UnqualifiedTypeNameLookupResult FoundTypeDecl =
188 UnqualifiedTypeNameLookupResult::NotFound;
189 for (const auto &Base : RD->bases()) {
190 const CXXRecordDecl *BaseRD = nullptr;
191 if (auto *BaseTT = Base.getType()->getAs<TagType>())
192 BaseRD = BaseTT->getAsCXXRecordDecl();
193 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
194 // Look for type decls in dependent base classes that have known primary
195 // templates.
196 if (!TST || !TST->isDependentType())
197 continue;
198 auto *TD = TST->getTemplateName().getAsTemplateDecl();
199 if (!TD)
200 continue;
201 if (auto *BasePrimaryTemplate =
202 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
203 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
204 BaseRD = BasePrimaryTemplate;
205 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
206 if (const ClassTemplatePartialSpecializationDecl *PS =
207 CTD->findPartialSpecialization(Base.getType()))
208 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
209 BaseRD = PS;
210 }
211 }
212 }
213 if (BaseRD) {
214 for (NamedDecl *ND : BaseRD->lookup(&II)) {
215 if (!isa<TypeDecl>(ND))
216 return UnqualifiedTypeNameLookupResult::FoundNonType;
217 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
218 }
219 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
220 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
221 case UnqualifiedTypeNameLookupResult::FoundNonType:
222 return UnqualifiedTypeNameLookupResult::FoundNonType;
223 case UnqualifiedTypeNameLookupResult::FoundType:
224 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
225 break;
226 case UnqualifiedTypeNameLookupResult::NotFound:
227 break;
228 }
229 }
230 }
231 }
232
233 return FoundTypeDecl;
234}
235
236static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
237 const IdentifierInfo &II,
238 SourceLocation NameLoc) {
239 // Lookup in the parent class template context, if any.
240 const CXXRecordDecl *RD = nullptr;
241 UnqualifiedTypeNameLookupResult FoundTypeDecl =
242 UnqualifiedTypeNameLookupResult::NotFound;
243 for (DeclContext *DC = S.CurContext;
244 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
245 DC = DC->getParent()) {
246 // Look for type decls in dependent base classes that have known primary
247 // templates.
248 RD = dyn_cast<CXXRecordDecl>(DC);
249 if (RD && RD->getDescribedClassTemplate())
250 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
251 }
252 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
253 return nullptr;
254
255 // We found some types in dependent base classes. Recover as if the user
256 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
257 // lookup during template instantiation.
258 S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
259
260 ASTContext &Context = S.Context;
261 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
262 cast<Type>(Context.getRecordType(RD)));
263 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
264
265 CXXScopeSpec SS;
266 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
267
268 TypeLocBuilder Builder;
269 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
270 DepTL.setNameLoc(NameLoc);
271 DepTL.setElaboratedKeywordLoc(SourceLocation());
272 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
273 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
274}
275
276/// If the identifier refers to a type name within this scope,
277/// return the declaration of that type.
278///
279/// This routine performs ordinary name lookup of the identifier II
280/// within the given scope, with optional C++ scope specifier SS, to
281/// determine whether the name refers to a type. If so, returns an
282/// opaque pointer (actually a QualType) corresponding to that
283/// type. Otherwise, returns NULL.
284ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
285 Scope *S, CXXScopeSpec *SS,
286 bool isClassName, bool HasTrailingDot,
287 ParsedType ObjectTypePtr,
288 bool IsCtorOrDtorName,
289 bool WantNontrivialTypeSourceInfo,
290 bool IsClassTemplateDeductionContext,
291 IdentifierInfo **CorrectedII) {
292 // FIXME: Consider allowing this outside C++1z mode as an extension.
293 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
294 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
295 !isClassName && !HasTrailingDot;
296
297 // Determine where we will perform name lookup.
298 DeclContext *LookupCtx = nullptr;
299 if (ObjectTypePtr) {
300 QualType ObjectType = ObjectTypePtr.get();
301 if (ObjectType->isRecordType())
302 LookupCtx = computeDeclContext(ObjectType);
303 } else if (SS && SS->isNotEmpty()) {
304 LookupCtx = computeDeclContext(*SS, false);
305
306 if (!LookupCtx) {
307 if (isDependentScopeSpecifier(*SS)) {
308 // C++ [temp.res]p3:
309 // A qualified-id that refers to a type and in which the
310 // nested-name-specifier depends on a template-parameter (14.6.2)
311 // shall be prefixed by the keyword typename to indicate that the
312 // qualified-id denotes a type, forming an
313 // elaborated-type-specifier (7.1.5.3).
314 //
315 // We therefore do not perform any name lookup if the result would
316 // refer to a member of an unknown specialization.
317 if (!isClassName && !IsCtorOrDtorName)
318 return nullptr;
319
320 // We know from the grammar that this name refers to a type,
321 // so build a dependent node to describe the type.
322 if (WantNontrivialTypeSourceInfo)
323 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
324
325 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
326 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
327 II, NameLoc);
328 return ParsedType::make(T);
329 }
330
331 return nullptr;
332 }
333
334 if (!LookupCtx->isDependentContext() &&
335 RequireCompleteDeclContext(*SS, LookupCtx))
336 return nullptr;
337 }
338
339 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
340 // lookup for class-names.
341 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
342 LookupOrdinaryName;
343 LookupResult Result(*this, &II, NameLoc, Kind);
344 if (LookupCtx) {
345 // Perform "qualified" name lookup into the declaration context we
346 // computed, which is either the type of the base of a member access
347 // expression or the declaration context associated with a prior
348 // nested-name-specifier.
349 LookupQualifiedName(Result, LookupCtx);
350
351 if (ObjectTypePtr && Result.empty()) {
352 // C++ [basic.lookup.classref]p3:
353 // If the unqualified-id is ~type-name, the type-name is looked up
354 // in the context of the entire postfix-expression. If the type T of
355 // the object expression is of a class type C, the type-name is also
356 // looked up in the scope of class C. At least one of the lookups shall
357 // find a name that refers to (possibly cv-qualified) T.
358 LookupName(Result, S);
359 }
360 } else {
361 // Perform unqualified name lookup.
362 LookupName(Result, S);
363
364 // For unqualified lookup in a class template in MSVC mode, look into
365 // dependent base classes where the primary class template is known.
366 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
367 if (ParsedType TypeInBase =
368 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
369 return TypeInBase;
370 }
371 }
372
373 NamedDecl *IIDecl = nullptr;
374 switch (Result.getResultKind()) {
375 case LookupResult::NotFound:
376 case LookupResult::NotFoundInCurrentInstantiation:
377 if (CorrectedII) {
378 TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
379 AllowDeducedTemplate);
380 TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
381 S, SS, CCC, CTK_ErrorRecovery);
382 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
383 TemplateTy Template;
384 bool MemberOfUnknownSpecialization;
385 UnqualifiedId TemplateName;
386 TemplateName.setIdentifier(NewII, NameLoc);
387 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
388 CXXScopeSpec NewSS, *NewSSPtr = SS;
389 if (SS && NNS) {
390 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
391 NewSSPtr = &NewSS;
392 }
393 if (Correction && (NNS || NewII != &II) &&
394 // Ignore a correction to a template type as the to-be-corrected
395 // identifier is not a template (typo correction for template names
396 // is handled elsewhere).
397 !(getLangOpts().CPlusPlus && NewSSPtr &&
398 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
399 Template, MemberOfUnknownSpecialization))) {
400 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
401 isClassName, HasTrailingDot, ObjectTypePtr,
402 IsCtorOrDtorName,
403 WantNontrivialTypeSourceInfo,
404 IsClassTemplateDeductionContext);
405 if (Ty) {
406 diagnoseTypo(Correction,
407 PDiag(diag::err_unknown_type_or_class_name_suggest)
408 << Result.getLookupName() << isClassName);
409 if (SS && NNS)
410 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
411 *CorrectedII = NewII;
412 return Ty;
413 }
414 }
415 }
416 // If typo correction failed or was not performed, fall through
417 LLVM_FALLTHROUGH[[gnu::fallthrough]];
418 case LookupResult::FoundOverloaded:
419 case LookupResult::FoundUnresolvedValue:
420 Result.suppressDiagnostics();
421 return nullptr;
422
423 case LookupResult::Ambiguous:
424 // Recover from type-hiding ambiguities by hiding the type. We'll
425 // do the lookup again when looking for an object, and we can
426 // diagnose the error then. If we don't do this, then the error
427 // about hiding the type will be immediately followed by an error
428 // that only makes sense if the identifier was treated like a type.
429 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
430 Result.suppressDiagnostics();
431 return nullptr;
432 }
433
434 // Look to see if we have a type anywhere in the list of results.
435 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
436 Res != ResEnd; ++Res) {
437 NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
438 if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
439 RealRes) ||
440 (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
441 if (!IIDecl ||
442 // Make the selection of the recovery decl deterministic.
443 RealRes->getLocation() < IIDecl->getLocation())
444 IIDecl = RealRes;
445 }
446 }
447
448 if (!IIDecl) {
449 // None of the entities we found is a type, so there is no way
450 // to even assume that the result is a type. In this case, don't
451 // complain about the ambiguity. The parser will either try to
452 // perform this lookup again (e.g., as an object name), which
453 // will produce the ambiguity, or will complain that it expected
454 // a type name.
455 Result.suppressDiagnostics();
456 return nullptr;
457 }
458
459 // We found a type within the ambiguous lookup; diagnose the
460 // ambiguity and then return that type. This might be the right
461 // answer, or it might not be, but it suppresses any attempt to
462 // perform the name lookup again.
463 break;
464
465 case LookupResult::Found:
466 IIDecl = Result.getFoundDecl();
467 break;
468 }
469
470 assert(IIDecl && "Didn't find decl")((void)0);
471
472 QualType T;
473 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
474 // C++ [class.qual]p2: A lookup that would find the injected-class-name
475 // instead names the constructors of the class, except when naming a class.
476 // This is ill-formed when we're not actually forming a ctor or dtor name.
477 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
478 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
479 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
480 FoundRD->isInjectedClassName() &&
481 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
482 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
483 << &II << /*Type*/1;
484
485 DiagnoseUseOfDecl(IIDecl, NameLoc);
486
487 T = Context.getTypeDeclType(TD);
488 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
489 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
490 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
491 if (!HasTrailingDot)
492 T = Context.getObjCInterfaceType(IDecl);
493 } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
494 (void)DiagnoseUseOfDecl(UD, NameLoc);
495 // Recover with 'int'
496 T = Context.IntTy;
497 } else if (AllowDeducedTemplate) {
498 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
499 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
500 QualType(), false);
501 }
502
503 if (T.isNull()) {
504 // If it's not plausibly a type, suppress diagnostics.
505 Result.suppressDiagnostics();
506 return nullptr;
507 }
508
509 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
510 // constructor or destructor name (in such a case, the scope specifier
511 // will be attached to the enclosing Expr or Decl node).
512 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
513 !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
514 if (WantNontrivialTypeSourceInfo) {
515 // Construct a type with type-source information.
516 TypeLocBuilder Builder;
517 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
518
519 T = getElaboratedType(ETK_None, *SS, T);
520 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
521 ElabTL.setElaboratedKeywordLoc(SourceLocation());
522 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
523 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
524 } else {
525 T = getElaboratedType(ETK_None, *SS, T);
526 }
527 }
528
529 return ParsedType::make(T);
530}
531
532// Builds a fake NNS for the given decl context.
533static NestedNameSpecifier *
534synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
535 for (;; DC = DC->getLookupParent()) {
536 DC = DC->getPrimaryContext();
537 auto *ND = dyn_cast<NamespaceDecl>(DC);
538 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
539 return NestedNameSpecifier::Create(Context, nullptr, ND);
540 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
541 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
542 RD->getTypeForDecl());
543 else if (isa<TranslationUnitDecl>(DC))
544 return NestedNameSpecifier::GlobalSpecifier(Context);
545 }
546 llvm_unreachable("something isn't in TU scope?")__builtin_unreachable();
547}
548
549/// Find the parent class with dependent bases of the innermost enclosing method
550/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
551/// up allowing unqualified dependent type names at class-level, which MSVC
552/// correctly rejects.
553static const CXXRecordDecl *
554findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
555 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
556 DC = DC->getPrimaryContext();
557 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
558 if (MD->getParent()->hasAnyDependentBases())
559 return MD->getParent();
560 }
561 return nullptr;
562}
563
564ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
565 SourceLocation NameLoc,
566 bool IsTemplateTypeArg) {
567 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")((void)0);
568
569 NestedNameSpecifier *NNS = nullptr;
570 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
571 // If we weren't able to parse a default template argument, delay lookup
572 // until instantiation time by making a non-dependent DependentTypeName. We
573 // pretend we saw a NestedNameSpecifier referring to the current scope, and
574 // lookup is retried.
575 // FIXME: This hurts our diagnostic quality, since we get errors like "no
576 // type named 'Foo' in 'current_namespace'" when the user didn't write any
577 // name specifiers.
578 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
579 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
580 } else if (const CXXRecordDecl *RD =
581 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
582 // Build a DependentNameType that will perform lookup into RD at
583 // instantiation time.
584 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
585 RD->getTypeForDecl());
586
587 // Diagnose that this identifier was undeclared, and retry the lookup during
588 // template instantiation.
589 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
590 << RD;
591 } else {
592 // This is not a situation that we should recover from.
593 return ParsedType();
594 }
595
596 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
597
598 // Build type location information. We synthesized the qualifier, so we have
599 // to build a fake NestedNameSpecifierLoc.
600 NestedNameSpecifierLocBuilder NNSLocBuilder;
601 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
602 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
603
604 TypeLocBuilder Builder;
605 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
606 DepTL.setNameLoc(NameLoc);
607 DepTL.setElaboratedKeywordLoc(SourceLocation());
608 DepTL.setQualifierLoc(QualifierLoc);
609 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
610}
611
612/// isTagName() - This method is called *for error recovery purposes only*
613/// to determine if the specified name is a valid tag name ("struct foo"). If
614/// so, this returns the TST for the tag corresponding to it (TST_enum,
615/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
616/// cases in C where the user forgot to specify the tag.
617DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
618 // Do a tag name lookup in this scope.
619 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
620 LookupName(R, S, false);
621 R.suppressDiagnostics();
622 if (R.getResultKind() == LookupResult::Found)
623 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
624 switch (TD->getTagKind()) {
625 case TTK_Struct: return DeclSpec::TST_struct;
626 case TTK_Interface: return DeclSpec::TST_interface;
627 case TTK_Union: return DeclSpec::TST_union;
628 case TTK_Class: return DeclSpec::TST_class;
629 case TTK_Enum: return DeclSpec::TST_enum;
630 }
631 }
632
633 return DeclSpec::TST_unspecified;
634}
635
636/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
637/// if a CXXScopeSpec's type is equal to the type of one of the base classes
638/// then downgrade the missing typename error to a warning.
639/// This is needed for MSVC compatibility; Example:
640/// @code
641/// template<class T> class A {
642/// public:
643/// typedef int TYPE;
644/// };
645/// template<class T> class B : public A<T> {
646/// public:
647/// A<T>::TYPE a; // no typename required because A<T> is a base class.
648/// };
649/// @endcode
650bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
651 if (CurContext->isRecord()) {
652 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
653 return true;
654
655 const Type *Ty = SS->getScopeRep()->getAsType();
656
657 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
658 for (const auto &Base : RD->bases())
659 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
660 return true;
661 return S->isFunctionPrototypeScope();
662 }
663 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
664}
665
666void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
667 SourceLocation IILoc,
668 Scope *S,
669 CXXScopeSpec *SS,
670 ParsedType &SuggestedType,
671 bool IsTemplateName) {
672 // Don't report typename errors for editor placeholders.
673 if (II->isEditorPlaceholder())
674 return;
675 // We don't have anything to suggest (yet).
676 SuggestedType = nullptr;
677
678 // There may have been a typo in the name of the type. Look up typo
679 // results, in case we have something that we can suggest.
680 TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
681 /*AllowTemplates=*/IsTemplateName,
682 /*AllowNonTemplates=*/!IsTemplateName);
683 if (TypoCorrection Corrected =
684 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
685 CCC, CTK_ErrorRecovery)) {
686 // FIXME: Support error recovery for the template-name case.
687 bool CanRecover = !IsTemplateName;
688 if (Corrected.isKeyword()) {
689 // We corrected to a keyword.
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName ? diag::err_no_template_suggest
692 : diag::err_unknown_typename_suggest)
693 << II);
694 II = Corrected.getCorrectionAsIdentifierInfo();
695 } else {
696 // We found a similarly-named type or interface; suggest that.
697 if (!SS || !SS->isSet()) {
698 diagnoseTypo(Corrected,
699 PDiag(IsTemplateName ? diag::err_no_template_suggest
700 : diag::err_unknown_typename_suggest)
701 << II, CanRecover);
702 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
703 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
704 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
705 II->getName().equals(CorrectedStr);
706 diagnoseTypo(Corrected,
707 PDiag(IsTemplateName
708 ? diag::err_no_member_template_suggest
709 : diag::err_unknown_nested_typename_suggest)
710 << II << DC << DroppedSpecifier << SS->getRange(),
711 CanRecover);
712 } else {
713 llvm_unreachable("could not have corrected a typo here")__builtin_unreachable();
714 }
715
716 if (!CanRecover)
717 return;
718
719 CXXScopeSpec tmpSS;
720 if (Corrected.getCorrectionSpecifier())
721 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
722 SourceRange(IILoc));
723 // FIXME: Support class template argument deduction here.
724 SuggestedType =
725 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
726 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
727 /*IsCtorOrDtorName=*/false,
728 /*WantNontrivialTypeSourceInfo=*/true);
729 }
730 return;
731 }
732
733 if (getLangOpts().CPlusPlus && !IsTemplateName) {
734 // See if II is a class template that the user forgot to pass arguments to.
735 UnqualifiedId Name;
736 Name.setIdentifier(II, IILoc);
737 CXXScopeSpec EmptySS;
738 TemplateTy TemplateResult;
739 bool MemberOfUnknownSpecialization;
740 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
741 Name, nullptr, true, TemplateResult,
742 MemberOfUnknownSpecialization) == TNK_Type_template) {
743 diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
744 return;
745 }
746 }
747
748 // FIXME: Should we move the logic that tries to recover from a missing tag
749 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
750
751 if (!SS || (!SS->isSet() && !SS->isInvalid()))
752 Diag(IILoc, IsTemplateName ? diag::err_no_template
753 : diag::err_unknown_typename)
754 << II;
755 else if (DeclContext *DC = computeDeclContext(*SS, false))
756 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
757 : diag::err_typename_nested_not_found)
758 << II << DC << SS->getRange();
759 else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
760 SuggestedType =
761 ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
762 } else if (isDependentScopeSpecifier(*SS)) {
763 unsigned DiagID = diag::err_typename_missing;
764 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
765 DiagID = diag::ext_typename_missing;
766
767 Diag(SS->getRange().getBegin(), DiagID)
768 << SS->getScopeRep() << II->getName()
769 << SourceRange(SS->getRange().getBegin(), IILoc)
770 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
771 SuggestedType = ActOnTypenameType(S, SourceLocation(),
772 *SS, *II, IILoc).get();
773 } else {
774 assert(SS && SS->isInvalid() &&((void)0)
775 "Invalid scope specifier has already been diagnosed")((void)0);
776 }
777}
778
779/// Determine whether the given result set contains either a type name
780/// or
781static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
782 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
783 NextToken.is(tok::less);
784
785 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
786 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
787 return true;
788
789 if (CheckTemplate && isa<TemplateDecl>(*I))
790 return true;
791 }
792
793 return false;
794}
795
796static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
797 Scope *S, CXXScopeSpec &SS,
798 IdentifierInfo *&Name,
799 SourceLocation NameLoc) {
800 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
801 SemaRef.LookupParsedName(R, S, &SS);
802 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
803 StringRef FixItTagName;
804 switch (Tag->getTagKind()) {
805 case TTK_Class:
806 FixItTagName = "class ";
807 break;
808
809 case TTK_Enum:
810 FixItTagName = "enum ";
811 break;
812
813 case TTK_Struct:
814 FixItTagName = "struct ";
815 break;
816
817 case TTK_Interface:
818 FixItTagName = "__interface ";
819 break;
820
821 case TTK_Union:
822 FixItTagName = "union ";
823 break;
824 }
825
826 StringRef TagName = FixItTagName.drop_back();
827 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
828 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
829 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
830
831 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
832 I != IEnd; ++I)
833 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
834 << Name << TagName;
835
836 // Replace lookup results with just the tag decl.
837 Result.clear(Sema::LookupTagName);
838 SemaRef.LookupParsedName(Result, S, &SS);
839 return true;
840 }
841
842 return false;
843}
844
845/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
846static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
847 QualType T, SourceLocation NameLoc) {
848 ASTContext &Context = S.Context;
849
850 TypeLocBuilder Builder;
851 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
852
853 T = S.getElaboratedType(ETK_None, SS, T);
854 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
855 ElabTL.setElaboratedKeywordLoc(SourceLocation());
856 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
857 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
858}
859
860Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
861 IdentifierInfo *&Name,
862 SourceLocation NameLoc,
863 const Token &NextToken,
864 CorrectionCandidateCallback *CCC) {
865 DeclarationNameInfo NameInfo(Name, NameLoc);
866 ObjCMethodDecl *CurMethod = getCurMethodDecl();
867
868 assert(NextToken.isNot(tok::coloncolon) &&((void)0)
869 "parse nested name specifiers before calling ClassifyName")((void)0);
870 if (getLangOpts().CPlusPlus && SS.isSet() &&
871 isCurrentClassName(*Name, S, &SS)) {
872 // Per [class.qual]p2, this names the constructors of SS, not the
873 // injected-class-name. We don't have a classification for that.
874 // There's not much point caching this result, since the parser
875 // will reject it later.
876 return NameClassification::Unknown();
877 }
878
879 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
880 LookupParsedName(Result, S, &SS, !CurMethod);
881
882 if (SS.isInvalid())
883 return NameClassification::Error();
884
885 // For unqualified lookup in a class template in MSVC mode, look into
886 // dependent base classes where the primary class template is known.
887 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
888 if (ParsedType TypeInBase =
889 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
890 return TypeInBase;
891 }
892
893 // Perform lookup for Objective-C instance variables (including automatically
894 // synthesized instance variables), if we're in an Objective-C method.
895 // FIXME: This lookup really, really needs to be folded in to the normal
896 // unqualified lookup mechanism.
897 if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
898 DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
899 if (Ivar.isInvalid())
900 return NameClassification::Error();
901 if (Ivar.isUsable())
902 return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
903
904 // We defer builtin creation until after ivar lookup inside ObjC methods.
905 if (Result.empty())
906 LookupBuiltin(Result);
907 }
908
909 bool SecondTry = false;
910 bool IsFilteredTemplateName = false;
911
912Corrected:
913 switch (Result.getResultKind()) {
914 case LookupResult::NotFound:
915 // If an unqualified-id is followed by a '(', then we have a function
916 // call.
917 if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
918 // In C++, this is an ADL-only call.
919 // FIXME: Reference?
920 if (getLangOpts().CPlusPlus)
921 return NameClassification::UndeclaredNonType();
922
923 // C90 6.3.2.2:
924 // If the expression that precedes the parenthesized argument list in a
925 // function call consists solely of an identifier, and if no
926 // declaration is visible for this identifier, the identifier is
927 // implicitly declared exactly as if, in the innermost block containing
928 // the function call, the declaration
929 //
930 // extern int identifier ();
931 //
932 // appeared.
933 //
934 // We also allow this in C99 as an extension.
935 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
936 return NameClassification::NonType(D);
937 }
938
939 if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
940 // In C++20 onwards, this could be an ADL-only call to a function
941 // template, and we're required to assume that this is a template name.
942 //
943 // FIXME: Find a way to still do typo correction in this case.
944 TemplateName Template =
945 Context.getAssumedTemplateName(NameInfo.getName());
946 return NameClassification::UndeclaredTemplate(Template);
947 }
948
949 // In C, we first see whether there is a tag type by the same name, in
950 // which case it's likely that the user just forgot to write "enum",
951 // "struct", or "union".
952 if (!getLangOpts().CPlusPlus && !SecondTry &&
953 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
954 break;
955 }
956
957 // Perform typo correction to determine if there is another name that is
958 // close to this name.
959 if (!SecondTry && CCC) {
960 SecondTry = true;
961 if (TypoCorrection Corrected =
962 CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
963 &SS, *CCC, CTK_ErrorRecovery)) {
964 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
965 unsigned QualifiedDiag = diag::err_no_member_suggest;
966
967 NamedDecl *FirstDecl = Corrected.getFoundDecl();
968 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
969 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
970 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
971 UnqualifiedDiag = diag::err_no_template_suggest;
972 QualifiedDiag = diag::err_no_member_template_suggest;
973 } else if (UnderlyingFirstDecl &&
974 (isa<TypeDecl>(UnderlyingFirstDecl) ||
975 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
976 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
977 UnqualifiedDiag = diag::err_unknown_typename_suggest;
978 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
979 }
980
981 if (SS.isEmpty()) {
982 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
983 } else {// FIXME: is this even reachable? Test it.
984 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
985 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
986 Name->getName().equals(CorrectedStr);
987 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
988 << Name << computeDeclContext(SS, false)
989 << DroppedSpecifier << SS.getRange());
990 }
991
992 // Update the name, so that the caller has the new name.
993 Name = Corrected.getCorrectionAsIdentifierInfo();
994
995 // Typo correction corrected to a keyword.
996 if (Corrected.isKeyword())
997 return Name;
998
999 // Also update the LookupResult...
1000 // FIXME: This should probably go away at some point
1001 Result.clear();
1002 Result.setLookupName(Corrected.getCorrection());
1003 if (FirstDecl)
1004 Result.addDecl(FirstDecl);
1005
1006 // If we found an Objective-C instance variable, let
1007 // LookupInObjCMethod build the appropriate expression to
1008 // reference the ivar.
1009 // FIXME: This is a gross hack.
1010 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1011 DeclResult R =
1012 LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1013 if (R.isInvalid())
1014 return NameClassification::Error();
1015 if (R.isUsable())
1016 return NameClassification::NonType(Ivar);
1017 }
1018
1019 goto Corrected;
1020 }
1021 }
1022
1023 // We failed to correct; just fall through and let the parser deal with it.
1024 Result.suppressDiagnostics();
1025 return NameClassification::Unknown();
1026
1027 case LookupResult::NotFoundInCurrentInstantiation: {
1028 // We performed name lookup into the current instantiation, and there were
1029 // dependent bases, so we treat this result the same way as any other
1030 // dependent nested-name-specifier.
1031
1032 // C++ [temp.res]p2:
1033 // A name used in a template declaration or definition and that is
1034 // dependent on a template-parameter is assumed not to name a type
1035 // unless the applicable name lookup finds a type name or the name is
1036 // qualified by the keyword typename.
1037 //
1038 // FIXME: If the next token is '<', we might want to ask the parser to
1039 // perform some heroics to see if we actually have a
1040 // template-argument-list, which would indicate a missing 'template'
1041 // keyword here.
1042 return NameClassification::DependentNonType();
1043 }
1044
1045 case LookupResult::Found:
1046 case LookupResult::FoundOverloaded:
1047 case LookupResult::FoundUnresolvedValue:
1048 break;
1049
1050 case LookupResult::Ambiguous:
1051 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1052 hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1053 /*AllowDependent=*/false)) {
1054 // C++ [temp.local]p3:
1055 // A lookup that finds an injected-class-name (10.2) can result in an
1056 // ambiguity in certain cases (for example, if it is found in more than
1057 // one base class). If all of the injected-class-names that are found
1058 // refer to specializations of the same class template, and if the name
1059 // is followed by a template-argument-list, the reference refers to the
1060 // class template itself and not a specialization thereof, and is not
1061 // ambiguous.
1062 //
1063 // This filtering can make an ambiguous result into an unambiguous one,
1064 // so try again after filtering out template names.
1065 FilterAcceptableTemplateNames(Result);
1066 if (!Result.isAmbiguous()) {
1067 IsFilteredTemplateName = true;
1068 break;
1069 }
1070 }
1071
1072 // Diagnose the ambiguity and return an error.
1073 return NameClassification::Error();
1074 }
1075
1076 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1077 (IsFilteredTemplateName ||
1078 hasAnyAcceptableTemplateNames(
1079 Result, /*AllowFunctionTemplates=*/true,
1080 /*AllowDependent=*/false,
1081 /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1082 getLangOpts().CPlusPlus20))) {
1083 // C++ [temp.names]p3:
1084 // After name lookup (3.4) finds that a name is a template-name or that
1085 // an operator-function-id or a literal- operator-id refers to a set of
1086 // overloaded functions any member of which is a function template if
1087 // this is followed by a <, the < is always taken as the delimiter of a
1088 // template-argument-list and never as the less-than operator.
1089 // C++2a [temp.names]p2:
1090 // A name is also considered to refer to a template if it is an
1091 // unqualified-id followed by a < and name lookup finds either one
1092 // or more functions or finds nothing.
1093 if (!IsFilteredTemplateName)
1094 FilterAcceptableTemplateNames(Result);
1095
1096 bool IsFunctionTemplate;
1097 bool IsVarTemplate;
1098 TemplateName Template;
1099 if (Result.end() - Result.begin() > 1) {
1100 IsFunctionTemplate = true;
1101 Template = Context.getOverloadedTemplateName(Result.begin(),
1102 Result.end());
1103 } else if (!Result.empty()) {
1104 auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1105 *Result.begin(), /*AllowFunctionTemplates=*/true,
1106 /*AllowDependent=*/false));
1107 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1108 IsVarTemplate = isa<VarTemplateDecl>(TD);
1109
1110 if (SS.isNotEmpty())
1111 Template =
1112 Context.getQualifiedTemplateName(SS.getScopeRep(),
1113 /*TemplateKeyword=*/false, TD);
1114 else
1115 Template = TemplateName(TD);
1116 } else {
1117 // All results were non-template functions. This is a function template
1118 // name.
1119 IsFunctionTemplate = true;
1120 Template = Context.getAssumedTemplateName(NameInfo.getName());
1121 }
1122
1123 if (IsFunctionTemplate) {
1124 // Function templates always go through overload resolution, at which
1125 // point we'll perform the various checks (e.g., accessibility) we need
1126 // to based on which function we selected.
1127 Result.suppressDiagnostics();
1128
1129 return NameClassification::FunctionTemplate(Template);
1130 }
1131
1132 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1133 : NameClassification::TypeTemplate(Template);
1134 }
1135
1136 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1137 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1138 DiagnoseUseOfDecl(Type, NameLoc);
1139 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1140 QualType T = Context.getTypeDeclType(Type);
1141 if (SS.isNotEmpty())
1142 return buildNestedType(*this, SS, T, NameLoc);
1143 return ParsedType::make(T);
1144 }
1145
1146 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1147 if (!Class) {
1148 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1149 if (ObjCCompatibleAliasDecl *Alias =
1150 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1151 Class = Alias->getClassInterface();
1152 }
1153
1154 if (Class) {
1155 DiagnoseUseOfDecl(Class, NameLoc);
1156
1157 if (NextToken.is(tok::period)) {
1158 // Interface. <something> is parsed as a property reference expression.
1159 // Just return "unknown" as a fall-through for now.
1160 Result.suppressDiagnostics();
1161 return NameClassification::Unknown();
1162 }
1163
1164 QualType T = Context.getObjCInterfaceType(Class);
1165 return ParsedType::make(T);
1166 }
1167
1168 if (isa<ConceptDecl>(FirstDecl))
1169 return NameClassification::Concept(
1170 TemplateName(cast<TemplateDecl>(FirstDecl)));
1171
1172 if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1173 (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1174 return NameClassification::Error();
1175 }
1176
1177 // We can have a type template here if we're classifying a template argument.
1178 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1179 !isa<VarTemplateDecl>(FirstDecl))
1180 return NameClassification::TypeTemplate(
1181 TemplateName(cast<TemplateDecl>(FirstDecl)));
1182
1183 // Check for a tag type hidden by a non-type decl in a few cases where it
1184 // seems likely a type is wanted instead of the non-type that was found.
1185 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1186 if ((NextToken.is(tok::identifier) ||
1187 (NextIsOp &&
1188 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1189 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1190 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1191 DiagnoseUseOfDecl(Type, NameLoc);
1192 QualType T = Context.getTypeDeclType(Type);
1193 if (SS.isNotEmpty())
1194 return buildNestedType(*this, SS, T, NameLoc);
1195 return ParsedType::make(T);
1196 }
1197
1198 // If we already know which single declaration is referenced, just annotate
1199 // that declaration directly. Defer resolving even non-overloaded class
1200 // member accesses, as we need to defer certain access checks until we know
1201 // the context.
1202 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1203 if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1204 return NameClassification::NonType(Result.getRepresentativeDecl());
1205
1206 // Otherwise, this is an overload set that we will need to resolve later.
1207 Result.suppressDiagnostics();
1208 return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1209 Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1210 Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1211 Result.begin(), Result.end()));
1212}
1213
1214ExprResult
1215Sema::ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
1216 SourceLocation NameLoc) {
1217 assert(getLangOpts().CPlusPlus && "ADL-only call in C?")((void)0);
1218 CXXScopeSpec SS;
1219 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1220 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1221}
1222
1223ExprResult
1224Sema::ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
1225 IdentifierInfo *Name,
1226 SourceLocation NameLoc,
1227 bool IsAddressOfOperand) {
1228 DeclarationNameInfo NameInfo(Name, NameLoc);
1229 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1230 NameInfo, IsAddressOfOperand,
1231 /*TemplateArgs=*/nullptr);
1232}
1233
1234ExprResult Sema::ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
1235 NamedDecl *Found,
1236 SourceLocation NameLoc,
1237 const Token &NextToken) {
1238 if (getCurMethodDecl() && SS.isEmpty())
1239 if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1240 return BuildIvarRefExpr(S, NameLoc, Ivar);
1241
1242 // Reconstruct the lookup result.
1243 LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1244 Result.addDecl(Found);
1245 Result.resolveKind();
1246
1247 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1248 return BuildDeclarationNameExpr(SS, Result, ADL);
1249}
1250
1251ExprResult Sema::ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *E) {
1252 // For an implicit class member access, transform the result into a member
1253 // access expression if necessary.
1254 auto *ULE = cast<UnresolvedLookupExpr>(E);
1255 if ((*ULE->decls_begin())->isCXXClassMember()) {
1256 CXXScopeSpec SS;
1257 SS.Adopt(ULE->getQualifierLoc());
1258
1259 // Reconstruct the lookup result.
1260 LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1261 LookupOrdinaryName);
1262 Result.setNamingClass(ULE->getNamingClass());
1263 for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1264 Result.addDecl(*I, I.getAccess());
1265 Result.resolveKind();
1266 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1267 nullptr, S);
1268 }
1269
1270 // Otherwise, this is already in the form we needed, and no further checks
1271 // are necessary.
1272 return ULE;
1273}
1274
1275Sema::TemplateNameKindForDiagnostics
1276Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1277 auto *TD = Name.getAsTemplateDecl();
1278 if (!TD)
1279 return TemplateNameKindForDiagnostics::DependentTemplate;
1280 if (isa<ClassTemplateDecl>(TD))
1281 return TemplateNameKindForDiagnostics::ClassTemplate;
1282 if (isa<FunctionTemplateDecl>(TD))
1283 return TemplateNameKindForDiagnostics::FunctionTemplate;
1284 if (isa<VarTemplateDecl>(TD))
1285 return TemplateNameKindForDiagnostics::VarTemplate;
1286 if (isa<TypeAliasTemplateDecl>(TD))
1287 return TemplateNameKindForDiagnostics::AliasTemplate;
1288 if (isa<TemplateTemplateParmDecl>(TD))
1289 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1290 if (isa<ConceptDecl>(TD))
1291 return TemplateNameKindForDiagnostics::Concept;
1292 return TemplateNameKindForDiagnostics::DependentTemplate;
1293}
1294
1295void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1296 assert(DC->getLexicalParent() == CurContext &&((void)0)
1297 "The next DeclContext should be lexically contained in the current one.")((void)0);
1298 CurContext = DC;
1299 S->setEntity(DC);
1300}
1301
1302void Sema::PopDeclContext() {
1303 assert(CurContext && "DeclContext imbalance!")((void)0);
1304
1305 CurContext = CurContext->getLexicalParent();
1306 assert(CurContext && "Popped translation unit!")((void)0);
1307}
1308
1309Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1310 Decl *D) {
1311 // Unlike PushDeclContext, the context to which we return is not necessarily
1312 // the containing DC of TD, because the new context will be some pre-existing
1313 // TagDecl definition instead of a fresh one.
1314 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1315 CurContext = cast<TagDecl>(D)->getDefinition();
1316 assert(CurContext && "skipping definition of undefined tag")((void)0);
1317 // Start lookups from the parent of the current context; we don't want to look
1318 // into the pre-existing complete definition.
1319 S->setEntity(CurContext->getLookupParent());
1320 return Result;
1321}
1322
1323void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1324 CurContext = static_cast<decltype(CurContext)>(Context);
1325}
1326
1327/// EnterDeclaratorContext - Used when we must lookup names in the context
1328/// of a declarator's nested name specifier.
1329///
1330void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1331 // C++0x [basic.lookup.unqual]p13:
1332 // A name used in the definition of a static data member of class
1333 // X (after the qualified-id of the static member) is looked up as
1334 // if the name was used in a member function of X.
1335 // C++0x [basic.lookup.unqual]p14:
1336 // If a variable member of a namespace is defined outside of the
1337 // scope of its namespace then any name used in the definition of
1338 // the variable member (after the declarator-id) is looked up as
1339 // if the definition of the variable member occurred in its
1340 // namespace.
1341 // Both of these imply that we should push a scope whose context
1342 // is the semantic context of the declaration. We can't use
1343 // PushDeclContext here because that context is not necessarily
1344 // lexically contained in the current context. Fortunately,
1345 // the containing scope should have the appropriate information.
1346
1347 assert(!S->getEntity() && "scope already has entity")((void)0);
1348
1349#ifndef NDEBUG1
1350 Scope *Ancestor = S->getParent();
1351 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1352 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")((void)0);
1353#endif
1354
1355 CurContext = DC;
1356 S->setEntity(DC);
1357
1358 if (S->getParent()->isTemplateParamScope()) {
1359 // Also set the corresponding entities for all immediately-enclosing
1360 // template parameter scopes.
1361 EnterTemplatedContext(S->getParent(), DC);
1362 }
1363}
1364
1365void Sema::ExitDeclaratorContext(Scope *S) {
1366 assert(S->getEntity() == CurContext && "Context imbalance!")((void)0);
1367
1368 // Switch back to the lexical context. The safety of this is
1369 // enforced by an assert in EnterDeclaratorContext.
1370 Scope *Ancestor = S->getParent();
1371 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1372 CurContext = Ancestor->getEntity();
1373
1374 // We don't need to do anything with the scope, which is going to
1375 // disappear.
1376}
1377
1378void Sema::EnterTemplatedContext(Scope *S, DeclContext *DC) {
1379 assert(S->isTemplateParamScope() &&((void)0)
1380 "expected to be initializing a template parameter scope")((void)0);
1381
1382 // C++20 [temp.local]p7:
1383 // In the definition of a member of a class template that appears outside
1384 // of the class template definition, the name of a member of the class
1385 // template hides the name of a template-parameter of any enclosing class
1386 // templates (but not a template-parameter of the member if the member is a
1387 // class or function template).
1388 // C++20 [temp.local]p9:
1389 // In the definition of a class template or in the definition of a member
1390 // of such a template that appears outside of the template definition, for
1391 // each non-dependent base class (13.8.2.1), if the name of the base class
1392 // or the name of a member of the base class is the same as the name of a
1393 // template-parameter, the base class name or member name hides the
1394 // template-parameter name (6.4.10).
1395 //
1396 // This means that a template parameter scope should be searched immediately
1397 // after searching the DeclContext for which it is a template parameter
1398 // scope. For example, for
1399 // template<typename T> template<typename U> template<typename V>
1400 // void N::A<T>::B<U>::f(...)
1401 // we search V then B<U> (and base classes) then U then A<T> (and base
1402 // classes) then T then N then ::.
1403 unsigned ScopeDepth = getTemplateDepth(S);
1404 for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1405 DeclContext *SearchDCAfterScope = DC;
1406 for (; DC; DC = DC->getLookupParent()) {
1407 if (const TemplateParameterList *TPL =
1408 cast<Decl>(DC)->getDescribedTemplateParams()) {
1409 unsigned DCDepth = TPL->getDepth() + 1;
1410 if (DCDepth > ScopeDepth)
1411 continue;
1412 if (ScopeDepth == DCDepth)
1413 SearchDCAfterScope = DC = DC->getLookupParent();
1414 break;
1415 }
1416 }
1417 S->setLookupEntity(SearchDCAfterScope);
1418 }
1419}
1420
1421void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1422 // We assume that the caller has already called
1423 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1424 FunctionDecl *FD = D->getAsFunction();
1425 if (!FD)
1426 return;
1427
1428 // Same implementation as PushDeclContext, but enters the context
1429 // from the lexical parent, rather than the top-level class.
1430 assert(CurContext == FD->getLexicalParent() &&((void)0)
1431 "The next DeclContext should be lexically contained in the current one.")((void)0);
1432 CurContext = FD;
1433 S->setEntity(CurContext);
1434
1435 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1436 ParmVarDecl *Param = FD->getParamDecl(P);
1437 // If the parameter has an identifier, then add it to the scope
1438 if (Param->getIdentifier()) {
1439 S->AddDecl(Param);
1440 IdResolver.AddDecl(Param);
1441 }
1442 }
1443}
1444
1445void Sema::ActOnExitFunctionContext() {
1446 // Same implementation as PopDeclContext, but returns to the lexical parent,
1447 // rather than the top-level class.
1448 assert(CurContext && "DeclContext imbalance!")((void)0);
1449 CurContext = CurContext->getLexicalParent();
1450 assert(CurContext && "Popped translation unit!")((void)0);
1451}
1452
1453/// Determine whether we allow overloading of the function
1454/// PrevDecl with another declaration.
1455///
1456/// This routine determines whether overloading is possible, not
1457/// whether some new function is actually an overload. It will return
1458/// true in C++ (where we can always provide overloads) or, as an
1459/// extension, in C when the previous function is already an
1460/// overloaded function declaration or has the "overloadable"
1461/// attribute.
1462static bool AllowOverloadingOfFunction(LookupResult &Previous,
1463 ASTContext &Context,
1464 const FunctionDecl *New) {
1465 if (Context.getLangOpts().CPlusPlus)
1466 return true;
1467
1468 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1469 return true;
1470
1471 return Previous.getResultKind() == LookupResult::Found &&
1472 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1473 New->hasAttr<OverloadableAttr>());
1474}
1475
1476/// Add this decl to the scope shadowed decl chains.
1477void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1478 // Move up the scope chain until we find the nearest enclosing
1479 // non-transparent context. The declaration will be introduced into this
1480 // scope.
1481 while (S->getEntity() && S->getEntity()->isTransparentContext())
1482 S = S->getParent();
1483
1484 // Add scoped declarations into their context, so that they can be
1485 // found later. Declarations without a context won't be inserted
1486 // into any context.
1487 if (AddToContext)
1488 CurContext->addDecl(D);
1489
1490 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1491 // are function-local declarations.
1492 if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1493 return;
1494
1495 // Template instantiations should also not be pushed into scope.
1496 if (isa<FunctionDecl>(D) &&
1497 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1498 return;
1499
1500 // If this replaces anything in the current scope,
1501 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1502 IEnd = IdResolver.end();
1503 for (; I != IEnd; ++I) {
1504 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1505 S->RemoveDecl(*I);
1506 IdResolver.RemoveDecl(*I);
1507
1508 // Should only need to replace one decl.
1509 break;
1510 }
1511 }
1512
1513 S->AddDecl(D);
1514
1515 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1516 // Implicitly-generated labels may end up getting generated in an order that
1517 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1518 // the label at the appropriate place in the identifier chain.
1519 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1520 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1521 if (IDC == CurContext) {
1522 if (!S->isDeclScope(*I))
1523 continue;
1524 } else if (IDC->Encloses(CurContext))
1525 break;
1526 }
1527
1528 IdResolver.InsertDeclAfter(I, D);
1529 } else {
1530 IdResolver.AddDecl(D);
1531 }
1532 warnOnReservedIdentifier(D);
1533}
1534
1535bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1536 bool AllowInlineNamespace) {
1537 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1538}
1539
1540Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1541 DeclContext *TargetDC = DC->getPrimaryContext();
1542 do {
1543 if (DeclContext *ScopeDC = S->getEntity())
1544 if (ScopeDC->getPrimaryContext() == TargetDC)
1545 return S;
1546 } while ((S = S->getParent()));
1547
1548 return nullptr;
1549}
1550
1551static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1552 DeclContext*,
1553 ASTContext&);
1554
1555/// Filters out lookup results that don't fall within the given scope
1556/// as determined by isDeclInScope.
1557void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1558 bool ConsiderLinkage,
1559 bool AllowInlineNamespace) {
1560 LookupResult::Filter F = R.makeFilter();
1561 while (F.hasNext()) {
1562 NamedDecl *D = F.next();
1563
1564 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1565 continue;
1566
1567 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1568 continue;
1569
1570 F.erase();
1571 }
1572
1573 F.done();
1574}
1575
1576/// We've determined that \p New is a redeclaration of \p Old. Check that they
1577/// have compatible owning modules.
1578bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1579 // FIXME: The Modules TS is not clear about how friend declarations are
1580 // to be treated. It's not meaningful to have different owning modules for
1581 // linkage in redeclarations of the same entity, so for now allow the
1582 // redeclaration and change the owning modules to match.
1583 if (New->getFriendObjectKind() &&
1584 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1585 New->setLocalOwningModule(Old->getOwningModule());
1586 makeMergedDefinitionVisible(New);
1587 return false;
1588 }
1589
1590 Module *NewM = New->getOwningModule();
1591 Module *OldM = Old->getOwningModule();
1592
1593 if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1594 NewM = NewM->Parent;
1595 if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1596 OldM = OldM->Parent;
1597
1598 if (NewM == OldM)
1599 return false;
1600
1601 bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1602 bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1603 if (NewIsModuleInterface || OldIsModuleInterface) {
1604 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1605 // if a declaration of D [...] appears in the purview of a module, all
1606 // other such declarations shall appear in the purview of the same module
1607 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1608 << New
1609 << NewIsModuleInterface
1610 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1611 << OldIsModuleInterface
1612 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1613 Diag(Old->getLocation(), diag::note_previous_declaration);
1614 New->setInvalidDecl();
1615 return true;
1616 }
1617
1618 return false;
1619}
1620
1621static bool isUsingDecl(NamedDecl *D) {
1622 return isa<UsingShadowDecl>(D) ||
1623 isa<UnresolvedUsingTypenameDecl>(D) ||
1624 isa<UnresolvedUsingValueDecl>(D);
1625}
1626
1627/// Removes using shadow declarations from the lookup results.
1628static void RemoveUsingDecls(LookupResult &R) {
1629 LookupResult::Filter F = R.makeFilter();
1630 while (F.hasNext())
1631 if (isUsingDecl(F.next()))
1632 F.erase();
1633
1634 F.done();
1635}
1636
1637/// Check for this common pattern:
1638/// @code
1639/// class S {
1640/// S(const S&); // DO NOT IMPLEMENT
1641/// void operator=(const S&); // DO NOT IMPLEMENT
1642/// };
1643/// @endcode
1644static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1645 // FIXME: Should check for private access too but access is set after we get
1646 // the decl here.
1647 if (D->doesThisDeclarationHaveABody())
1648 return false;
1649
1650 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1651 return CD->isCopyConstructor();
1652 return D->isCopyAssignmentOperator();
1653}
1654
1655// We need this to handle
1656//
1657// typedef struct {
1658// void *foo() { return 0; }
1659// } A;
1660//
1661// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1662// for example. If 'A', foo will have external linkage. If we have '*A',
1663// foo will have no linkage. Since we can't know until we get to the end
1664// of the typedef, this function finds out if D might have non-external linkage.
1665// Callers should verify at the end of the TU if it D has external linkage or
1666// not.
1667bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1668 const DeclContext *DC = D->getDeclContext();
1669 while (!DC->isTranslationUnit()) {
1670 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1671 if (!RD->hasNameForLinkage())
1672 return true;
1673 }
1674 DC = DC->getParent();
1675 }
1676
1677 return !D->isExternallyVisible();
1678}
1679
1680// FIXME: This needs to be refactored; some other isInMainFile users want
1681// these semantics.
1682static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1683 if (S.TUKind != TU_Complete)
1684 return false;
1685 return S.SourceMgr.isInMainFile(Loc);
1686}
1687
1688bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1689 assert(D)((void)0);
1690
1691 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1692 return false;
1693
1694 // Ignore all entities declared within templates, and out-of-line definitions
1695 // of members of class templates.
1696 if (D->getDeclContext()->isDependentContext() ||
1697 D->getLexicalDeclContext()->isDependentContext())
1698 return false;
1699
1700 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1701 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1702 return false;
1703 // A non-out-of-line declaration of a member specialization was implicitly
1704 // instantiated; it's the out-of-line declaration that we're interested in.
1705 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1706 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1707 return false;
1708
1709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1710 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1711 return false;
1712 } else {
1713 // 'static inline' functions are defined in headers; don't warn.
1714 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1715 return false;
1716 }
1717
1718 if (FD->doesThisDeclarationHaveABody() &&
1719 Context.DeclMustBeEmitted(FD))
1720 return false;
1721 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1722 // Constants and utility variables are defined in headers with internal
1723 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1724 // like "inline".)
1725 if (!isMainFileLoc(*this, VD->getLocation()))
1726 return false;
1727
1728 if (Context.DeclMustBeEmitted(VD))
1729 return false;
1730
1731 if (VD->isStaticDataMember() &&
1732 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1733 return false;
1734 if (VD->isStaticDataMember() &&
1735 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1736 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1737 return false;
1738
1739 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1740 return false;
1741 } else {
1742 return false;
1743 }
1744
1745 // Only warn for unused decls internal to the translation unit.
1746 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1747 // for inline functions defined in the main source file, for instance.
1748 return mightHaveNonExternalLinkage(D);
1749}
1750
1751void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1752 if (!D)
1753 return;
1754
1755 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1756 const FunctionDecl *First = FD->getFirstDecl();
1757 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1758 return; // First should already be in the vector.
1759 }
1760
1761 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1762 const VarDecl *First = VD->getFirstDecl();
1763 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1764 return; // First should already be in the vector.
1765 }
1766
1767 if (ShouldWarnIfUnusedFileScopedDecl(D))
1768 UnusedFileScopedDecls.push_back(D);
1769}
1770
1771static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1772 if (D->isInvalidDecl())
1773 return false;
1774
1775 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1776 // For a decomposition declaration, warn if none of the bindings are
1777 // referenced, instead of if the variable itself is referenced (which
1778 // it is, by the bindings' expressions).
1779 for (auto *BD : DD->bindings())
1780 if (BD->isReferenced())
1781 return false;
1782 } else if (!D->getDeclName()) {
1783 return false;
1784 } else if (D->isReferenced() || D->isUsed()) {
1785 return false;
1786 }
1787
1788 if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1789 return false;
1790
1791 if (isa<LabelDecl>(D))
1792 return true;
1793
1794 // Except for labels, we only care about unused decls that are local to
1795 // functions.
1796 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1797 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1798 // For dependent types, the diagnostic is deferred.
1799 WithinFunction =
1800 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1801 if (!WithinFunction)
1802 return false;
1803
1804 if (isa<TypedefNameDecl>(D))
1805 return true;
1806
1807 // White-list anything that isn't a local variable.
1808 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1809 return false;
1810
1811 // Types of valid local variables should be complete, so this should succeed.
1812 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1813
1814 // White-list anything with an __attribute__((unused)) type.
1815 const auto *Ty = VD->getType().getTypePtr();
1816
1817 // Only look at the outermost level of typedef.
1818 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1819 if (TT->getDecl()->hasAttr<UnusedAttr>())
1820 return false;
1821 }
1822
1823 // If we failed to complete the type for some reason, or if the type is
1824 // dependent, don't diagnose the variable.
1825 if (Ty->isIncompleteType() || Ty->isDependentType())
1826 return false;
1827
1828 // Look at the element type to ensure that the warning behaviour is
1829 // consistent for both scalars and arrays.
1830 Ty = Ty->getBaseElementTypeUnsafe();
1831
1832 if (const TagType *TT = Ty->getAs<TagType>()) {
1833 const TagDecl *Tag = TT->getDecl();
1834 if (Tag->hasAttr<UnusedAttr>())
1835 return false;
1836
1837 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1838 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1839 return false;
1840
1841 if (const Expr *Init = VD->getInit()) {
1842 if (const ExprWithCleanups *Cleanups =
1843 dyn_cast<ExprWithCleanups>(Init))
1844 Init = Cleanups->getSubExpr();
1845 const CXXConstructExpr *Construct =
1846 dyn_cast<CXXConstructExpr>(Init);
1847 if (Construct && !Construct->isElidable()) {
1848 CXXConstructorDecl *CD = Construct->getConstructor();
1849 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1850 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1851 return false;
1852 }
1853
1854 // Suppress the warning if we don't know how this is constructed, and
1855 // it could possibly be non-trivial constructor.
1856 if (Init->isTypeDependent())
1857 for (const CXXConstructorDecl *Ctor : RD->ctors())
1858 if (!Ctor->isTrivial())
1859 return false;
1860 }
1861 }
1862 }
1863
1864 // TODO: __attribute__((unused)) templates?
1865 }
1866
1867 return true;
1868}
1869
1870static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1871 FixItHint &Hint) {
1872 if (isa<LabelDecl>(D)) {
1873 SourceLocation AfterColon = Lexer::findLocationAfterToken(
1874 D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1875 true);
1876 if (AfterColon.isInvalid())
1877 return;
1878 Hint = FixItHint::CreateRemoval(
1879 CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1880 }
1881}
1882
1883void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1884 if (D->getTypeForDecl()->isDependentType())
1885 return;
1886
1887 for (auto *TmpD : D->decls()) {
1888 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1889 DiagnoseUnusedDecl(T);
1890 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1891 DiagnoseUnusedNestedTypedefs(R);
1892 }
1893}
1894
1895/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1896/// unless they are marked attr(unused).
1897void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1898 if (!ShouldDiagnoseUnusedDecl(D))
1899 return;
1900
1901 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1902 // typedefs can be referenced later on, so the diagnostics are emitted
1903 // at end-of-translation-unit.
1904 UnusedLocalTypedefNameCandidates.insert(TD);
1905 return;
1906 }
1907
1908 FixItHint Hint;
1909 GenerateFixForUnusedDecl(D, Context, Hint);
1910
1911 unsigned DiagID;
1912 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1913 DiagID = diag::warn_unused_exception_param;
1914 else if (isa<LabelDecl>(D))
1915 DiagID = diag::warn_unused_label;
1916 else
1917 DiagID = diag::warn_unused_variable;
1918
1919 Diag(D->getLocation(), DiagID) << D << Hint;
1920}
1921
1922void Sema::DiagnoseUnusedButSetDecl(const VarDecl *VD) {
1923 // If it's not referenced, it can't be set.
1924 if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>())
1925 return;
1926
1927 const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
1928
1929 if (Ty->isReferenceType() || Ty->isDependentType())
1930 return;
1931
1932 if (const TagType *TT = Ty->getAs<TagType>()) {
1933 const TagDecl *Tag = TT->getDecl();
1934 if (Tag->hasAttr<UnusedAttr>())
1935 return;
1936 // In C++, don't warn for record types that don't have WarnUnusedAttr, to
1937 // mimic gcc's behavior.
1938 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1939 if (!RD->hasAttr<WarnUnusedAttr>())
1940 return;
1941 }
1942 }
1943
1944 auto iter = RefsMinusAssignments.find(VD);
1945 if (iter == RefsMinusAssignments.end())
1946 return;
1947
1948 assert(iter->getSecond() >= 0 &&((void)0)
1949 "Found a negative number of references to a VarDecl")((void)0);
1950 if (iter->getSecond() != 0)
1951 return;
1952 unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
1953 : diag::warn_unused_but_set_variable;
1954 Diag(VD->getLocation(), DiagID) << VD;
1955}
1956
1957static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1958 // Verify that we have no forward references left. If so, there was a goto
1959 // or address of a label taken, but no definition of it. Label fwd
1960 // definitions are indicated with a null substmt which is also not a resolved
1961 // MS inline assembly label name.
1962 bool Diagnose = false;
1963 if (L->isMSAsmLabel())
1964 Diagnose = !L->isResolvedMSAsmLabel();
1965 else
1966 Diagnose = L->getStmt() == nullptr;
1967 if (Diagnose)
1968 S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
1969}
1970
1971void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1972 S->mergeNRVOIntoParent();
1973
1974 if (S->decl_empty()) return;
1975 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&((void)0)
1976 "Scope shouldn't contain decls!")((void)0);
1977
1978 for (auto *TmpD : S->decls()) {
1979 assert(TmpD && "This decl didn't get pushed??")((void)0);
1980
1981 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")((void)0);
1982 NamedDecl *D = cast<NamedDecl>(TmpD);
1983
1984 // Diagnose unused variables in this scope.
1985 if (!S->hasUnrecoverableErrorOccurred()) {
1986 DiagnoseUnusedDecl(D);
1987 if (const auto *RD = dyn_cast<RecordDecl>(D))
1988 DiagnoseUnusedNestedTypedefs(RD);
1989 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1990 DiagnoseUnusedButSetDecl(VD);
1991 RefsMinusAssignments.erase(VD);
1992 }
1993 }
1994
1995 if (!D->getDeclName()) continue;
1996
1997 // If this was a forward reference to a label, verify it was defined.
1998 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1999 CheckPoppedLabel(LD, *this);
2000
2001 // Remove this name from our lexical scope, and warn on it if we haven't
2002 // already.
2003 IdResolver.RemoveDecl(D);
2004 auto ShadowI = ShadowingDecls.find(D);
2005 if (ShadowI != ShadowingDecls.end()) {
2006 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2007 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2008 << D << FD << FD->getParent();
2009 Diag(FD->getLocation(), diag::note_previous_declaration);
2010 }
2011 ShadowingDecls.erase(ShadowI);
2012 }
2013 }
2014}
2015
2016/// Look for an Objective-C class in the translation unit.
2017///
2018/// \param Id The name of the Objective-C class we're looking for. If
2019/// typo-correction fixes this name, the Id will be updated
2020/// to the fixed name.
2021///
2022/// \param IdLoc The location of the name in the translation unit.
2023///
2024/// \param DoTypoCorrection If true, this routine will attempt typo correction
2025/// if there is no class with the given name.
2026///
2027/// \returns The declaration of the named Objective-C class, or NULL if the
2028/// class could not be found.
2029ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
2030 SourceLocation IdLoc,
2031 bool DoTypoCorrection) {
2032 // The third "scope" argument is 0 since we aren't enabling lazy built-in
2033 // creation from this context.
2034 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2035
2036 if (!IDecl && DoTypoCorrection) {
2037 // Perform typo correction at the given location, but only if we
2038 // find an Objective-C class name.
2039 DeclFilterCCC<ObjCInterfaceDecl> CCC{};
2040 if (TypoCorrection C =
2041 CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2042 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2043 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2044 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2045 Id = IDecl->getIdentifier();
2046 }
2047 }
2048 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2049 // This routine must always return a class definition, if any.
2050 if (Def && Def->getDefinition())
2051 Def = Def->getDefinition();
2052 return Def;
2053}
2054
2055/// getNonFieldDeclScope - Retrieves the innermost scope, starting
2056/// from S, where a non-field would be declared. This routine copes
2057/// with the difference between C and C++ scoping rules in structs and
2058/// unions. For example, the following code is well-formed in C but
2059/// ill-formed in C++:
2060/// @code
2061/// struct S6 {
2062/// enum { BAR } e;
2063/// };
2064///
2065/// void test_S6() {
2066/// struct S6 a;
2067/// a.e = BAR;
2068/// }
2069/// @endcode
2070/// For the declaration of BAR, this routine will return a different
2071/// scope. The scope S will be the scope of the unnamed enumeration
2072/// within S6. In C++, this routine will return the scope associated
2073/// with S6, because the enumeration's scope is a transparent
2074/// context but structures can contain non-field names. In C, this
2075/// routine will return the translation unit scope, since the
2076/// enumeration's scope is a transparent context and structures cannot
2077/// contain non-field names.
2078Scope *Sema::getNonFieldDeclScope(Scope *S) {
2079 while (((S->getFlags() & Scope::DeclScope) == 0) ||
2080 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2081 (S->isClassScope() && !getLangOpts().CPlusPlus))
2082 S = S->getParent();
2083 return S;
2084}
2085
2086static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2087 ASTContext::GetBuiltinTypeError Error) {
2088 switch (Error) {
2089 case ASTContext::GE_None:
2090 return "";
2091 case ASTContext::GE_Missing_type:
2092 return BuiltinInfo.getHeaderName(ID);
2093 case ASTContext::GE_Missing_stdio:
2094 return "stdio.h";
2095 case ASTContext::GE_Missing_setjmp:
2096 return "setjmp.h";
2097 case ASTContext::GE_Missing_ucontext:
2098 return "ucontext.h";
2099 }
2100 llvm_unreachable("unhandled error kind")__builtin_unreachable();
2101}
2102
2103FunctionDecl *Sema::CreateBuiltin(IdentifierInfo *II, QualType Type,
2104 unsigned ID, SourceLocation Loc) {
2105 DeclContext *Parent = Context.getTranslationUnitDecl();
2106
2107 if (getLangOpts().CPlusPlus) {
2108 LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2109 Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2110 CLinkageDecl->setImplicit();
2111 Parent->addDecl(CLinkageDecl);
2112 Parent = CLinkageDecl;
2113 }
2114
2115 FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2116 /*TInfo=*/nullptr, SC_Extern, false,
2117 Type->isFunctionProtoType());
2118 New->setImplicit();
2119 New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2120
2121 // Create Decl objects for each parameter, adding them to the
2122 // FunctionDecl.
2123 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2124 SmallVector<ParmVarDecl *, 16> Params;
2125 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2126 ParmVarDecl *parm = ParmVarDecl::Create(
2127 Context, New, SourceLocation(), SourceLocation(), nullptr,
2128 FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2129 parm->setScopeInfo(0, i);
2130 Params.push_back(parm);
2131 }
2132 New->setParams(Params);
2133 }
2134
2135 AddKnownFunctionAttributes(New);
2136 return New;
2137}
2138
2139/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2140/// file scope. lazily create a decl for it. ForRedeclaration is true
2141/// if we're creating this built-in in anticipation of redeclaring the
2142/// built-in.
2143NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
2144 Scope *S, bool ForRedeclaration,
2145 SourceLocation Loc) {
2146 LookupNecessaryTypesForBuiltin(S, ID);
2147
2148 ASTContext::GetBuiltinTypeError Error;
2149 QualType R = Context.GetBuiltinType(ID, Error);
2150 if (Error) {
2151 if (!ForRedeclaration)
2152 return nullptr;
2153
2154 // If we have a builtin without an associated type we should not emit a
2155 // warning when we were not able to find a type for it.
2156 if (Error == ASTContext::GE_Missing_type ||
2157 Context.BuiltinInfo.allowTypeMismatch(ID))
2158 return nullptr;
2159
2160 // If we could not find a type for setjmp it is because the jmp_buf type was
2161 // not defined prior to the setjmp declaration.
2162 if (Error == ASTContext::GE_Missing_setjmp) {
2163 Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2164 << Context.BuiltinInfo.getName(ID);
2165 return nullptr;
2166 }
2167
2168 // Generally, we emit a warning that the declaration requires the
2169 // appropriate header.
2170 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2171 << getHeaderName(Context.BuiltinInfo, ID, Error)
2172 << Context.BuiltinInfo.getName(ID);
2173 return nullptr;
2174 }
2175
2176 if (!ForRedeclaration &&
2177 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
2178 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
2179 Diag(Loc, diag::ext_implicit_lib_function_decl)
2180 << Context.BuiltinInfo.getName(ID) << R;
2181 if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2182 Diag(Loc, diag::note_include_header_or_declare)
2183 << Header << Context.BuiltinInfo.getName(ID);
2184 }
2185
2186 if (R.isNull())
2187 return nullptr;
2188
2189 FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2190 RegisterLocallyScopedExternCDecl(New, S);
2191
2192 // TUScope is the translation-unit scope to insert this function into.
2193 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2194 // relate Scopes to DeclContexts, and probably eliminate CurContext
2195 // entirely, but we're not there yet.
2196 DeclContext *SavedContext = CurContext;
2197 CurContext = New->getDeclContext();
2198 PushOnScopeChains(New, TUScope);
2199 CurContext = SavedContext;
2200 return New;
2201}
2202
2203/// Typedef declarations don't have linkage, but they still denote the same
2204/// entity if their types are the same.
2205/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2206/// isSameEntity.
2207static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2208 TypedefNameDecl *Decl,
2209 LookupResult &Previous) {
2210 // This is only interesting when modules are enabled.
2211 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2212 return;
2213
2214 // Empty sets are uninteresting.
2215 if (Previous.empty())
2216 return;
2217
2218 LookupResult::Filter Filter = Previous.makeFilter();
2219 while (Filter.hasNext()) {
2220 NamedDecl *Old = Filter.next();
2221
2222 // Non-hidden declarations are never ignored.
2223 if (S.isVisible(Old))
2224 continue;
2225
2226 // Declarations of the same entity are not ignored, even if they have
2227 // different linkages.
2228 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2229 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2230 Decl->getUnderlyingType()))
2231 continue;
2232
2233 // If both declarations give a tag declaration a typedef name for linkage
2234 // purposes, then they declare the same entity.
2235 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2236 Decl->getAnonDeclWithTypedefName())
2237 continue;
2238 }
2239
2240 Filter.erase();
2241 }
2242
2243 Filter.done();
2244}
2245
2246bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2247 QualType OldType;
2248 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2249 OldType = OldTypedef->getUnderlyingType();
2250 else
2251 OldType = Context.getTypeDeclType(Old);
2252 QualType NewType = New->getUnderlyingType();
2253
2254 if (NewType->isVariablyModifiedType()) {
2255 // Must not redefine a typedef with a variably-modified type.
2256 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2257 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2258 << Kind << NewType;
2259 if (Old->getLocation().isValid())
2260 notePreviousDefinition(Old, New->getLocation());
2261 New->setInvalidDecl();
2262 return true;
2263 }
2264
2265 if (OldType != NewType &&
2266 !OldType->isDependentType() &&
2267 !NewType->isDependentType() &&
2268 !Context.hasSameType(OldType, NewType)) {
2269 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2270 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2271 << Kind << NewType << OldType;
2272 if (Old->getLocation().isValid())
2273 notePreviousDefinition(Old, New->getLocation());
2274 New->setInvalidDecl();
2275 return true;
2276 }
2277 return false;
2278}
2279
2280/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2281/// same name and scope as a previous declaration 'Old'. Figure out
2282/// how to resolve this situation, merging decls or emitting
2283/// diagnostics as appropriate. If there was an error, set New to be invalid.
2284///
2285void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2286 LookupResult &OldDecls) {
2287 // If the new decl is known invalid already, don't bother doing any
2288 // merging checks.
2289 if (New->isInvalidDecl()) return;
2290
2291 // Allow multiple definitions for ObjC built-in typedefs.
2292 // FIXME: Verify the underlying types are equivalent!
2293 if (getLangOpts().ObjC) {
2294 const IdentifierInfo *TypeID = New->getIdentifier();
2295 switch (TypeID->getLength()) {
2296 default: break;
2297 case 2:
2298 {
2299 if (!TypeID->isStr("id"))
2300 break;
2301 QualType T = New->getUnderlyingType();
2302 if (!T->isPointerType())
2303 break;
2304 if (!T->isVoidPointerType()) {
2305 QualType PT = T->castAs<PointerType>()->getPointeeType();
2306 if (!PT->isStructureType())
2307 break;
2308 }
2309 Context.setObjCIdRedefinitionType(T);
2310 // Install the built-in type for 'id', ignoring the current definition.
2311 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2312 return;
2313 }
2314 case 5:
2315 if (!TypeID->isStr("Class"))
2316 break;
2317 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2318 // Install the built-in type for 'Class', ignoring the current definition.
2319 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2320 return;
2321 case 3:
2322 if (!TypeID->isStr("SEL"))
2323 break;
2324 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2325 // Install the built-in type for 'SEL', ignoring the current definition.
2326 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2327 return;
2328 }
2329 // Fall through - the typedef name was not a builtin type.
2330 }
2331
2332 // Verify the old decl was also a type.
2333 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2334 if (!Old) {
2335 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2336 << New->getDeclName();
2337
2338 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2339 if (OldD->getLocation().isValid())
2340 notePreviousDefinition(OldD, New->getLocation());
2341
2342 return New->setInvalidDecl();
2343 }
2344
2345 // If the old declaration is invalid, just give up here.
2346 if (Old->isInvalidDecl())
2347 return New->setInvalidDecl();
2348
2349 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2350 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2351 auto *NewTag = New->getAnonDeclWithTypedefName();
2352 NamedDecl *Hidden = nullptr;
2353 if (OldTag && NewTag &&
2354 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2355 !hasVisibleDefinition(OldTag, &Hidden)) {
2356 // There is a definition of this tag, but it is not visible. Use it
2357 // instead of our tag.
2358 New->setTypeForDecl(OldTD->getTypeForDecl());
2359 if (OldTD->isModed())
2360 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2361 OldTD->getUnderlyingType());
2362 else
2363 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2364
2365 // Make the old tag definition visible.
2366 makeMergedDefinitionVisible(Hidden);
2367
2368 // If this was an unscoped enumeration, yank all of its enumerators
2369 // out of the scope.
2370 if (isa<EnumDecl>(NewTag)) {
2371 Scope *EnumScope = getNonFieldDeclScope(S);
2372 for (auto *D : NewTag->decls()) {
2373 auto *ED = cast<EnumConstantDecl>(D);
2374 assert(EnumScope->isDeclScope(ED))((void)0);
2375 EnumScope->RemoveDecl(ED);
2376 IdResolver.RemoveDecl(ED);
2377 ED->getLexicalDeclContext()->removeDecl(ED);
2378 }
2379 }
2380 }
2381 }
2382
2383 // If the typedef types are not identical, reject them in all languages and
2384 // with any extensions enabled.
2385 if (isIncompatibleTypedef(Old, New))
2386 return;
2387
2388 // The types match. Link up the redeclaration chain and merge attributes if
2389 // the old declaration was a typedef.
2390 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2391 New->setPreviousDecl(Typedef);
2392 mergeDeclAttributes(New, Old);
2393 }
2394
2395 if (getLangOpts().MicrosoftExt)
2396 return;
2397
2398 if (getLangOpts().CPlusPlus) {
2399 // C++ [dcl.typedef]p2:
2400 // In a given non-class scope, a typedef specifier can be used to
2401 // redefine the name of any type declared in that scope to refer
2402 // to the type to which it already refers.
2403 if (!isa<CXXRecordDecl>(CurContext))
2404 return;
2405
2406 // C++0x [dcl.typedef]p4:
2407 // In a given class scope, a typedef specifier can be used to redefine
2408 // any class-name declared in that scope that is not also a typedef-name
2409 // to refer to the type to which it already refers.
2410 //
2411 // This wording came in via DR424, which was a correction to the
2412 // wording in DR56, which accidentally banned code like:
2413 //
2414 // struct S {
2415 // typedef struct A { } A;
2416 // };
2417 //
2418 // in the C++03 standard. We implement the C++0x semantics, which
2419 // allow the above but disallow
2420 //
2421 // struct S {
2422 // typedef int I;
2423 // typedef int I;
2424 // };
2425 //
2426 // since that was the intent of DR56.
2427 if (!isa<TypedefNameDecl>(Old))
2428 return;
2429
2430 Diag(New->getLocation(), diag::err_redefinition)
2431 << New->getDeclName();
2432 notePreviousDefinition(Old, New->getLocation());
2433 return New->setInvalidDecl();
2434 }
2435
2436 // Modules always permit redefinition of typedefs, as does C11.
2437 if (getLangOpts().Modules || getLangOpts().C11)
2438 return;
2439
2440 // If we have a redefinition of a typedef in C, emit a warning. This warning
2441 // is normally mapped to an error, but can be controlled with
2442 // -Wtypedef-redefinition. If either the original or the redefinition is
2443 // in a system header, don't emit this for compatibility with GCC.
2444 if (getDiagnostics().getSuppressSystemWarnings() &&
2445 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2446 (Old->isImplicit() ||
2447 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2448 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2449 return;
2450
2451 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2452 << New->getDeclName();
2453 notePreviousDefinition(Old, New->getLocation());
2454}
2455
2456/// DeclhasAttr - returns true if decl Declaration already has the target
2457/// attribute.
2458static bool DeclHasAttr(const Decl *D, const Attr *A) {
2459 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2460 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2461 for (const auto *i : D->attrs())
2462 if (i->getKind() == A->getKind()) {
2463 if (Ann) {
2464 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2465 return true;
2466 continue;
2467 }
2468 // FIXME: Don't hardcode this check
2469 if (OA && isa<OwnershipAttr>(i))
2470 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2471 return true;
2472 }
2473
2474 return false;
2475}
2476
2477static bool isAttributeTargetADefinition(Decl *D) {
2478 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2479 return VD->isThisDeclarationADefinition();
2480 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2481 return TD->isCompleteDefinition() || TD->isBeingDefined();
2482 return true;
2483}
2484
2485/// Merge alignment attributes from \p Old to \p New, taking into account the
2486/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2487///
2488/// \return \c true if any attributes were added to \p New.
2489static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2490 // Look for alignas attributes on Old, and pick out whichever attribute
2491 // specifies the strictest alignment requirement.
2492 AlignedAttr *OldAlignasAttr = nullptr;
2493 AlignedAttr *OldStrictestAlignAttr = nullptr;
2494 unsigned OldAlign = 0;
2495 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2496 // FIXME: We have no way of representing inherited dependent alignments
2497 // in a case like:
2498 // template<int A, int B> struct alignas(A) X;
2499 // template<int A, int B> struct alignas(B) X {};
2500 // For now, we just ignore any alignas attributes which are not on the
2501 // definition in such a case.
2502 if (I->isAlignmentDependent())
2503 return false;
2504
2505 if (I->isAlignas())
2506 OldAlignasAttr = I;
2507
2508 unsigned Align = I->getAlignment(S.Context);
2509 if (Align > OldAlign) {
2510 OldAlign = Align;
2511 OldStrictestAlignAttr = I;
2512 }
2513 }
2514
2515 // Look for alignas attributes on New.
2516 AlignedAttr *NewAlignasAttr = nullptr;
2517 unsigned NewAlign = 0;
2518 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2519 if (I->isAlignmentDependent())
2520 return false;
2521
2522 if (I->isAlignas())
2523 NewAlignasAttr = I;
2524
2525 unsigned Align = I->getAlignment(S.Context);
2526 if (Align > NewAlign)
2527 NewAlign = Align;
2528 }
2529
2530 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2531 // Both declarations have 'alignas' attributes. We require them to match.
2532 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2533 // fall short. (If two declarations both have alignas, they must both match
2534 // every definition, and so must match each other if there is a definition.)
2535
2536 // If either declaration only contains 'alignas(0)' specifiers, then it
2537 // specifies the natural alignment for the type.
2538 if (OldAlign == 0 || NewAlign == 0) {
2539 QualType Ty;
2540 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2541 Ty = VD->getType();
2542 else
2543 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2544
2545 if (OldAlign == 0)
2546 OldAlign = S.Context.getTypeAlign(Ty);
2547 if (NewAlign == 0)
2548 NewAlign = S.Context.getTypeAlign(Ty);
2549 }
2550
2551 if (OldAlign != NewAlign) {
2552 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2553 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2554 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2555 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2556 }
2557 }
2558
2559 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2560 // C++11 [dcl.align]p6:
2561 // if any declaration of an entity has an alignment-specifier,
2562 // every defining declaration of that entity shall specify an
2563 // equivalent alignment.
2564 // C11 6.7.5/7:
2565 // If the definition of an object does not have an alignment
2566 // specifier, any other declaration of that object shall also
2567 // have no alignment specifier.
2568 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2569 << OldAlignasAttr;
2570 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2571 << OldAlignasAttr;
2572 }
2573
2574 bool AnyAdded = false;
2575
2576 // Ensure we have an attribute representing the strictest alignment.
2577 if (OldAlign > NewAlign) {
2578 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2579 Clone->setInherited(true);
2580 New->addAttr(Clone);
2581 AnyAdded = true;
2582 }
2583
2584 // Ensure we have an alignas attribute if the old declaration had one.
2585 if (OldAlignasAttr && !NewAlignasAttr &&
2586 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2587 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2588 Clone->setInherited(true);
2589 New->addAttr(Clone);
2590 AnyAdded = true;
2591 }
2592
2593 return AnyAdded;
2594}
2595
2596#define WANT_DECL_MERGE_LOGIC
2597#include "clang/Sema/AttrParsedAttrImpl.inc"
2598#undef WANT_DECL_MERGE_LOGIC
2599
2600static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2601 const InheritableAttr *Attr,
2602 Sema::AvailabilityMergeKind AMK) {
2603 // Diagnose any mutual exclusions between the attribute that we want to add
2604 // and attributes that already exist on the declaration.
2605 if (!DiagnoseMutualExclusions(S, D, Attr))
2606 return false;
2607
2608 // This function copies an attribute Attr from a previous declaration to the
2609 // new declaration D if the new declaration doesn't itself have that attribute
2610 // yet or if that attribute allows duplicates.
2611 // If you're adding a new attribute that requires logic different from
2612 // "use explicit attribute on decl if present, else use attribute from
2613 // previous decl", for example if the attribute needs to be consistent
2614 // between redeclarations, you need to call a custom merge function here.
2615 InheritableAttr *NewAttr = nullptr;
2616 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2617 NewAttr = S.mergeAvailabilityAttr(
2618 D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2619 AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2620 AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2621 AA->getPriority());
2622 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2623 NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2624 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2625 NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2626 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2627 NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2628 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2629 NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2630 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2631 NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2632 FA->getFirstArg());
2633 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2634 NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2635 else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2636 NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2637 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2638 NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2639 IA->getInheritanceModel());
2640 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2641 NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2642 &S.Context.Idents.get(AA->getSpelling()));
2643 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2644 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2645 isa<CUDAGlobalAttr>(Attr))) {
2646 // CUDA target attributes are part of function signature for
2647 // overloading purposes and must not be merged.
2648 return false;
2649 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2650 NewAttr = S.mergeMinSizeAttr(D, *MA);
2651 else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2652 NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2653 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2654 NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2655 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2656 NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2657 else if (isa<AlignedAttr>(Attr))
2658 // AlignedAttrs are handled separately, because we need to handle all
2659 // such attributes on a declaration at the same time.
2660 NewAttr = nullptr;
2661 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2662 (AMK == Sema::AMK_Override ||
2663 AMK == Sema::AMK_ProtocolImplementation ||
2664 AMK == Sema::AMK_OptionalProtocolImplementation))
2665 NewAttr = nullptr;
2666 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2667 NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2668 else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2669 NewAttr = S.mergeImportModuleAttr(D, *IMA);
2670 else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2671 NewAttr = S.mergeImportNameAttr(D, *INA);
2672 else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2673 NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2674 else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2675 NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2676 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2677 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2678
2679 if (NewAttr) {
2680 NewAttr->setInherited(true);
2681 D->addAttr(NewAttr);
2682 if (isa<MSInheritanceAttr>(NewAttr))
2683 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2684 return true;
2685 }
2686
2687 return false;
2688}
2689
2690static const NamedDecl *getDefinition(const Decl *D) {
2691 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2692 return TD->getDefinition();
2693 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2694 const VarDecl *Def = VD->getDefinition();
2695 if (Def)
2696 return Def;
2697 return VD->getActingDefinition();
2698 }
2699 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2700 const FunctionDecl *Def = nullptr;
2701 if (FD->isDefined(Def, true))
2702 return Def;
2703 }
2704 return nullptr;
2705}
2706
2707static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2708 for (const auto *Attribute : D->attrs())
2709 if (Attribute->getKind() == Kind)
2710 return true;
2711 return false;
2712}
2713
2714/// checkNewAttributesAfterDef - If we already have a definition, check that
2715/// there are no new attributes in this declaration.
2716static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2717 if (!New->hasAttrs())
2718 return;
2719
2720 const NamedDecl *Def = getDefinition(Old);
2721 if (!Def || Def == New)
2722 return;
2723
2724 AttrVec &NewAttributes = New->getAttrs();
2725 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2726 const Attr *NewAttribute = NewAttributes[I];
2727
2728 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2729 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2730 Sema::SkipBodyInfo SkipBody;
2731 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2732
2733 // If we're skipping this definition, drop the "alias" attribute.
2734 if (SkipBody.ShouldSkip) {
2735 NewAttributes.erase(NewAttributes.begin() + I);
2736 --E;
2737 continue;
2738 }
2739 } else {
2740 VarDecl *VD = cast<VarDecl>(New);
2741 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2742 VarDecl::TentativeDefinition
2743 ? diag::err_alias_after_tentative
2744 : diag::err_redefinition;
2745 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2746 if (Diag == diag::err_redefinition)
2747 S.notePreviousDefinition(Def, VD->getLocation());
2748 else
2749 S.Diag(Def->getLocation(), diag::note_previous_definition);
2750 VD->setInvalidDecl();
2751 }
2752 ++I;
2753 continue;
2754 }
2755
2756 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2757 // Tentative definitions are only interesting for the alias check above.
2758 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2759 ++I;
2760 continue;
2761 }
2762 }
2763
2764 if (hasAttribute(Def, NewAttribute->getKind())) {
2765 ++I;
2766 continue; // regular attr merging will take care of validating this.
2767 }
2768
2769 if (isa<C11NoReturnAttr>(NewAttribute)) {
2770 // C's _Noreturn is allowed to be added to a function after it is defined.
2771 ++I;
2772 continue;
2773 } else if (isa<UuidAttr>(NewAttribute)) {
2774 // msvc will allow a subsequent definition to add an uuid to a class
2775 ++I;
2776 continue;
2777 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2778 if (AA->isAlignas()) {
2779 // C++11 [dcl.align]p6:
2780 // if any declaration of an entity has an alignment-specifier,
2781 // every defining declaration of that entity shall specify an
2782 // equivalent alignment.
2783 // C11 6.7.5/7:
2784 // If the definition of an object does not have an alignment
2785 // specifier, any other declaration of that object shall also
2786 // have no alignment specifier.
2787 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2788 << AA;
2789 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2790 << AA;
2791 NewAttributes.erase(NewAttributes.begin() + I);
2792 --E;
2793 continue;
2794 }
2795 } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2796 // If there is a C definition followed by a redeclaration with this
2797 // attribute then there are two different definitions. In C++, prefer the
2798 // standard diagnostics.
2799 if (!S.getLangOpts().CPlusPlus) {
2800 S.Diag(NewAttribute->getLocation(),
2801 diag::err_loader_uninitialized_redeclaration);
2802 S.Diag(Def->getLocation(), diag::note_previous_definition);
2803 NewAttributes.erase(NewAttributes.begin() + I);
2804 --E;
2805 continue;
2806 }
2807 } else if (isa<SelectAnyAttr>(NewAttribute) &&
2808 cast<VarDecl>(New)->isInline() &&
2809 !cast<VarDecl>(New)->isInlineSpecified()) {
2810 // Don't warn about applying selectany to implicitly inline variables.
2811 // Older compilers and language modes would require the use of selectany
2812 // to make such variables inline, and it would have no effect if we
2813 // honored it.
2814 ++I;
2815 continue;
2816 } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2817 // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2818 // declarations after defintions.
2819 ++I;
2820 continue;
2821 }
2822
2823 S.Diag(NewAttribute->getLocation(),
2824 diag::warn_attribute_precede_definition);
2825 S.Diag(Def->getLocation(), diag::note_previous_definition);
2826 NewAttributes.erase(NewAttributes.begin() + I);
2827 --E;
2828 }
2829}
2830
2831static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2832 const ConstInitAttr *CIAttr,
2833 bool AttrBeforeInit) {
2834 SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2835
2836 // Figure out a good way to write this specifier on the old declaration.
2837 // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2838 // enough of the attribute list spelling information to extract that without
2839 // heroics.
2840 std::string SuitableSpelling;
2841 if (S.getLangOpts().CPlusPlus20)
2842 SuitableSpelling = std::string(
2843 S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2844 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2845 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2846 InsertLoc, {tok::l_square, tok::l_square,
2847 S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2848 S.PP.getIdentifierInfo("require_constant_initialization"),
2849 tok::r_square, tok::r_square}));
2850 if (SuitableSpelling.empty())
2851 SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2852 InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2853 S.PP.getIdentifierInfo("require_constant_initialization"),
2854 tok::r_paren, tok::r_paren}));
2855 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
2856 SuitableSpelling = "constinit";
2857 if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2858 SuitableSpelling = "[[clang::require_constant_initialization]]";
2859 if (SuitableSpelling.empty())
2860 SuitableSpelling = "__attribute__((require_constant_initialization))";
2861 SuitableSpelling += " ";
2862
2863 if (AttrBeforeInit) {
2864 // extern constinit int a;
2865 // int a = 0; // error (missing 'constinit'), accepted as extension
2866 assert(CIAttr->isConstinit() && "should not diagnose this for attribute")((void)0);
2867 S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
2868 << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2869 S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
2870 } else {
2871 // int a = 0;
2872 // constinit extern int a; // error (missing 'constinit')
2873 S.Diag(CIAttr->getLocation(),
2874 CIAttr->isConstinit() ? diag::err_constinit_added_too_late
2875 : diag::warn_require_const_init_added_too_late)
2876 << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
2877 S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
2878 << CIAttr->isConstinit()
2879 << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
2880 }
2881}
2882
2883/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2884void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2885 AvailabilityMergeKind AMK) {
2886 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2887 UsedAttr *NewAttr = OldAttr->clone(Context);
2888 NewAttr->setInherited(true);
2889 New->addAttr(NewAttr);
2890 }
2891 if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
2892 RetainAttr *NewAttr = OldAttr->clone(Context);
2893 NewAttr->setInherited(true);
2894 New->addAttr(NewAttr);
2895 }
2896
2897 if (!Old->hasAttrs() && !New->hasAttrs())
2898 return;
2899
2900 // [dcl.constinit]p1:
2901 // If the [constinit] specifier is applied to any declaration of a
2902 // variable, it shall be applied to the initializing declaration.
2903 const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
2904 const auto *NewConstInit = New->getAttr<ConstInitAttr>();
2905 if (bool(OldConstInit) != bool(NewConstInit)) {
2906 const auto *OldVD = cast<VarDecl>(Old);
2907 auto *NewVD = cast<VarDecl>(New);
2908
2909 // Find the initializing declaration. Note that we might not have linked
2910 // the new declaration into the redeclaration chain yet.
2911 const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
2912 if (!InitDecl &&
2913 (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
2914 InitDecl = NewVD;
2915
2916 if (InitDecl == NewVD) {
2917 // This is the initializing declaration. If it would inherit 'constinit',
2918 // that's ill-formed. (Note that we do not apply this to the attribute
2919 // form).
2920 if (OldConstInit && OldConstInit->isConstinit())
2921 diagnoseMissingConstinit(*this, NewVD, OldConstInit,
2922 /*AttrBeforeInit=*/true);
2923 } else if (NewConstInit) {
2924 // This is the first time we've been told that this declaration should
2925 // have a constant initializer. If we already saw the initializing
2926 // declaration, this is too late.
2927 if (InitDecl && InitDecl != NewVD) {
2928 diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
2929 /*AttrBeforeInit=*/false);
2930 NewVD->dropAttr<ConstInitAttr>();
2931 }
2932 }
2933 }
2934
2935 // Attributes declared post-definition are currently ignored.
2936 checkNewAttributesAfterDef(*this, New, Old);
2937
2938 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2939 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2940 if (!OldA->isEquivalent(NewA)) {
2941 // This redeclaration changes __asm__ label.
2942 Diag(New->getLocation(), diag::err_different_asm_label);
2943 Diag(OldA->getLocation(), diag::note_previous_declaration);
2944 }
2945 } else if (Old->isUsed()) {
2946 // This redeclaration adds an __asm__ label to a declaration that has
2947 // already been ODR-used.
2948 Diag(New->getLocation(), diag::err_late_asm_label_name)
2949 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2950 }
2951 }
2952
2953 // Re-declaration cannot add abi_tag's.
2954 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2955 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2956 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2957 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2958 NewTag) == OldAbiTagAttr->tags_end()) {
2959 Diag(NewAbiTagAttr->getLocation(),
2960 diag::err_new_abi_tag_on_redeclaration)
2961 << NewTag;
2962 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2963 }
2964 }
2965 } else {
2966 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2967 Diag(Old->getLocation(), diag::note_previous_declaration);
2968 }
2969 }
2970
2971 // This redeclaration adds a section attribute.
2972 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2973 if (auto *VD = dyn_cast<VarDecl>(New)) {
2974 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2975 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2976 Diag(Old->getLocation(), diag::note_previous_declaration);
2977 }
2978 }
2979 }
2980
2981 // Redeclaration adds code-seg attribute.
2982 const auto *NewCSA = New->getAttr<CodeSegAttr>();
2983 if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2984 !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2985 Diag(New->getLocation(), diag::warn_mismatched_section)
2986 << 0 /*codeseg*/;
2987 Diag(Old->getLocation(), diag::note_previous_declaration);
2988 }
2989
2990 if (!Old->hasAttrs())
2991 return;
2992
2993 bool foundAny = New->hasAttrs();
2994
2995 // Ensure that any moving of objects within the allocated map is done before
2996 // we process them.
2997 if (!foundAny) New->setAttrs(AttrVec());
2998
2999 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3000 // Ignore deprecated/unavailable/availability attributes if requested.
3001 AvailabilityMergeKind LocalAMK = AMK_None;
3002 if (isa<DeprecatedAttr>(I) ||
3003 isa<UnavailableAttr>(I) ||
3004 isa<AvailabilityAttr>(I)) {
3005 switch (AMK) {
3006 case AMK_None:
3007 continue;
3008
3009 case AMK_Redeclaration:
3010 case AMK_Override:
3011 case AMK_ProtocolImplementation:
3012 case AMK_OptionalProtocolImplementation:
3013 LocalAMK = AMK;
3014 break;
3015 }
3016 }
3017
3018 // Already handled.
3019 if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3020 continue;
3021
3022 if (mergeDeclAttribute(*this, New, I, LocalAMK))
3023 foundAny = true;
3024 }
3025
3026 if (mergeAlignedAttrs(*this, New, Old))
3027 foundAny = true;
3028
3029 if (!foundAny) New->dropAttrs();
3030}
3031
3032/// mergeParamDeclAttributes - Copy attributes from the old parameter
3033/// to the new one.
3034static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
3035 const ParmVarDecl *oldDecl,
3036 Sema &S) {
3037 // C++11 [dcl.attr.depend]p2:
3038 // The first declaration of a function shall specify the
3039 // carries_dependency attribute for its declarator-id if any declaration
3040 // of the function specifies the carries_dependency attribute.
3041 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3042 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3043 S.Diag(CDA->getLocation(),
3044 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3045 // Find the first declaration of the parameter.
3046 // FIXME: Should we build redeclaration chains for function parameters?
3047 const FunctionDecl *FirstFD =
3048 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3049 const ParmVarDecl *FirstVD =
3050 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3051 S.Diag(FirstVD->getLocation(),
3052 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3053 }
3054
3055 if (!oldDecl->hasAttrs())
3056 return;
3057
3058 bool foundAny = newDecl->hasAttrs();
3059
3060 // Ensure that any moving of objects within the allocated map is
3061 // done before we process them.
3062 if (!foundAny) newDecl->setAttrs(AttrVec());
3063
3064 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3065 if (!DeclHasAttr(newDecl, I)) {
3066 InheritableAttr *newAttr =
3067 cast<InheritableParamAttr>(I->clone(S.Context));
3068 newAttr->setInherited(true);
3069 newDecl->addAttr(newAttr);
3070 foundAny = true;
3071 }
3072 }
3073
3074 if (!foundAny) newDecl->dropAttrs();
3075}
3076
3077static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3078 const ParmVarDecl *OldParam,
3079 Sema &S) {
3080 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3081 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3082 if (*Oldnullability != *Newnullability) {
3083 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3084 << DiagNullabilityKind(
3085 *Newnullability,
3086 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3087 != 0))
3088 << DiagNullabilityKind(
3089 *Oldnullability,
3090 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
3091 != 0));
3092 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3093 }
3094 } else {
3095 QualType NewT = NewParam->getType();
3096 NewT = S.Context.getAttributedType(
3097 AttributedType::getNullabilityAttrKind(*Oldnullability),
3098 NewT, NewT);
3099 NewParam->setType(NewT);
3100 }
3101 }
3102}
3103
3104namespace {
3105
3106/// Used in MergeFunctionDecl to keep track of function parameters in
3107/// C.
3108struct GNUCompatibleParamWarning {
3109 ParmVarDecl *OldParm;
3110 ParmVarDecl *NewParm;
3111 QualType PromotedType;
3112};
3113
3114} // end anonymous namespace
3115
3116// Determine whether the previous declaration was a definition, implicit
3117// declaration, or a declaration.
3118template <typename T>
3119static std::pair<diag::kind, SourceLocation>
3120getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3121 diag::kind PrevDiag;
3122 SourceLocation OldLocation = Old->getLocation();
3123 if (Old->isThisDeclarationADefinition())
3124 PrevDiag = diag::note_previous_definition;
3125 else if (Old->isImplicit()) {
3126 PrevDiag = diag::note_previous_implicit_declaration;
3127 if (OldLocation.isInvalid())
3128 OldLocation = New->getLocation();
3129 } else
3130 PrevDiag = diag::note_previous_declaration;
3131 return std::make_pair(PrevDiag, OldLocation);
3132}
3133
3134/// canRedefineFunction - checks if a function can be redefined. Currently,
3135/// only extern inline functions can be redefined, and even then only in
3136/// GNU89 mode.
3137static bool canRedefineFunction(const FunctionDecl *FD,
3138 const LangOptions& LangOpts) {
3139 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3140 !LangOpts.CPlusPlus &&
3141 FD->isInlineSpecified() &&
3142 FD->getStorageClass() == SC_Extern);
3143}
3144
3145const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
3146 const AttributedType *AT = T->getAs<AttributedType>();
3147 while (AT && !AT->isCallingConv())
3148 AT = AT->getModifiedType()->getAs<AttributedType>();
3149 return AT;
3150}
3151
3152template <typename T>
3153static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3154 const DeclContext *DC = Old->getDeclContext();
3155 if (DC->isRecord())
3156 return false;
3157
3158 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3159 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3160 return true;
3161 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3162 return true;
3163 return false;
3164}
3165
3166template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3167static bool isExternC(VarTemplateDecl *) { return false; }
3168static bool isExternC(FunctionTemplateDecl *) { return false; }
3169
3170/// Check whether a redeclaration of an entity introduced by a
3171/// using-declaration is valid, given that we know it's not an overload
3172/// (nor a hidden tag declaration).
3173template<typename ExpectedDecl>
3174static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
3175 ExpectedDecl *New) {
3176 // C++11 [basic.scope.declarative]p4:
3177 // Given a set of declarations in a single declarative region, each of
3178 // which specifies the same unqualified name,
3179 // -- they shall all refer to the same entity, or all refer to functions
3180 // and function templates; or
3181 // -- exactly one declaration shall declare a class name or enumeration
3182 // name that is not a typedef name and the other declarations shall all
3183 // refer to the same variable or enumerator, or all refer to functions
3184 // and function templates; in this case the class name or enumeration
3185 // name is hidden (3.3.10).
3186
3187 // C++11 [namespace.udecl]p14:
3188 // If a function declaration in namespace scope or block scope has the
3189 // same name and the same parameter-type-list as a function introduced
3190 // by a using-declaration, and the declarations do not declare the same
3191 // function, the program is ill-formed.
3192
3193 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3194 if (Old &&
3195 !Old->getDeclContext()->getRedeclContext()->Equals(
3196 New->getDeclContext()->getRedeclContext()) &&
3197 !(isExternC(Old) && isExternC(New)))
3198 Old = nullptr;
3199
3200 if (!Old) {
3201 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3202 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3203 S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3204 return true;
3205 }
3206 return false;
3207}
3208
3209static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
3210 const FunctionDecl *B) {
3211 assert(A->getNumParams() == B->getNumParams())((void)0);
3212
3213 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3214 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3215 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3216 if (AttrA == AttrB)
3217 return true;
3218 return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3219 AttrA->isDynamic() == AttrB->isDynamic();
3220 };
3221
3222 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3223}
3224
3225/// If necessary, adjust the semantic declaration context for a qualified
3226/// declaration to name the correct inline namespace within the qualifier.
3227static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
3228 DeclaratorDecl *OldD) {
3229 // The only case where we need to update the DeclContext is when
3230 // redeclaration lookup for a qualified name finds a declaration
3231 // in an inline namespace within the context named by the qualifier:
3232 //
3233 // inline namespace N { int f(); }
3234 // int ::f(); // Sema DC needs adjusting from :: to N::.
3235 //
3236 // For unqualified declarations, the semantic context *can* change
3237 // along the redeclaration chain (for local extern declarations,
3238 // extern "C" declarations, and friend declarations in particular).
3239 if (!NewD->getQualifier())
3240 return;
3241
3242 // NewD is probably already in the right context.
3243 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3244 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3245 if (NamedDC->Equals(SemaDC))
3246 return;
3247
3248 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||((void)0)
3249 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&((void)0)
3250 "unexpected context for redeclaration")((void)0);
3251
3252 auto *LexDC = NewD->getLexicalDeclContext();
3253 auto FixSemaDC = [=](NamedDecl *D) {
3254 if (!D)
3255 return;
3256 D->setDeclContext(SemaDC);
3257 D->setLexicalDeclContext(LexDC);
3258 };
3259
3260 FixSemaDC(NewD);
3261 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3262 FixSemaDC(FD->getDescribedFunctionTemplate());
3263 else if (auto *VD = dyn_cast<VarDecl>(NewD))
3264 FixSemaDC(VD->getDescribedVarTemplate());
3265}
3266
3267/// MergeFunctionDecl - We just parsed a function 'New' from
3268/// declarator D which has the same name and scope as a previous
3269/// declaration 'Old'. Figure out how to resolve this situation,
3270/// merging decls or emitting diagnostics as appropriate.
3271///
3272/// In C++, New and Old must be declarations that are not
3273/// overloaded. Use IsOverload to determine whether New and Old are
3274/// overloaded, and to select the Old declaration that New should be
3275/// merged with.
3276///
3277/// Returns true if there was an error, false otherwise.
3278bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
3279 Scope *S, bool MergeTypeWithOld) {
3280 // Verify the old decl was also a function.
3281 FunctionDecl *Old = OldD->getAsFunction();
3282 if (!Old) {
3283 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3284 if (New->getFriendObjectKind()) {
3285 Diag(New->getLocation(), diag::err_using_decl_friend);
3286 Diag(Shadow->getTargetDecl()->getLocation(),
3287 diag::note_using_decl_target);
3288 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3289 << 0;
3290 return true;
3291 }
3292
3293 // Check whether the two declarations might declare the same function or
3294 // function template.
3295 if (FunctionTemplateDecl *NewTemplate =
3296 New->getDescribedFunctionTemplate()) {
3297 if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3298 NewTemplate))
3299 return true;
3300 OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3301 ->getAsFunction();
3302 } else {
3303 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3304 return true;
3305 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3306 }
3307 } else {
3308 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3309 << New->getDeclName();
3310 notePreviousDefinition(OldD, New->getLocation());
3311 return true;
3312 }
3313 }
3314
3315 // If the old declaration was found in an inline namespace and the new
3316 // declaration was qualified, update the DeclContext to match.
3317 adjustDeclContextForDeclaratorDecl(New, Old);
3318
3319 // If the old declaration is invalid, just give up here.
3320 if (Old->isInvalidDecl())
3321 return true;
3322
3323 // Disallow redeclaration of some builtins.
3324 if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3325 Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3326 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3327 << Old << Old->getType();
3328 return true;
3329 }
3330
3331 diag::kind PrevDiag;
3332 SourceLocation OldLocation;
3333 std::tie(PrevDiag, OldLocation) =
3334 getNoteDiagForInvalidRedeclaration(Old, New);
3335
3336 // Don't complain about this if we're in GNU89 mode and the old function
3337 // is an extern inline function.
3338 // Don't complain about specializations. They are not supposed to have
3339 // storage classes.
3340 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3341 New->getStorageClass() == SC_Static &&
3342 Old->hasExternalFormalLinkage() &&
3343 !New->getTemplateSpecializationInfo() &&
3344 !canRedefineFunction(Old, getLangOpts())) {
3345 if (getLangOpts().MicrosoftExt) {
3346 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3347 Diag(OldLocation, PrevDiag);
3348 } else {
3349 Diag(New->getLocation(), diag::err_static_non_static) << New;
3350 Diag(OldLocation, PrevDiag);
3351 return true;
3352 }
3353 }
3354
3355 if (New->hasAttr<InternalLinkageAttr>() &&
3356 !Old->hasAttr<InternalLinkageAttr>()) {
3357 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3358 << New->getDeclName();
3359 notePreviousDefinition(Old, New->getLocation());
3360 New->dropAttr<InternalLinkageAttr>();
3361 }
3362
3363 if (CheckRedeclarationModuleOwnership(New, Old))
3364 return true;
3365
3366 if (!getLangOpts().CPlusPlus) {
3367 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3368 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3369 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3370 << New << OldOvl;
3371
3372 // Try our best to find a decl that actually has the overloadable
3373 // attribute for the note. In most cases (e.g. programs with only one
3374 // broken declaration/definition), this won't matter.
3375 //
3376 // FIXME: We could do this if we juggled some extra state in
3377 // OverloadableAttr, rather than just removing it.
3378 const Decl *DiagOld = Old;
3379 if (OldOvl) {
3380 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3381 const auto *A = D->getAttr<OverloadableAttr>();
3382 return A && !A->isImplicit();
3383 });
3384 // If we've implicitly added *all* of the overloadable attrs to this
3385 // chain, emitting a "previous redecl" note is pointless.
3386 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3387 }
3388
3389 if (DiagOld)
3390 Diag(DiagOld->getLocation(),
3391 diag::note_attribute_overloadable_prev_overload)
3392 << OldOvl;
3393
3394 if (OldOvl)
3395 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3396 else
3397 New->dropAttr<OverloadableAttr>();
3398 }
3399 }
3400
3401 // If a function is first declared with a calling convention, but is later
3402 // declared or defined without one, all following decls assume the calling
3403 // convention of the first.
3404 //
3405 // It's OK if a function is first declared without a calling convention,
3406 // but is later declared or defined with the default calling convention.
3407 //
3408 // To test if either decl has an explicit calling convention, we look for
3409 // AttributedType sugar nodes on the type as written. If they are missing or
3410 // were canonicalized away, we assume the calling convention was implicit.
3411 //
3412 // Note also that we DO NOT return at this point, because we still have
3413 // other tests to run.
3414 QualType OldQType = Context.getCanonicalType(Old->getType());
3415 QualType NewQType = Context.getCanonicalType(New->getType());
3416 const FunctionType *OldType = cast<FunctionType>(OldQType);
3417 const FunctionType *NewType = cast<FunctionType>(NewQType);
3418 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3419 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3420 bool RequiresAdjustment = false;
3421
3422 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3423 FunctionDecl *First = Old->getFirstDecl();
3424 const FunctionType *FT =
3425 First->getType().getCanonicalType()->castAs<FunctionType>();
3426 FunctionType::ExtInfo FI = FT->getExtInfo();
3427 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3428 if (!NewCCExplicit) {
3429 // Inherit the CC from the previous declaration if it was specified
3430 // there but not here.
3431 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3432 RequiresAdjustment = true;
3433 } else if (Old->getBuiltinID()) {
3434 // Builtin attribute isn't propagated to the new one yet at this point,
3435 // so we check if the old one is a builtin.
3436
3437 // Calling Conventions on a Builtin aren't really useful and setting a
3438 // default calling convention and cdecl'ing some builtin redeclarations is
3439 // common, so warn and ignore the calling convention on the redeclaration.
3440 Diag(New->getLocation(), diag::warn_cconv_unsupported)
3441 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3442 << (int)CallingConventionIgnoredReason::BuiltinFunction;
3443 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3444 RequiresAdjustment = true;
3445 } else {
3446 // Calling conventions aren't compatible, so complain.
3447 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3448 Diag(New->getLocation(), diag::err_cconv_change)
3449 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3450 << !FirstCCExplicit
3451 << (!FirstCCExplicit ? "" :
3452 FunctionType::getNameForCallConv(FI.getCC()));
3453
3454 // Put the note on the first decl, since it is the one that matters.
3455 Diag(First->getLocation(), diag::note_previous_declaration);
3456 return true;
3457 }
3458 }
3459
3460 // FIXME: diagnose the other way around?
3461 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3462 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3463 RequiresAdjustment = true;
3464 }
3465
3466 // Merge regparm attribute.
3467 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3468 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3469 if (NewTypeInfo.getHasRegParm()) {
3470 Diag(New->getLocation(), diag::err_regparm_mismatch)
3471 << NewType->getRegParmType()
3472 << OldType->getRegParmType();
3473 Diag(OldLocation, diag::note_previous_declaration);
3474 return true;
3475 }
3476
3477 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3478 RequiresAdjustment = true;
3479 }
3480
3481 // Merge ns_returns_retained attribute.
3482 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3483 if (NewTypeInfo.getProducesResult()) {
3484 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3485 << "'ns_returns_retained'";
3486 Diag(OldLocation, diag::note_previous_declaration);
3487 return true;
3488 }
3489
3490 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3491 RequiresAdjustment = true;
3492 }
3493
3494 if (OldTypeInfo.getNoCallerSavedRegs() !=
3495 NewTypeInfo.getNoCallerSavedRegs()) {
3496 if (NewTypeInfo.getNoCallerSavedRegs()) {
3497 AnyX86NoCallerSavedRegistersAttr *Attr =
3498 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3499 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3500 Diag(OldLocation, diag::note_previous_declaration);
3501 return true;
3502 }
3503
3504 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3505 RequiresAdjustment = true;
3506 }
3507
3508 if (RequiresAdjustment) {
3509 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3510 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3511 New->setType(QualType(AdjustedType, 0));
3512 NewQType = Context.getCanonicalType(New->getType());
3513 }
3514
3515 // If this redeclaration makes the function inline, we may need to add it to
3516 // UndefinedButUsed.
3517 if (!Old->isInlined() && New->isInlined() &&
3518 !New->hasAttr<GNUInlineAttr>() &&
3519 !getLangOpts().GNUInline &&
3520 Old->isUsed(false) &&
3521 !Old->isDefined() && !New->isThisDeclarationADefinition())
3522 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3523 SourceLocation()));
3524
3525 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3526 // about it.
3527 if (New->hasAttr<GNUInlineAttr>() &&
3528 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3529 UndefinedButUsed.erase(Old->getCanonicalDecl());
3530 }
3531
3532 // If pass_object_size params don't match up perfectly, this isn't a valid
3533 // redeclaration.
3534 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3535 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3536 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3537 << New->getDeclName();
3538 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3539 return true;
3540 }
3541
3542 if (getLangOpts().CPlusPlus) {
3543 // C++1z [over.load]p2
3544 // Certain function declarations cannot be overloaded:
3545 // -- Function declarations that differ only in the return type,
3546 // the exception specification, or both cannot be overloaded.
3547
3548 // Check the exception specifications match. This may recompute the type of
3549 // both Old and New if it resolved exception specifications, so grab the
3550 // types again after this. Because this updates the type, we do this before
3551 // any of the other checks below, which may update the "de facto" NewQType
3552 // but do not necessarily update the type of New.
3553 if (CheckEquivalentExceptionSpec(Old, New))
3554 return true;
3555 OldQType = Context.getCanonicalType(Old->getType());
3556 NewQType = Context.getCanonicalType(New->getType());
3557
3558 // Go back to the type source info to compare the declared return types,
3559 // per C++1y [dcl.type.auto]p13:
3560 // Redeclarations or specializations of a function or function template
3561 // with a declared return type that uses a placeholder type shall also
3562 // use that placeholder, not a deduced type.
3563 QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3564 QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3565 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3566 canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3567 OldDeclaredReturnType)) {
3568 QualType ResQT;
3569 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3570 OldDeclaredReturnType->isObjCObjectPointerType())
3571 // FIXME: This does the wrong thing for a deduced return type.
3572 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3573 if (ResQT.isNull()) {
3574 if (New->isCXXClassMember() && New->isOutOfLine())
3575 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3576 << New << New->getReturnTypeSourceRange();
3577 else
3578 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3579 << New->getReturnTypeSourceRange();
3580 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3581 << Old->getReturnTypeSourceRange();
3582 return true;
3583 }
3584 else
3585 NewQType = ResQT;
3586 }
3587
3588 QualType OldReturnType = OldType->getReturnType();
3589 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3590 if (OldReturnType != NewReturnType) {
3591 // If this function has a deduced return type and has already been
3592 // defined, copy the deduced value from the old declaration.
3593 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3594 if (OldAT && OldAT->isDeduced()) {
3595 New->setType(
3596 SubstAutoType(New->getType(),
3597 OldAT->isDependentType() ? Context.DependentTy
3598 : OldAT->getDeducedType()));
3599 NewQType = Context.getCanonicalType(
3600 SubstAutoType(NewQType,
3601 OldAT->isDependentType() ? Context.DependentTy
3602 : OldAT->getDeducedType()));
3603 }
3604 }
3605
3606 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3607 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3608 if (OldMethod && NewMethod) {
3609 // Preserve triviality.
3610 NewMethod->setTrivial(OldMethod->isTrivial());
3611
3612 // MSVC allows explicit template specialization at class scope:
3613 // 2 CXXMethodDecls referring to the same function will be injected.
3614 // We don't want a redeclaration error.
3615 bool IsClassScopeExplicitSpecialization =
3616 OldMethod->isFunctionTemplateSpecialization() &&
3617 NewMethod->isFunctionTemplateSpecialization();
3618 bool isFriend = NewMethod->getFriendObjectKind();
3619
3620 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3621 !IsClassScopeExplicitSpecialization) {
3622 // -- Member function declarations with the same name and the
3623 // same parameter types cannot be overloaded if any of them
3624 // is a static member function declaration.
3625 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3626 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3627 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3628 return true;
3629 }
3630
3631 // C++ [class.mem]p1:
3632 // [...] A member shall not be declared twice in the
3633 // member-specification, except that a nested class or member
3634 // class template can be declared and then later defined.
3635 if (!inTemplateInstantiation()) {
3636 unsigned NewDiag;
3637 if (isa<CXXConstructorDecl>(OldMethod))
3638 NewDiag = diag::err_constructor_redeclared;
3639 else if (isa<CXXDestructorDecl>(NewMethod))
3640 NewDiag = diag::err_destructor_redeclared;
3641 else if (isa<CXXConversionDecl>(NewMethod))
3642 NewDiag = diag::err_conv_function_redeclared;
3643 else
3644 NewDiag = diag::err_member_redeclared;
3645
3646 Diag(New->getLocation(), NewDiag);
3647 } else {
3648 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3649 << New << New->getType();
3650 }
3651 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3652 return true;
3653
3654 // Complain if this is an explicit declaration of a special
3655 // member that was initially declared implicitly.
3656 //
3657 // As an exception, it's okay to befriend such methods in order
3658 // to permit the implicit constructor/destructor/operator calls.
3659 } else if (OldMethod->isImplicit()) {
3660 if (isFriend) {
3661 NewMethod->setImplicit();
3662 } else {
3663 Diag(NewMethod->getLocation(),
3664 diag::err_definition_of_implicitly_declared_member)
3665 << New << getSpecialMember(OldMethod);
3666 return true;
3667 }
3668 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3669 Diag(NewMethod->getLocation(),
3670 diag::err_definition_of_explicitly_defaulted_member)
3671 << getSpecialMember(OldMethod);
3672 return true;
3673 }
3674 }
3675
3676 // C++11 [dcl.attr.noreturn]p1:
3677 // The first declaration of a function shall specify the noreturn
3678 // attribute if any declaration of that function specifies the noreturn
3679 // attribute.
3680 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3681 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3682 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3683 Diag(Old->getFirstDecl()->getLocation(),
3684 diag::note_noreturn_missing_first_decl);
3685 }
3686
3687 // C++11 [dcl.attr.depend]p2:
3688 // The first declaration of a function shall specify the
3689 // carries_dependency attribute for its declarator-id if any declaration
3690 // of the function specifies the carries_dependency attribute.
3691 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3692 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3693 Diag(CDA->getLocation(),
3694 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3695 Diag(Old->getFirstDecl()->getLocation(),
3696 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3697 }
3698
3699 // (C++98 8.3.5p3):
3700 // All declarations for a function shall agree exactly in both the
3701 // return type and the parameter-type-list.
3702 // We also want to respect all the extended bits except noreturn.
3703
3704 // noreturn should now match unless the old type info didn't have it.
3705 QualType OldQTypeForComparison = OldQType;
3706 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3707 auto *OldType = OldQType->castAs<FunctionProtoType>();
3708 const FunctionType *OldTypeForComparison
3709 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3710 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3711 assert(OldQTypeForComparison.isCanonical())((void)0);
3712 }
3713
3714 if (haveIncompatibleLanguageLinkages(Old, New)) {
3715 // As a special case, retain the language linkage from previous
3716 // declarations of a friend function as an extension.
3717 //
3718 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3719 // and is useful because there's otherwise no way to specify language
3720 // linkage within class scope.
3721 //
3722 // Check cautiously as the friend object kind isn't yet complete.
3723 if (New->getFriendObjectKind() != Decl::FOK_None) {
3724 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3725 Diag(OldLocation, PrevDiag);
3726 } else {
3727 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3728 Diag(OldLocation, PrevDiag);
3729 return true;
3730 }
3731 }
3732
3733 // If the function types are compatible, merge the declarations. Ignore the
3734 // exception specifier because it was already checked above in
3735 // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3736 // about incompatible types under -fms-compatibility.
3737 if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3738 NewQType))
3739 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3740
3741 // If the types are imprecise (due to dependent constructs in friends or
3742 // local extern declarations), it's OK if they differ. We'll check again
3743 // during instantiation.
3744 if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3745 return false;
3746
3747 // Fall through for conflicting redeclarations and redefinitions.
3748 }
3749
3750 // C: Function types need to be compatible, not identical. This handles
3751 // duplicate function decls like "void f(int); void f(enum X);" properly.
3752 if (!getLangOpts().CPlusPlus &&
3753 Context.typesAreCompatible(OldQType, NewQType)) {
3754 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3755 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3756 const FunctionProtoType *OldProto = nullptr;
3757 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3758 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3759 // The old declaration provided a function prototype, but the
3760 // new declaration does not. Merge in the prototype.
3761 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")((void)0);
3762 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3763 NewQType =
3764 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3765 OldProto->getExtProtoInfo());
3766 New->setType(NewQType);
3767 New->setHasInheritedPrototype();
3768
3769 // Synthesize parameters with the same types.
3770 SmallVector<ParmVarDecl*, 16> Params;
3771 for (const auto &ParamType : OldProto->param_types()) {
3772 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3773 SourceLocation(), nullptr,
3774 ParamType, /*TInfo=*/nullptr,
3775 SC_None, nullptr);
3776 Param->setScopeInfo(0, Params.size());
3777 Param->setImplicit();
3778 Params.push_back(Param);
3779 }
3780
3781 New->setParams(Params);
3782 }
3783
3784 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3785 }
3786
3787 // Check if the function types are compatible when pointer size address
3788 // spaces are ignored.
3789 if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3790 return false;
3791
3792 // GNU C permits a K&R definition to follow a prototype declaration
3793 // if the declared types of the parameters in the K&R definition
3794 // match the types in the prototype declaration, even when the
3795 // promoted types of the parameters from the K&R definition differ
3796 // from the types in the prototype. GCC then keeps the types from
3797 // the prototype.
3798 //
3799 // If a variadic prototype is followed by a non-variadic K&R definition,
3800 // the K&R definition becomes variadic. This is sort of an edge case, but
3801 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3802 // C99 6.9.1p8.
3803 if (!getLangOpts().CPlusPlus &&
3804 Old->hasPrototype() && !New->hasPrototype() &&
3805 New->getType()->getAs<FunctionProtoType>() &&
3806 Old->getNumParams() == New->getNumParams()) {
3807 SmallVector<QualType, 16> ArgTypes;
3808 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3809 const FunctionProtoType *OldProto
3810 = Old->getType()->getAs<FunctionProtoType>();
3811 const FunctionProtoType *NewProto
3812 = New->getType()->getAs<FunctionProtoType>();
3813
3814 // Determine whether this is the GNU C extension.
3815 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3816 NewProto->getReturnType());
3817 bool LooseCompatible = !MergedReturn.isNull();
3818 for (unsigned Idx = 0, End = Old->getNumParams();
3819 LooseCompatible && Idx != End; ++Idx) {
3820 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3821 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3822 if (Context.typesAreCompatible(OldParm->getType(),
3823 NewProto->getParamType(Idx))) {
3824 ArgTypes.push_back(NewParm->getType());
3825 } else if (Context.typesAreCompatible(OldParm->getType(),
3826 NewParm->getType(),
3827 /*CompareUnqualified=*/true)) {
3828 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3829 NewProto->getParamType(Idx) };
3830 Warnings.push_back(Warn);
3831 ArgTypes.push_back(NewParm->getType());
3832 } else
3833 LooseCompatible = false;
3834 }
3835
3836 if (LooseCompatible) {
3837 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3838 Diag(Warnings[Warn].NewParm->getLocation(),
3839 diag::ext_param_promoted_not_compatible_with_prototype)
3840 << Warnings[Warn].PromotedType
3841 << Warnings[Warn].OldParm->getType();
3842 if (Warnings[Warn].OldParm->getLocation().isValid())
3843 Diag(Warnings[Warn].OldParm->getLocation(),
3844 diag::note_previous_declaration);
3845 }
3846
3847 if (MergeTypeWithOld)
3848 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3849 OldProto->getExtProtoInfo()));
3850 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3851 }
3852
3853 // Fall through to diagnose conflicting types.
3854 }
3855
3856 // A function that has already been declared has been redeclared or
3857 // defined with a different type; show an appropriate diagnostic.
3858
3859 // If the previous declaration was an implicitly-generated builtin
3860 // declaration, then at the very least we should use a specialized note.
3861 unsigned BuiltinID;
3862 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3863 // If it's actually a library-defined builtin function like 'malloc'
3864 // or 'printf', just warn about the incompatible redeclaration.
3865 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3866 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3867 Diag(OldLocation, diag::note_previous_builtin_declaration)
3868 << Old << Old->getType();
3869 return false;
3870 }
3871
3872 PrevDiag = diag::note_previous_builtin_declaration;
3873 }
3874
3875 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3876 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3877 return true;
3878}
3879
3880/// Completes the merge of two function declarations that are
3881/// known to be compatible.
3882///
3883/// This routine handles the merging of attributes and other
3884/// properties of function declarations from the old declaration to
3885/// the new declaration, once we know that New is in fact a
3886/// redeclaration of Old.
3887///
3888/// \returns false
3889bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3890 Scope *S, bool MergeTypeWithOld) {
3891 // Merge the attributes
3892 mergeDeclAttributes(New, Old);
3893
3894 // Merge "pure" flag.
3895 if (Old->isPure())
3896 New->setPure();
3897
3898 // Merge "used" flag.
3899 if (Old->getMostRecentDecl()->isUsed(false))
3900 New->setIsUsed();
3901
3902 // Merge attributes from the parameters. These can mismatch with K&R
3903 // declarations.
3904 if (New->getNumParams() == Old->getNumParams())
3905 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3906 ParmVarDecl *NewParam = New->getParamDecl(i);
3907 ParmVarDecl *OldParam = Old->getParamDecl(i);
3908 mergeParamDeclAttributes(NewParam, OldParam, *this);
3909 mergeParamDeclTypes(NewParam, OldParam, *this);
3910 }
3911
3912 if (getLangOpts().CPlusPlus)
3913 return MergeCXXFunctionDecl(New, Old, S);
3914
3915 // Merge the function types so the we get the composite types for the return
3916 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3917 // was visible.
3918 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3919 if (!Merged.isNull() && MergeTypeWithOld)
3920 New->setType(Merged);
3921
3922 return false;
3923}
3924
3925void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3926 ObjCMethodDecl *oldMethod) {
3927 // Merge the attributes, including deprecated/unavailable
3928 AvailabilityMergeKind MergeKind =
3929 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3930 ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
3931 : AMK_ProtocolImplementation)
3932 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3933 : AMK_Override;
3934
3935 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3936
3937 // Merge attributes from the parameters.
3938 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3939 oe = oldMethod->param_end();
3940 for (ObjCMethodDecl::param_iterator
3941 ni = newMethod->param_begin(), ne = newMethod->param_end();
3942 ni != ne && oi != oe; ++ni, ++oi)
3943 mergeParamDeclAttributes(*ni, *oi, *this);
3944
3945 CheckObjCMethodOverride(newMethod, oldMethod);
3946}
3947
3948static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3949 assert(!S.Context.hasSameType(New->getType(), Old->getType()))((void)0);
3950
3951 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3952 ? diag::err_redefinition_different_type
3953 : diag::err_redeclaration_different_type)
3954 << New->getDeclName() << New->getType() << Old->getType();
3955
3956 diag::kind PrevDiag;
3957 SourceLocation OldLocation;
3958 std::tie(PrevDiag, OldLocation)
3959 = getNoteDiagForInvalidRedeclaration(Old, New);
3960 S.Diag(OldLocation, PrevDiag);
3961 New->setInvalidDecl();
3962}
3963
3964/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3965/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3966/// emitting diagnostics as appropriate.
3967///
3968/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3969/// to here in AddInitializerToDecl. We can't check them before the initializer
3970/// is attached.
3971void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3972 bool MergeTypeWithOld) {
3973 if (New->isInvalidDecl() || Old->isInvalidDecl())
3974 return;
3975
3976 QualType MergedT;
3977 if (getLangOpts().CPlusPlus) {
3978 if (New->getType()->isUndeducedType()) {
3979 // We don't know what the new type is until the initializer is attached.
3980 return;
3981 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3982 // These could still be something that needs exception specs checked.
3983 return MergeVarDeclExceptionSpecs(New, Old);
3984 }
3985 // C++ [basic.link]p10:
3986 // [...] the types specified by all declarations referring to a given
3987 // object or function shall be identical, except that declarations for an
3988 // array object can specify array types that differ by the presence or
3989 // absence of a major array bound (8.3.4).
3990 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3991 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3992 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3993
3994 // We are merging a variable declaration New into Old. If it has an array
3995 // bound, and that bound differs from Old's bound, we should diagnose the
3996 // mismatch.
3997 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3998 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3999 PrevVD = PrevVD->getPreviousDecl()) {
4000 QualType PrevVDTy = PrevVD->getType();
4001 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4002 continue;
4003
4004 if (!Context.hasSameType(New->getType(), PrevVDTy))
4005 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4006 }
4007 }
4008
4009 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4010 if (Context.hasSameType(OldArray->getElementType(),
4011 NewArray->getElementType()))
4012 MergedT = New->getType();
4013 }
4014 // FIXME: Check visibility. New is hidden but has a complete type. If New
4015 // has no array bound, it should not inherit one from Old, if Old is not
4016 // visible.
4017 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4018 if (Context.hasSameType(OldArray->getElementType(),
4019 NewArray->getElementType()))
4020 MergedT = Old->getType();
4021 }
4022 }
4023 else if (New->getType()->isObjCObjectPointerType() &&
4024 Old->getType()->isObjCObjectPointerType()) {
4025 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4026 Old->getType());
4027 }
4028 } else {
4029 // C 6.2.7p2:
4030 // All declarations that refer to the same object or function shall have
4031 // compatible type.
4032 MergedT = Context.mergeTypes(New->getType(), Old->getType());
4033 }
4034 if (MergedT.isNull()) {
4035 // It's OK if we couldn't merge types if either type is dependent, for a
4036 // block-scope variable. In other cases (static data members of class
4037 // templates, variable templates, ...), we require the types to be
4038 // equivalent.
4039 // FIXME: The C++ standard doesn't say anything about this.
4040 if ((New->getType()->isDependentType() ||
4041 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4042 // If the old type was dependent, we can't merge with it, so the new type
4043 // becomes dependent for now. We'll reproduce the original type when we
4044 // instantiate the TypeSourceInfo for the variable.
4045 if (!New->getType()->isDependentType() && MergeTypeWithOld)
4046 New->setType(Context.DependentTy);
4047 return;
4048 }
4049 return diagnoseVarDeclTypeMismatch(*this, New, Old);
4050 }
4051
4052 // Don't actually update the type on the new declaration if the old
4053 // declaration was an extern declaration in a different scope.
4054 if (MergeTypeWithOld)
4055 New->setType(MergedT);
4056}
4057
4058static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4059 LookupResult &Previous) {
4060 // C11 6.2.7p4:
4061 // For an identifier with internal or external linkage declared
4062 // in a scope in which a prior declaration of that identifier is
4063 // visible, if the prior declaration specifies internal or
4064 // external linkage, the type of the identifier at the later
4065 // declaration becomes the composite type.
4066 //
4067 // If the variable isn't visible, we do not merge with its type.
4068 if (Previous.isShadowed())
4069 return false;
4070
4071 if (S.getLangOpts().CPlusPlus) {
4072 // C++11 [dcl.array]p3:
4073 // If there is a preceding declaration of the entity in the same
4074 // scope in which the bound was specified, an omitted array bound
4075 // is taken to be the same as in that earlier declaration.
4076 return NewVD->isPreviousDeclInSameBlockScope() ||
4077 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4078 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
4079 } else {
4080 // If the old declaration was function-local, don't merge with its
4081 // type unless we're in the same function.
4082 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4083 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4084 }
4085}
4086
4087/// MergeVarDecl - We just parsed a variable 'New' which has the same name
4088/// and scope as a previous declaration 'Old'. Figure out how to resolve this
4089/// situation, merging decls or emitting diagnostics as appropriate.
4090///
4091/// Tentative definition rules (C99 6.9.2p2) are checked by
4092/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4093/// definitions here, since the initializer hasn't been attached.
4094///
4095void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
4096 // If the new decl is already invalid, don't do any other checking.
4097 if (New->isInvalidDecl())
4098 return;
4099
4100 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4101 return;
4102
4103 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4104
4105 // Verify the old decl was also a variable or variable template.
4106 VarDecl *Old = nullptr;
4107 VarTemplateDecl *OldTemplate = nullptr;
4108 if (Previous.isSingleResult()) {
4109 if (NewTemplate) {
4110 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4111 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4112
4113 if (auto *Shadow =
4114 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4115 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4116 return New->setInvalidDecl();
4117 } else {
4118 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4119
4120 if (auto *Shadow =
4121 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4122 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4123 return New->setInvalidDecl();
4124 }
4125 }
4126 if (!Old) {
4127 Diag(New->getLocation(), diag::err_redefinition_different_kind)
4128 << New->getDeclName();
4129 notePreviousDefinition(Previous.getRepresentativeDecl(),
4130 New->getLocation());
4131 return New->setInvalidDecl();
4132 }
4133
4134 // If the old declaration was found in an inline namespace and the new
4135 // declaration was qualified, update the DeclContext to match.
4136 adjustDeclContextForDeclaratorDecl(New, Old);
4137
4138 // Ensure the template parameters are compatible.
4139 if (NewTemplate &&
4140 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4141 OldTemplate->getTemplateParameters(),
4142 /*Complain=*/true, TPL_TemplateMatch))
4143 return New->setInvalidDecl();
4144
4145 // C++ [class.mem]p1:
4146 // A member shall not be declared twice in the member-specification [...]
4147 //
4148 // Here, we need only consider static data members.
4149 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4150 Diag(New->getLocation(), diag::err_duplicate_member)
4151 << New->getIdentifier();
4152 Diag(Old->getLocation(), diag::note_previous_declaration);
4153 New->setInvalidDecl();
4154 }
4155
4156 mergeDeclAttributes(New, Old);
4157 // Warn if an already-declared variable is made a weak_import in a subsequent
4158 // declaration
4159 if (New->hasAttr<WeakImportAttr>() &&
4160 Old->getStorageClass() == SC_None &&
4161 !Old->hasAttr<WeakImportAttr>()) {
4162 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4163 notePreviousDefinition(Old, New->getLocation());
4164 // Remove weak_import attribute on new declaration.
4165 New->dropAttr<WeakImportAttr>();
4166 }
4167
4168 if (New->hasAttr<InternalLinkageAttr>() &&
4169 !Old->hasAttr<InternalLinkageAttr>()) {
4170 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
4171 << New->getDeclName();
4172 notePreviousDefinition(Old, New->getLocation());
4173 New->dropAttr<InternalLinkageAttr>();
4174 }
4175
4176 // Merge the types.
4177 VarDecl *MostRecent = Old->getMostRecentDecl();
4178 if (MostRecent != Old) {
4179 MergeVarDeclTypes(New, MostRecent,
4180 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4181 if (New->isInvalidDecl())
4182 return;
4183 }
4184
4185 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4186 if (New->isInvalidDecl())
4187 return;
4188
4189 diag::kind PrevDiag;
4190 SourceLocation OldLocation;
4191 std::tie(PrevDiag, OldLocation) =
4192 getNoteDiagForInvalidRedeclaration(Old, New);
4193
4194 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4195 if (New->getStorageClass() == SC_Static &&
4196 !New->isStaticDataMember() &&
4197 Old->hasExternalFormalLinkage()) {
4198 if (getLangOpts().MicrosoftExt) {
4199 Diag(New->getLocation(), diag::ext_static_non_static)
4200 << New->getDeclName();
4201 Diag(OldLocation, PrevDiag);
4202 } else {
4203 Diag(New->getLocation(), diag::err_static_non_static)
4204 << New->getDeclName();
4205 Diag(OldLocation, PrevDiag);
4206 return New->setInvalidDecl();
4207 }
4208 }
4209 // C99 6.2.2p4:
4210 // For an identifier declared with the storage-class specifier
4211 // extern in a scope in which a prior declaration of that
4212 // identifier is visible,23) if the prior declaration specifies
4213 // internal or external linkage, the linkage of the identifier at
4214 // the later declaration is the same as the linkage specified at
4215 // the prior declaration. If no prior declaration is visible, or
4216 // if the prior declaration specifies no linkage, then the
4217 // identifier has external linkage.
4218 if (New->hasExternalStorage() && Old->hasLinkage())
4219 /* Okay */;
4220 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4221 !New->isStaticDataMember() &&
4222 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
4223 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4224 Diag(OldLocation, PrevDiag);
4225 return New->setInvalidDecl();
4226 }
4227
4228 // Check if extern is followed by non-extern and vice-versa.
4229 if (New->hasExternalStorage() &&
4230 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4231 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4232 Diag(OldLocation, PrevDiag);
4233 return New->setInvalidDecl();
4234 }
4235 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4236 !New->hasExternalStorage()) {
4237 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4238 Diag(OldLocation, PrevDiag);
4239 return New->setInvalidDecl();
4240 }
4241
4242 if (CheckRedeclarationModuleOwnership(New, Old))
4243 return;
4244
4245 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4246
4247 // FIXME: The test for external storage here seems wrong? We still
4248 // need to check for mismatches.
4249 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4250 // Don't complain about out-of-line definitions of static members.
4251 !(Old->getLexicalDeclContext()->isRecord() &&
4252 !New->getLexicalDeclContext()->isRecord())) {
4253 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4254 Diag(OldLocation, PrevDiag);
4255 return New->setInvalidDecl();
4256 }
4257
4258 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4259 if (VarDecl *Def = Old->getDefinition()) {
4260 // C++1z [dcl.fcn.spec]p4:
4261 // If the definition of a variable appears in a translation unit before
4262 // its first declaration as inline, the program is ill-formed.
4263 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4264 Diag(Def->getLocation(), diag::note_previous_definition);
4265 }
4266 }
4267
4268 // If this redeclaration makes the variable inline, we may need to add it to
4269 // UndefinedButUsed.
4270 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4271 !Old->getDefinition() && !New->isThisDeclarationADefinition())
4272 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4273 SourceLocation()));
4274
4275 if (New->getTLSKind() != Old->getTLSKind()) {
4276 if (!Old->getTLSKind()) {
4277 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4278 Diag(OldLocation, PrevDiag);
4279 } else if (!New->getTLSKind()) {
4280 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4281 Diag(OldLocation, PrevDiag);
4282 } else {
4283 // Do not allow redeclaration to change the variable between requiring
4284 // static and dynamic initialization.
4285 // FIXME: GCC allows this, but uses the TLS keyword on the first
4286 // declaration to determine the kind. Do we need to be compatible here?
4287 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4288 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4289 Diag(OldLocation, PrevDiag);
4290 }
4291 }
4292
4293 // C++ doesn't have tentative definitions, so go right ahead and check here.
4294 if (getLangOpts().CPlusPlus &&
4295 New->isThisDeclarationADefinition() == VarDecl::Definition) {
4296 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4297 Old->getCanonicalDecl()->isConstexpr()) {
4298 // This definition won't be a definition any more once it's been merged.
4299 Diag(New->getLocation(),
4300 diag::warn_deprecated_redundant_constexpr_static_def);
4301 } else if (VarDecl *Def = Old->getDefinition()) {
4302 if (checkVarDeclRedefinition(Def, New))
4303 return;
4304 }
4305 }
4306
4307 if (haveIncompatibleLanguageLinkages(Old, New)) {
4308 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4309 Diag(OldLocation, PrevDiag);
4310 New->setInvalidDecl();
4311 return;
4312 }
4313
4314 // Merge "used" flag.
4315 if (Old->getMostRecentDecl()->isUsed(false))
4316 New->setIsUsed();
4317
4318 // Keep a chain of previous declarations.
4319 New->setPreviousDecl(Old);
4320 if (NewTemplate)
4321 NewTemplate->setPreviousDecl(OldTemplate);
4322
4323 // Inherit access appropriately.
4324 New->setAccess(Old->getAccess());
4325 if (NewTemplate)
4326 NewTemplate->setAccess(New->getAccess());
4327
4328 if (Old->isInline())
4329 New->setImplicitlyInline();
4330}
4331
4332void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4333 SourceManager &SrcMgr = getSourceManager();
4334 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4335 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4336 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4337 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4338 auto &HSI = PP.getHeaderSearchInfo();
4339 StringRef HdrFilename =
4340 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4341
4342 auto noteFromModuleOrInclude = [&](Module *Mod,
4343 SourceLocation IncLoc) -> bool {
4344 // Redefinition errors with modules are common with non modular mapped
4345 // headers, example: a non-modular header H in module A that also gets
4346 // included directly in a TU. Pointing twice to the same header/definition
4347 // is confusing, try to get better diagnostics when modules is on.
4348 if (IncLoc.isValid()) {
4349 if (Mod) {
4350 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4351 << HdrFilename.str() << Mod->getFullModuleName();
4352 if (!Mod->DefinitionLoc.isInvalid())
4353 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4354 << Mod->getFullModuleName();
4355 } else {
4356 Diag(IncLoc, diag::note_redefinition_include_same_file)
4357 << HdrFilename.str();
4358 }
4359 return true;
4360 }
4361
4362 return false;
4363 };
4364
4365 // Is it the same file and same offset? Provide more information on why
4366 // this leads to a redefinition error.
4367 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4368 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4369 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4370 bool EmittedDiag =
4371 noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4372 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4373
4374 // If the header has no guards, emit a note suggesting one.
4375 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4376 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4377
4378 if (EmittedDiag)
4379 return;
4380 }
4381
4382 // Redefinition coming from different files or couldn't do better above.
4383 if (Old->getLocation().isValid())
4384 Diag(Old->getLocation(), diag::note_previous_definition);
4385}
4386
4387/// We've just determined that \p Old and \p New both appear to be definitions
4388/// of the same variable. Either diagnose or fix the problem.
4389bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4390 if (!hasVisibleDefinition(Old) &&
4391 (New->getFormalLinkage() == InternalLinkage ||
4392 New->isInline() ||
4393 New->getDescribedVarTemplate() ||
4394 New->getNumTemplateParameterLists() ||
4395 New->getDeclContext()->isDependentContext())) {
4396 // The previous definition is hidden, and multiple definitions are
4397 // permitted (in separate TUs). Demote this to a declaration.
4398 New->demoteThisDefinitionToDeclaration();
4399
4400 // Make the canonical definition visible.
4401 if (auto *OldTD = Old->getDescribedVarTemplate())
4402 makeMergedDefinitionVisible(OldTD);
4403 makeMergedDefinitionVisible(Old);
4404 return false;
4405 } else {
4406 Diag(New->getLocation(), diag::err_redefinition) << New;
4407 notePreviousDefinition(Old, New->getLocation());
4408 New->setInvalidDecl();
4409 return true;
4410 }
4411}
4412
4413/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4414/// no declarator (e.g. "struct foo;") is parsed.
4415Decl *
4416Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4417 RecordDecl *&AnonRecord) {
4418 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4419 AnonRecord);
4420}
4421
4422// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4423// disambiguate entities defined in different scopes.
4424// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4425// compatibility.
4426// We will pick our mangling number depending on which version of MSVC is being
4427// targeted.
4428static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4429 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4430 ? S->getMSCurManglingNumber()
4431 : S->getMSLastManglingNumber();
4432}
4433
4434void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4435 if (!Context.getLangOpts().CPlusPlus)
4436 return;
4437
4438 if (isa<CXXRecordDecl>(Tag->getParent())) {
4439 // If this tag is the direct child of a class, number it if
4440 // it is anonymous.
4441 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4442 return;
4443 MangleNumberingContext &MCtx =
4444 Context.getManglingNumberContext(Tag->getParent());
4445 Context.setManglingNumber(
4446 Tag, MCtx.getManglingNumber(
4447 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4448 return;
4449 }
4450
4451 // If this tag isn't a direct child of a class, number it if it is local.
4452 MangleNumberingContext *MCtx;
4453 Decl *ManglingContextDecl;
4454 std::tie(MCtx, ManglingContextDecl) =
4455 getCurrentMangleNumberContext(Tag->getDeclContext());
4456 if (MCtx) {
4457 Context.setManglingNumber(
4458 Tag, MCtx->getManglingNumber(
4459 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4460 }
4461}
4462
4463namespace {
4464struct NonCLikeKind {
4465 enum {
4466 None,
4467 BaseClass,
4468 DefaultMemberInit,
4469 Lambda,
4470 Friend,
4471 OtherMember,
4472 Invalid,
4473 } Kind = None;
4474 SourceRange Range;
4475
4476 explicit operator bool() { return Kind != None; }
4477};
4478}
4479
4480/// Determine whether a class is C-like, according to the rules of C++
4481/// [dcl.typedef] for anonymous classes with typedef names for linkage.
4482static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4483 if (RD->isInvalidDecl())
4484 return {NonCLikeKind::Invalid, {}};
4485
4486 // C++ [dcl.typedef]p9: [P1766R1]
4487 // An unnamed class with a typedef name for linkage purposes shall not
4488 //
4489 // -- have any base classes
4490 if (RD->getNumBases())
4491 return {NonCLikeKind::BaseClass,
4492 SourceRange(RD->bases_begin()->getBeginLoc(),
4493 RD->bases_end()[-1].getEndLoc())};
4494 bool Invalid = false;
4495 for (Decl *D : RD->decls()) {
4496 // Don't complain about things we already diagnosed.
4497 if (D->isInvalidDecl()) {
4498 Invalid = true;
4499 continue;
4500 }
4501
4502 // -- have any [...] default member initializers
4503 if (auto *FD = dyn_cast<FieldDecl>(D)) {
4504 if (FD->hasInClassInitializer()) {
4505 auto *Init = FD->getInClassInitializer();
4506 return {NonCLikeKind::DefaultMemberInit,
4507 Init ? Init->getSourceRange() : D->getSourceRange()};
4508 }
4509 continue;
4510 }
4511
4512 // FIXME: We don't allow friend declarations. This violates the wording of
4513 // P1766, but not the intent.
4514 if (isa<FriendDecl>(D))
4515 return {NonCLikeKind::Friend, D->getSourceRange()};
4516
4517 // -- declare any members other than non-static data members, member
4518 // enumerations, or member classes,
4519 if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4520 isa<EnumDecl>(D))
4521 continue;
4522 auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4523 if (!MemberRD) {
4524 if (D->isImplicit())
4525 continue;
4526 return {NonCLikeKind::OtherMember, D->getSourceRange()};
4527 }
4528
4529 // -- contain a lambda-expression,
4530 if (MemberRD->isLambda())
4531 return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4532
4533 // and all member classes shall also satisfy these requirements
4534 // (recursively).
4535 if (MemberRD->isThisDeclarationADefinition()) {
4536 if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4537 return Kind;
4538 }
4539 }
4540
4541 return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4542}
4543
4544void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4545 TypedefNameDecl *NewTD) {
4546 if (TagFromDeclSpec->isInvalidDecl())
4547 return;
4548
4549 // Do nothing if the tag already has a name for linkage purposes.
4550 if (TagFromDeclSpec->hasNameForLinkage())
4551 return;
4552
4553 // A well-formed anonymous tag must always be a TUK_Definition.
4554 assert(TagFromDeclSpec->isThisDeclarationADefinition())((void)0);
4555
4556 // The type must match the tag exactly; no qualifiers allowed.
4557 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4558 Context.getTagDeclType(TagFromDeclSpec))) {
4559 if (getLangOpts().CPlusPlus)
4560 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4561 return;
4562 }
4563
4564 // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4565 // An unnamed class with a typedef name for linkage purposes shall [be
4566 // C-like].
4567 //
4568 // FIXME: Also diagnose if we've already computed the linkage. That ideally
4569 // shouldn't happen, but there are constructs that the language rule doesn't
4570 // disallow for which we can't reasonably avoid computing linkage early.
4571 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4572 NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4573 : NonCLikeKind();
4574 bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4575 if (NonCLike || ChangesLinkage) {
4576 if (NonCLike.Kind == NonCLikeKind::Invalid)
4577 return;
4578
4579 unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4580 if (ChangesLinkage) {
4581 // If the linkage changes, we can't accept this as an extension.
4582 if (NonCLike.Kind == NonCLikeKind::None)
4583 DiagID = diag::err_typedef_changes_linkage;
4584 else
4585 DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4586 }
4587
4588 SourceLocation FixitLoc =
4589 getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4590 llvm::SmallString<40> TextToInsert;
4591 TextToInsert += ' ';
4592 TextToInsert += NewTD->getIdentifier()->getName();
4593
4594 Diag(FixitLoc, DiagID)
4595 << isa<TypeAliasDecl>(NewTD)
4596 << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4597 if (NonCLike.Kind != NonCLikeKind::None) {
4598 Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4599 << NonCLike.Kind - 1 << NonCLike.Range;
4600 }
4601 Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4602 << NewTD << isa<TypeAliasDecl>(NewTD);
4603
4604 if (ChangesLinkage)
4605 return;
4606 }
4607
4608 // Otherwise, set this as the anon-decl typedef for the tag.
4609 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4610}
4611
4612static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4613 switch (T) {
4614 case DeclSpec::TST_class:
4615 return 0;
4616 case DeclSpec::TST_struct:
4617 return 1;
4618 case DeclSpec::TST_interface:
4619 return 2;
4620 case DeclSpec::TST_union:
4621 return 3;
4622 case DeclSpec::TST_enum:
4623 return 4;
4624 default:
4625 llvm_unreachable("unexpected type specifier")__builtin_unreachable();
4626 }
4627}
4628
4629/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4630/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4631/// parameters to cope with template friend declarations.
4632Decl *
4633Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4634 MultiTemplateParamsArg TemplateParams,
4635 bool IsExplicitInstantiation,
4636 RecordDecl *&AnonRecord) {
4637 Decl *TagD = nullptr;
4638 TagDecl *Tag = nullptr;
4639 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4640 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4641 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4642 DS.getTypeSpecType() == DeclSpec::TST_union ||
4643 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4644 TagD = DS.getRepAsDecl();
4645
4646 if (!TagD) // We probably had an error
4647 return nullptr;
4648
4649 // Note that the above type specs guarantee that the
4650 // type rep is a Decl, whereas in many of the others
4651 // it's a Type.
4652 if (isa<TagDecl>(TagD))
4653 Tag = cast<TagDecl>(TagD);
4654 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4655 Tag = CTD->getTemplatedDecl();
4656 }
4657
4658 if (Tag) {
4659 handleTagNumbering(Tag, S);
4660 Tag->setFreeStanding();
4661 if (Tag->isInvalidDecl())
4662 return Tag;
4663 }
4664
4665 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4666 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4667 // or incomplete types shall not be restrict-qualified."
4668 if (TypeQuals & DeclSpec::TQ_restrict)
4669 Diag(DS.getRestrictSpecLoc(),
4670 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4671 << DS.getSourceRange();
4672 }
4673
4674 if (DS.isInlineSpecified())
4675 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4676 << getLangOpts().CPlusPlus17;
4677
4678 if (DS.hasConstexprSpecifier()) {
4679 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4680 // and definitions of functions and variables.
4681 // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4682 // the declaration of a function or function template
4683 if (Tag)
4684 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4685 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType())
4686 << static_cast<int>(DS.getConstexprSpecifier());
4687 else
4688 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4689 << static_cast<int>(DS.getConstexprSpecifier());
4690 // Don't emit warnings after this error.
4691 return TagD;
4692 }
4693
4694 DiagnoseFunctionSpecifiers(DS);
4695
4696 if (DS.isFriendSpecified()) {
4697 // If we're dealing with a decl but not a TagDecl, assume that
4698 // whatever routines created it handled the friendship aspect.
4699 if (TagD && !Tag)
4700 return nullptr;
4701 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4702 }
4703
4704 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4705 bool IsExplicitSpecialization =
4706 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4707 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4708 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4709 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4710 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4711 // nested-name-specifier unless it is an explicit instantiation
4712 // or an explicit specialization.
4713 //
4714 // FIXME: We allow class template partial specializations here too, per the
4715 // obvious intent of DR1819.
4716 //
4717 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4718 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4719 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4720 return nullptr;
4721 }
4722
4723 // Track whether this decl-specifier declares anything.
4724 bool DeclaresAnything = true;
4725
4726 // Handle anonymous struct definitions.
4727 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4728 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4729 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4730 if (getLangOpts().CPlusPlus ||
4731 Record->getDeclContext()->isRecord()) {
4732 // If CurContext is a DeclContext that can contain statements,
4733 // RecursiveASTVisitor won't visit the decls that
4734 // BuildAnonymousStructOrUnion() will put into CurContext.
4735 // Also store them here so that they can be part of the
4736 // DeclStmt that gets created in this case.
4737 // FIXME: Also return the IndirectFieldDecls created by
4738 // BuildAnonymousStructOr union, for the same reason?
4739 if (CurContext->isFunctionOrMethod())
4740 AnonRecord = Record;
4741 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4742 Context.getPrintingPolicy());
4743 }
4744
4745 DeclaresAnything = false;
4746 }
4747 }
4748
4749 // C11 6.7.2.1p2:
4750 // A struct-declaration that does not declare an anonymous structure or
4751 // anonymous union shall contain a struct-declarator-list.
4752 //
4753 // This rule also existed in C89 and C99; the grammar for struct-declaration
4754 // did not permit a struct-declaration without a struct-declarator-list.
4755 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4756 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4757 // Check for Microsoft C extension: anonymous struct/union member.
4758 // Handle 2 kinds of anonymous struct/union:
4759 // struct STRUCT;
4760 // union UNION;
4761 // and
4762 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4763 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4764 if ((Tag && Tag->getDeclName()) ||
4765 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4766 RecordDecl *Record = nullptr;
4767 if (Tag)
4768 Record = dyn_cast<RecordDecl>(Tag);
4769 else if (const RecordType *RT =
4770 DS.getRepAsType().get()->getAsStructureType())
4771 Record = RT->getDecl();
4772 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4773 Record = UT->getDecl();
4774
4775 if (Record && getLangOpts().MicrosoftExt) {
4776 Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4777 << Record->isUnion() << DS.getSourceRange();
4778 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4779 }
4780
4781 DeclaresAnything = false;
4782 }
4783 }
4784
4785 // Skip all the checks below if we have a type error.
4786 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4787 (TagD && TagD->isInvalidDecl()))
4788 return TagD;
4789
4790 if (getLangOpts().CPlusPlus &&
4791 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4792 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4793 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4794 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4795 DeclaresAnything = false;
4796
4797 if (!DS.isMissingDeclaratorOk()) {
4798 // Customize diagnostic for a typedef missing a name.
4799 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4800 Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4801 << DS.getSourceRange();
4802 else
4803 DeclaresAnything = false;
4804 }
4805
4806 if (DS.isModulePrivateSpecified() &&
4807 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4808 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4809 << Tag->getTagKind()
4810 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4811
4812 ActOnDocumentableDecl(TagD);
4813
4814 // C 6.7/2:
4815 // A declaration [...] shall declare at least a declarator [...], a tag,
4816 // or the members of an enumeration.
4817 // C++ [dcl.dcl]p3:
4818 // [If there are no declarators], and except for the declaration of an
4819 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4820 // names into the program, or shall redeclare a name introduced by a
4821 // previous declaration.
4822 if (!DeclaresAnything) {
4823 // In C, we allow this as a (popular) extension / bug. Don't bother
4824 // producing further diagnostics for redundant qualifiers after this.
4825 Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4826 ? diag::err_no_declarators
4827 : diag::ext_no_declarators)
4828 << DS.getSourceRange();
4829 return TagD;
4830 }
4831
4832 // C++ [dcl.stc]p1:
4833 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4834 // init-declarator-list of the declaration shall not be empty.
4835 // C++ [dcl.fct.spec]p1:
4836 // If a cv-qualifier appears in a decl-specifier-seq, the
4837 // init-declarator-list of the declaration shall not be empty.
4838 //
4839 // Spurious qualifiers here appear to be valid in C.
4840 unsigned DiagID = diag::warn_standalone_specifier;
4841 if (getLangOpts().CPlusPlus)
4842 DiagID = diag::ext_standalone_specifier;
4843
4844 // Note that a linkage-specification sets a storage class, but
4845 // 'extern "C" struct foo;' is actually valid and not theoretically
4846 // useless.
4847 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4848 if (SCS == DeclSpec::SCS_mutable)
4849 // Since mutable is not a viable storage class specifier in C, there is
4850 // no reason to treat it as an extension. Instead, diagnose as an error.
4851 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4852 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4853 Diag(DS.getStorageClassSpecLoc(), DiagID)
4854 << DeclSpec::getSpecifierName(SCS);
4855 }
4856
4857 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4858 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4859 << DeclSpec::getSpecifierName(TSCS);
4860 if (DS.getTypeQualifiers()) {
4861 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4862 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4863 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4864 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4865 // Restrict is covered above.
4866 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4867 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4868 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4869 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4870 }
4871
4872 // Warn about ignored type attributes, for example:
4873 // __attribute__((aligned)) struct A;
4874 // Attributes should be placed after tag to apply to type declaration.
4875 if (!DS.getAttributes().empty()) {
4876 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4877 if (TypeSpecType == DeclSpec::TST_class ||
4878 TypeSpecType == DeclSpec::TST_struct ||
4879 TypeSpecType == DeclSpec::TST_interface ||
4880 TypeSpecType == DeclSpec::TST_union ||
4881 TypeSpecType == DeclSpec::TST_enum) {
4882 for (const ParsedAttr &AL : DS.getAttributes())
4883 Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4884 << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
4885 }
4886 }
4887
4888 return TagD;
4889}
4890
4891/// We are trying to inject an anonymous member into the given scope;
4892/// check if there's an existing declaration that can't be overloaded.
4893///
4894/// \return true if this is a forbidden redeclaration
4895static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4896 Scope *S,
4897 DeclContext *Owner,
4898 DeclarationName Name,
4899 SourceLocation NameLoc,
4900 bool IsUnion) {
4901 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4902 Sema::ForVisibleRedeclaration);
4903 if (!SemaRef.LookupName(R, S)) return false;
4904
4905 // Pick a representative declaration.
4906 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4907 assert(PrevDecl && "Expected a non-null Decl")((void)0);
4908
4909 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4910 return false;
4911
4912 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4913 << IsUnion << Name;
4914 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4915
4916 return true;
4917}
4918
4919/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4920/// anonymous struct or union AnonRecord into the owning context Owner
4921/// and scope S. This routine will be invoked just after we realize
4922/// that an unnamed union or struct is actually an anonymous union or
4923/// struct, e.g.,
4924///
4925/// @code
4926/// union {
4927/// int i;
4928/// float f;
4929/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4930/// // f into the surrounding scope.x
4931/// @endcode
4932///
4933/// This routine is recursive, injecting the names of nested anonymous
4934/// structs/unions into the owning context and scope as well.
4935static bool
4936InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4937 RecordDecl *AnonRecord, AccessSpecifier AS,
4938 SmallVectorImpl<NamedDecl *> &Chaining) {
4939 bool Invalid = false;
4940
4941 // Look every FieldDecl and IndirectFieldDecl with a name.
4942 for (auto *D : AnonRecord->decls()) {
4943 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4944 cast<NamedDecl>(D)->getDeclName()) {
4945 ValueDecl *VD = cast<ValueDecl>(D);
4946 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4947 VD->getLocation(),
4948 AnonRecord->isUnion())) {
4949 // C++ [class.union]p2:
4950 // The names of the members of an anonymous union shall be
4951 // distinct from the names of any other entity in the
4952 // scope in which the anonymous union is declared.
4953 Invalid = true;
4954 } else {
4955 // C++ [class.union]p2:
4956 // For the purpose of name lookup, after the anonymous union
4957 // definition, the members of the anonymous union are
4958 // considered to have been defined in the scope in which the
4959 // anonymous union is declared.
4960 unsigned OldChainingSize = Chaining.size();
4961 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4962 Chaining.append(IF->chain_begin(), IF->chain_end());
4963 else
4964 Chaining.push_back(VD);
4965
4966 assert(Chaining.size() >= 2)((void)0);
4967 NamedDecl **NamedChain =
4968 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4969 for (unsigned i = 0; i < Chaining.size(); i++)
4970 NamedChain[i] = Chaining[i];
4971
4972 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4973 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4974 VD->getType(), {NamedChain, Chaining.size()});
4975
4976 for (const auto *Attr : VD->attrs())
4977 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4978
4979 IndirectField->setAccess(AS);
4980 IndirectField->setImplicit();
4981 SemaRef.PushOnScopeChains(IndirectField, S);
4982
4983 // That includes picking up the appropriate access specifier.
4984 if (AS != AS_none) IndirectField->setAccess(AS);
4985
4986 Chaining.resize(OldChainingSize);
4987 }
4988 }
4989 }
4990
4991 return Invalid;
4992}
4993
4994/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4995/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4996/// illegal input values are mapped to SC_None.
4997static StorageClass
4998StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4999 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5000 assert(StorageClassSpec != DeclSpec::SCS_typedef &&((void)0)
5001 "Parser allowed 'typedef' as storage class VarDecl.")((void)0);
5002 switch (StorageClassSpec) {
5003 case DeclSpec::SCS_unspecified: return SC_None;
5004 case DeclSpec::SCS_extern:
5005 if (DS.isExternInLinkageSpec())
5006 return SC_None;
5007 return SC_Extern;
5008 case DeclSpec::SCS_static: return SC_Static;
5009 case DeclSpec::SCS_auto: return SC_Auto;
5010 case DeclSpec::SCS_register: return SC_Register;
5011 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
5012 // Illegal SCSs map to None: error reporting is up to the caller.
5013 case DeclSpec::SCS_mutable: // Fall through.
5014 case DeclSpec::SCS_typedef: return SC_None;
5015 }
5016 llvm_unreachable("unknown storage class specifier")__builtin_unreachable();
5017}
5018
5019static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
5020 assert(Record->hasInClassInitializer())((void)0);
5021
5022 for (const auto *I : Record->decls()) {
5023 const auto *FD = dyn_cast<FieldDecl>(I);
5024 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5025 FD = IFD->getAnonField();
5026 if (FD && FD->hasInClassInitializer())
5027 return FD->getLocation();
5028 }
5029
5030 llvm_unreachable("couldn't find in-class initializer")__builtin_unreachable();
5031}
5032
5033static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5034 SourceLocation DefaultInitLoc) {
5035 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5036 return;
5037
5038 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5039 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5040}
5041
5042static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
5043 CXXRecordDecl *AnonUnion) {
5044 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5045 return;
5046
5047 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
5048}
5049
5050/// BuildAnonymousStructOrUnion - Handle the declaration of an
5051/// anonymous structure or union. Anonymous unions are a C++ feature
5052/// (C++ [class.union]) and a C11 feature; anonymous structures
5053/// are a C11 feature and GNU C++ extension.
5054Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
5055 AccessSpecifier AS,
5056 RecordDecl *Record,
5057 const PrintingPolicy &Policy) {
5058 DeclContext *Owner = Record->getDeclContext();
5059
5060 // Diagnose whether this anonymous struct/union is an extension.
5061 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5062 Diag(Record->getLocation(), diag::ext_anonymous_union);
5063 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5064 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5065 else if (!Record->isUnion() && !getLangOpts().C11)
5066 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5067
5068 // C and C++ require different kinds of checks for anonymous
5069 // structs/unions.
5070 bool Invalid = false;
5071 if (getLangOpts().CPlusPlus) {
5072 const char *PrevSpec = nullptr;
5073 if (Record->isUnion()) {
5074 // C++ [class.union]p6:
5075 // C++17 [class.union.anon]p2:
5076 // Anonymous unions declared in a named namespace or in the
5077 // global namespace shall be declared static.
5078 unsigned DiagID;
5079 DeclContext *OwnerScope = Owner->getRedeclContext();
5080 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
5081 (OwnerScope->isTranslationUnit() ||
5082 (OwnerScope->isNamespace() &&
5083 !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5084 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5085 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5086
5087 // Recover by adding 'static'.
5088 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
5089 PrevSpec, DiagID, Policy);
5090 }
5091 // C++ [class.union]p6:
5092 // A storage class is not allowed in a declaration of an
5093 // anonymous union in a class scope.
5094 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
5095 isa<RecordDecl>(Owner)) {
5096 Diag(DS.getStorageClassSpecLoc(),
5097 diag::err_anonymous_union_with_storage_spec)
5098 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
5099
5100 // Recover by removing the storage specifier.
5101 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
5102 SourceLocation(),
5103 PrevSpec, DiagID, Context.getPrintingPolicy());
5104 }
5105 }
5106
5107 // Ignore const/volatile/restrict qualifiers.
5108 if (DS.getTypeQualifiers()) {
5109 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
5110 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5111 << Record->isUnion() << "const"
5112 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
5113 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
5114 Diag(DS.getVolatileSpecLoc(),
5115 diag::ext_anonymous_struct_union_qualified)
5116 << Record->isUnion() << "volatile"
5117 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
5118 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
5119 Diag(DS.getRestrictSpecLoc(),
5120 diag::ext_anonymous_struct_union_qualified)
5121 << Record->isUnion() << "restrict"
5122 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
5123 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
5124 Diag(DS.getAtomicSpecLoc(),
5125 diag::ext_anonymous_struct_union_qualified)
5126 << Record->isUnion() << "_Atomic"
5127 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
5128 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
5129 Diag(DS.getUnalignedSpecLoc(),
5130 diag::ext_anonymous_struct_union_qualified)
5131 << Record->isUnion() << "__unaligned"
5132 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
5133
5134 DS.ClearTypeQualifiers();
5135 }
5136
5137 // C++ [class.union]p2:
5138 // The member-specification of an anonymous union shall only
5139 // define non-static data members. [Note: nested types and
5140 // functions cannot be declared within an anonymous union. ]
5141 for (auto *Mem : Record->decls()) {
5142 // Ignore invalid declarations; we already diagnosed them.
5143 if (Mem->isInvalidDecl())
5144 continue;
5145
5146 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5147 // C++ [class.union]p3:
5148 // An anonymous union shall not have private or protected
5149 // members (clause 11).
5150 assert(FD->getAccess() != AS_none)((void)0);
5151 if (FD->getAccess() != AS_public) {
5152 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5153 << Record->isUnion() << (FD->getAccess() == AS_protected);
5154 Invalid = true;
5155 }
5156
5157 // C++ [class.union]p1
5158 // An object of a class with a non-trivial constructor, a non-trivial
5159 // copy constructor, a non-trivial destructor, or a non-trivial copy
5160 // assignment operator cannot be a member of a union, nor can an
5161 // array of such objects.
5162 if (CheckNontrivialField(FD))
5163 Invalid = true;
5164 } else if (Mem->isImplicit()) {
5165 // Any implicit members are fine.
5166 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5167 // This is a type that showed up in an
5168 // elaborated-type-specifier inside the anonymous struct or
5169 // union, but which actually declares a type outside of the
5170 // anonymous struct or union. It's okay.
5171 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5172 if (!MemRecord->isAnonymousStructOrUnion() &&
5173 MemRecord->getDeclName()) {
5174 // Visual C++ allows type definition in anonymous struct or union.
5175 if (getLangOpts().MicrosoftExt)
5176 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5177 << Record->isUnion();
5178 else {
5179 // This is a nested type declaration.
5180 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5181 << Record->isUnion();
5182 Invalid = true;
5183 }
5184 } else {
5185 // This is an anonymous type definition within another anonymous type.
5186 // This is a popular extension, provided by Plan9, MSVC and GCC, but
5187 // not part of standard C++.
5188 Diag(MemRecord->getLocation(),
5189 diag::ext_anonymous_record_with_anonymous_type)
5190 << Record->isUnion();
5191 }
5192 } else if (isa<AccessSpecDecl>(Mem)) {
5193 // Any access specifier is fine.
5194 } else if (isa<StaticAssertDecl>(Mem)) {
5195 // In C++1z, static_assert declarations are also fine.
5196 } else {
5197 // We have something that isn't a non-static data
5198 // member. Complain about it.
5199 unsigned DK = diag::err_anonymous_record_bad_member;
5200 if (isa<TypeDecl>(Mem))
5201 DK = diag::err_anonymous_record_with_type;
5202 else if (isa<FunctionDecl>(Mem))
5203 DK = diag::err_anonymous_record_with_function;
5204 else if (isa<VarDecl>(Mem))
5205 DK = diag::err_anonymous_record_with_static;
5206
5207 // Visual C++ allows type definition in anonymous struct or union.
5208 if (getLangOpts().MicrosoftExt &&
5209 DK == diag::err_anonymous_record_with_type)
5210 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5211 << Record->isUnion();
5212 else {
5213 Diag(Mem->getLocation(), DK) << Record->isUnion();
5214 Invalid = true;
5215 }
5216 }
5217 }
5218
5219 // C++11 [class.union]p8 (DR1460):
5220 // At most one variant member of a union may have a
5221 // brace-or-equal-initializer.
5222 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5223 Owner->isRecord())
5224 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5225 cast<CXXRecordDecl>(Record));
5226 }
5227
5228 if (!Record->isUnion() && !Owner->isRecord()) {
5229 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5230 << getLangOpts().CPlusPlus;
5231 Invalid = true;
5232 }
5233
5234 // C++ [dcl.dcl]p3:
5235 // [If there are no declarators], and except for the declaration of an
5236 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5237 // names into the program
5238 // C++ [class.mem]p2:
5239 // each such member-declaration shall either declare at least one member
5240 // name of the class or declare at least one unnamed bit-field
5241 //
5242 // For C this is an error even for a named struct, and is diagnosed elsewhere.
5243 if (getLangOpts().CPlusPlus && Record->field_empty())
5244 Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5245
5246 // Mock up a declarator.
5247 Declarator Dc(DS, DeclaratorContext::Member);
5248 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5249 assert(TInfo && "couldn't build declarator info for anonymous struct/union")((void)0);
5250
5251 // Create a declaration for this anonymous struct/union.
5252 NamedDecl *Anon = nullptr;
5253 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5254 Anon = FieldDecl::Create(
5255 Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5256 /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5257 /*BitWidth=*/nullptr, /*Mutable=*/false,
5258 /*InitStyle=*/ICIS_NoInit);
5259 Anon->setAccess(AS);
5260 ProcessDeclAttributes(S, Anon, Dc);
5261
5262 if (getLangOpts().CPlusPlus)
5263 FieldCollector->Add(cast<FieldDecl>(Anon));
5264 } else {
5265 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5266 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
5267 if (SCSpec == DeclSpec::SCS_mutable) {
5268 // mutable can only appear on non-static class members, so it's always
5269 // an error here
5270 Diag(Record->getLocation(), diag::err_mutable_nonmember);
5271 Invalid = true;
5272 SC = SC_None;
5273 }
5274
5275 assert(DS.getAttributes().empty() && "No attribute expected")((void)0);
5276 Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5277 Record->getLocation(), /*IdentifierInfo=*/nullptr,
5278 Context.getTypeDeclType(Record), TInfo, SC);
5279
5280 // Default-initialize the implicit variable. This initialization will be
5281 // trivial in almost all cases, except if a union member has an in-class
5282 // initializer:
5283 // union { int n = 0; };
5284 if (!Invalid)
5285 ActOnUninitializedDecl(Anon);
5286 }
5287 Anon->setImplicit();
5288
5289 // Mark this as an anonymous struct/union type.
5290 Record->setAnonymousStructOrUnion(true);
5291
5292 // Add the anonymous struct/union object to the current
5293 // context. We'll be referencing this object when we refer to one of
5294 // its members.
5295 Owner->addDecl(Anon);
5296
5297 // Inject the members of the anonymous struct/union into the owning
5298 // context and into the identifier resolver chain for name lookup
5299 // purposes.
5300 SmallVector<NamedDecl*, 2> Chain;
5301 Chain.push_back(Anon);
5302
5303 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5304 Invalid = true;
5305
5306 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5307 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5308 MangleNumberingContext *MCtx;
5309 Decl *ManglingContextDecl;
5310 std::tie(MCtx, ManglingContextDecl) =
5311 getCurrentMangleNumberContext(NewVD->getDeclContext());
5312 if (MCtx) {
5313 Context.setManglingNumber(
5314 NewVD, MCtx->getManglingNumber(
5315 NewVD, getMSManglingNumber(getLangOpts(), S)));
5316 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5317 }
5318 }
5319 }
5320
5321 if (Invalid)
5322 Anon->setInvalidDecl();
5323
5324 return Anon;
5325}
5326
5327/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5328/// Microsoft C anonymous structure.
5329/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5330/// Example:
5331///
5332/// struct A { int a; };
5333/// struct B { struct A; int b; };
5334///
5335/// void foo() {
5336/// B var;
5337/// var.a = 3;
5338/// }
5339///
5340Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
5341 RecordDecl *Record) {
5342 assert(Record && "expected a record!")((void)0);
5343
5344 // Mock up a declarator.
5345 Declarator Dc(DS, DeclaratorContext::TypeName);
5346 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5347 assert(TInfo && "couldn't build declarator info for anonymous struct")((void)0);
5348
5349 auto *ParentDecl = cast<RecordDecl>(CurContext);
5350 QualType RecTy = Context.getTypeDeclType(Record);
5351
5352 // Create a declaration for this anonymous struct.
5353 NamedDecl *Anon =
5354 FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5355 /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5356 /*BitWidth=*/nullptr, /*Mutable=*/false,
5357 /*InitStyle=*/ICIS_NoInit);
5358 Anon->setImplicit();
5359
5360 // Add the anonymous struct object to the current context.
5361 CurContext->addDecl(Anon);
5362
5363 // Inject the members of the anonymous struct into the current
5364 // context and into the identifier resolver chain for name lookup
5365 // purposes.
5366 SmallVector<NamedDecl*, 2> Chain;
5367 Chain.push_back(Anon);
5368
5369 RecordDecl *RecordDef = Record->getDefinition();
5370 if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5371 diag::err_field_incomplete_or_sizeless) ||
5372 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5373 AS_none, Chain)) {
5374 Anon->setInvalidDecl();
5375 ParentDecl->setInvalidDecl();
5376 }
5377
5378 return Anon;
5379}
5380
5381/// GetNameForDeclarator - Determine the full declaration name for the
5382/// given Declarator.
5383DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
5384 return GetNameFromUnqualifiedId(D.getName());
5385}
5386
5387/// Retrieves the declaration name from a parsed unqualified-id.
5388DeclarationNameInfo
5389Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
5390 DeclarationNameInfo NameInfo;
5391 NameInfo.setLoc(Name.StartLocation);
5392
5393 switch (Name.getKind()) {
5394
5395 case UnqualifiedIdKind::IK_ImplicitSelfParam:
5396 case UnqualifiedIdKind::IK_Identifier:
5397 NameInfo.setName(Name.Identifier);
5398 return NameInfo;
5399
5400 case UnqualifiedIdKind::IK_DeductionGuideName: {
5401 // C++ [temp.deduct.guide]p3:
5402 // The simple-template-id shall name a class template specialization.
5403 // The template-name shall be the same identifier as the template-name
5404 // of the simple-template-id.
5405 // These together intend to imply that the template-name shall name a
5406 // class template.
5407 // FIXME: template<typename T> struct X {};
5408 // template<typename T> using Y = X<T>;
5409 // Y(int) -> Y<int>;
5410 // satisfies these rules but does not name a class template.
5411 TemplateName TN = Name.TemplateName.get().get();
5412 auto *Template = TN.getAsTemplateDecl();
5413 if (!Template || !isa<ClassTemplateDecl>(Template)) {
5414 Diag(Name.StartLocation,
5415 diag::err_deduction_guide_name_not_class_template)
5416 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5417 if (Template)
5418 Diag(Template->getLocation(), diag::note_template_decl_here);
5419 return DeclarationNameInfo();
5420 }
5421
5422 NameInfo.setName(
5423 Context.DeclarationNames.getCXXDeductionGuideName(Template));
5424 return NameInfo;
5425 }
5426
5427 case UnqualifiedIdKind::IK_OperatorFunctionId:
5428 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5429 Name.OperatorFunctionId.Operator));
5430 NameInfo.setCXXOperatorNameRange(SourceRange(
5431 Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5432 return NameInfo;
5433
5434 case UnqualifiedIdKind::IK_LiteralOperatorId:
5435 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5436 Name.Identifier));
5437 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5438 return NameInfo;
5439
5440 case UnqualifiedIdKind::IK_ConversionFunctionId: {
5441 TypeSourceInfo *TInfo;
5442 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5443 if (Ty.isNull())
5444 return DeclarationNameInfo();
5445 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5446 Context.getCanonicalType(Ty)));
5447 NameInfo.setNamedTypeInfo(TInfo);
5448 return NameInfo;
5449 }
5450
5451 case UnqualifiedIdKind::IK_ConstructorName: {
5452 TypeSourceInfo *TInfo;
5453 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5454 if (Ty.isNull())
5455 return DeclarationNameInfo();
5456 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5457 Context.getCanonicalType(Ty)));
5458 NameInfo.setNamedTypeInfo(TInfo);
5459 return NameInfo;
5460 }
5461
5462 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5463 // In well-formed code, we can only have a constructor
5464 // template-id that refers to the current context, so go there
5465 // to find the actual type being constructed.
5466 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5467 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5468 return DeclarationNameInfo();
5469
5470 // Determine the type of the class being constructed.
5471 QualType CurClassType = Context.getTypeDeclType(CurClass);
5472
5473 // FIXME: Check two things: that the template-id names the same type as
5474 // CurClassType, and that the template-id does not occur when the name
5475 // was qualified.
5476
5477 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5478 Context.getCanonicalType(CurClassType)));
5479 // FIXME: should we retrieve TypeSourceInfo?
5480 NameInfo.setNamedTypeInfo(nullptr);
5481 return NameInfo;
5482 }
5483
5484 case UnqualifiedIdKind::IK_DestructorName: {
5485 TypeSourceInfo *TInfo;
5486 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5487 if (Ty.isNull())
5488 return DeclarationNameInfo();
5489 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5490 Context.getCanonicalType(Ty)));
5491 NameInfo.setNamedTypeInfo(TInfo);
5492 return NameInfo;
5493 }
5494
5495 case UnqualifiedIdKind::IK_TemplateId: {
5496 TemplateName TName = Name.TemplateId->Template.get();
5497 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5498 return Context.getNameForTemplate(TName, TNameLoc);
5499 }
5500
5501 } // switch (Name.getKind())
5502
5503 llvm_unreachable("Unknown name kind")__builtin_unreachable();
5504}
5505
5506static QualType getCoreType(QualType Ty) {
5507 do {
5508 if (Ty->isPointerType() || Ty->isReferenceType())
5509 Ty = Ty->getPointeeType();
5510 else if (Ty->isArrayType())
5511 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5512 else
5513 return Ty.withoutLocalFastQualifiers();
5514 } while (true);
5515}
5516
5517/// hasSimilarParameters - Determine whether the C++ functions Declaration
5518/// and Definition have "nearly" matching parameters. This heuristic is
5519/// used to improve diagnostics in the case where an out-of-line function
5520/// definition doesn't match any declaration within the class or namespace.
5521/// Also sets Params to the list of indices to the parameters that differ
5522/// between the declaration and the definition. If hasSimilarParameters
5523/// returns true and Params is empty, then all of the parameters match.
5524static bool hasSimilarParameters(ASTContext &Context,
5525 FunctionDecl *Declaration,
5526 FunctionDecl *Definition,
5527 SmallVectorImpl<unsigned> &Params) {
5528 Params.clear();
5529 if (Declaration->param_size() != Definition->param_size())
5530 return false;
5531 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5532 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5533 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5534
5535 // The parameter types are identical
5536 if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5537 continue;
5538
5539 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5540 QualType DefParamBaseTy = getCoreType(DefParamTy);
5541 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5542 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5543
5544 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5545 (DeclTyName && DeclTyName == DefTyName))
5546 Params.push_back(Idx);
5547 else // The two parameters aren't even close
5548 return false;
5549 }
5550
5551 return true;
5552}
5553
5554/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5555/// declarator needs to be rebuilt in the current instantiation.
5556/// Any bits of declarator which appear before the name are valid for
5557/// consideration here. That's specifically the type in the decl spec
5558/// and the base type in any member-pointer chunks.
5559static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5560 DeclarationName Name) {
5561 // The types we specifically need to rebuild are:
5562 // - typenames, typeofs, and decltypes
5563 // - types which will become injected class names
5564 // Of course, we also need to rebuild any type referencing such a
5565 // type. It's safest to just say "dependent", but we call out a
5566 // few cases here.
5567
5568 DeclSpec &DS = D.getMutableDeclSpec();
5569 switch (DS.getTypeSpecType()) {
5570 case DeclSpec::TST_typename:
5571 case DeclSpec::TST_typeofType:
5572 case DeclSpec::TST_underlyingType:
5573 case DeclSpec::TST_atomic: {
5574 // Grab the type from the parser.
5575 TypeSourceInfo *TSI = nullptr;
5576 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5577 if (T.isNull() || !T->isInstantiationDependentType()) break;
5578
5579 // Make sure there's a type source info. This isn't really much
5580 // of a waste; most dependent types should have type source info
5581 // attached already.
5582 if (!TSI)
5583 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5584
5585 // Rebuild the type in the current instantiation.
5586 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5587 if (!TSI) return true;
5588
5589 // Store the new type back in the decl spec.
5590 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5591 DS.UpdateTypeRep(LocType);
5592 break;
5593 }
5594
5595 case DeclSpec::TST_decltype:
5596 case DeclSpec::TST_typeofExpr: {
5597 Expr *E = DS.getRepAsExpr();
5598 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5599 if (Result.isInvalid()) return true;
5600 DS.UpdateExprRep(Result.get());
5601 break;
5602 }
5603
5604 default:
5605 // Nothing to do for these decl specs.
5606 break;
5607 }
5608
5609 // It doesn't matter what order we do this in.
5610 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5611 DeclaratorChunk &Chunk = D.getTypeObject(I);
5612
5613 // The only type information in the declarator which can come
5614 // before the declaration name is the base type of a member
5615 // pointer.
5616 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5617 continue;
5618
5619 // Rebuild the scope specifier in-place.
5620 CXXScopeSpec &SS = Chunk.Mem.Scope();
5621 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5622 return true;
5623 }
5624
5625 return false;
5626}
5627
5628void Sema::warnOnReservedIdentifier(const NamedDecl *D) {
5629 // Avoid warning twice on the same identifier, and don't warn on redeclaration
5630 // of system decl.
5631 if (D->getPreviousDecl() || D->isImplicit())
5632 return;
5633 ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5634 if (Status != ReservedIdentifierStatus::NotReserved &&
5635 !Context.getSourceManager().isInSystemHeader(D->getLocation()))
5636 Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5637 << D << static_cast<int>(Status);
5638}
5639
5640Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5641 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration);
5642 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5643
5644 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5645 Dcl && Dcl->getDeclContext()->isFileContext())
5646 Dcl->setTopLevelDeclInObjCContainer();
5647
5648 return Dcl;
5649}
5650
5651/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5652/// If T is the name of a class, then each of the following shall have a
5653/// name different from T:
5654/// - every static data member of class T;
5655/// - every member function of class T
5656/// - every member of class T that is itself a type;
5657/// \returns true if the declaration name violates these rules.
5658bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5659 DeclarationNameInfo NameInfo) {
5660 DeclarationName Name = NameInfo.getName();
5661
5662 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5663 while (Record && Record->isAnonymousStructOrUnion())
5664 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5665 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5666 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5667 return true;
5668 }
5669
5670 return false;
5671}
5672
5673/// Diagnose a declaration whose declarator-id has the given
5674/// nested-name-specifier.
5675///
5676/// \param SS The nested-name-specifier of the declarator-id.
5677///
5678/// \param DC The declaration context to which the nested-name-specifier
5679/// resolves.
5680///
5681/// \param Name The name of the entity being declared.
5682///
5683/// \param Loc The location of the name of the entity being declared.
5684///
5685/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5686/// we're declaring an explicit / partial specialization / instantiation.
5687///
5688/// \returns true if we cannot safely recover from this error, false otherwise.
5689bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5690 DeclarationName Name,
5691 SourceLocation Loc, bool IsTemplateId) {
5692 DeclContext *Cur = CurContext;
5693 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5694 Cur = Cur->getParent();
5695
5696 // If the user provided a superfluous scope specifier that refers back to the
5697 // class in which the entity is already declared, diagnose and ignore it.
5698 //
5699 // class X {
5700 // void X::f();
5701 // };
5702 //
5703 // Note, it was once ill-formed to give redundant qualification in all
5704 // contexts, but that rule was removed by DR482.
5705 if (Cur->Equals(DC)) {
5706 if (Cur->isRecord()) {
5707 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5708 : diag::err_member_extra_qualification)
5709 << Name << FixItHint::CreateRemoval(SS.getRange());
5710 SS.clear();
5711 } else {
5712 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5713 }
5714 return false;
5715 }
5716
5717 // Check whether the qualifying scope encloses the scope of the original
5718 // declaration. For a template-id, we perform the checks in
5719 // CheckTemplateSpecializationScope.
5720 if (!Cur->Encloses(DC) && !IsTemplateId) {
5721 if (Cur->isRecord())
5722 Diag(Loc, diag::err_member_qualification)
5723 << Name << SS.getRange();
5724 else if (isa<TranslationUnitDecl>(DC))
5725 Diag(Loc, diag::err_invalid_declarator_global_scope)
5726 << Name << SS.getRange();
5727 else if (isa<FunctionDecl>(Cur))
5728 Diag(Loc, diag::err_invalid_declarator_in_function)
5729 << Name << SS.getRange();
5730 else if (isa<BlockDecl>(Cur))
5731 Diag(Loc, diag::err_invalid_declarator_in_block)
5732 << Name << SS.getRange();
5733 else
5734 Diag(Loc, diag::err_invalid_declarator_scope)
5735 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5736
5737 return true;
5738 }
5739
5740 if (Cur->isRecord()) {
5741 // Cannot qualify members within a class.
5742 Diag(Loc, diag::err_member_qualification)
5743 << Name << SS.getRange();
5744 SS.clear();
5745
5746 // C++ constructors and destructors with incorrect scopes can break
5747 // our AST invariants by having the wrong underlying types. If
5748 // that's the case, then drop this declaration entirely.
5749 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5750 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5751 !Context.hasSameType(Name.getCXXNameType(),
5752 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5753 return true;
5754
5755 return false;
5756 }
5757
5758 // C++11 [dcl.meaning]p1:
5759 // [...] "The nested-name-specifier of the qualified declarator-id shall
5760 // not begin with a decltype-specifer"
5761 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5762 while (SpecLoc.getPrefix())
5763 SpecLoc = SpecLoc.getPrefix();
5764 if (dyn_cast_or_null<DecltypeType>(
5765 SpecLoc.getNestedNameSpecifier()->getAsType()))
5766 Diag(Loc, diag::err_decltype_in_declarator)
5767 << SpecLoc.getTypeLoc().getSourceRange();
5768
5769 return false;
5770}
5771
5772NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5773 MultiTemplateParamsArg TemplateParamLists) {
5774 // TODO: consider using NameInfo for diagnostic.
5775 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5776 DeclarationName Name = NameInfo.getName();
5777
5778 // All of these full declarators require an identifier. If it doesn't have
5779 // one, the ParsedFreeStandingDeclSpec action should be used.
5780 if (D.isDecompositionDeclarator()) {
5781 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5782 } else if (!Name) {
5783 if (!D.isInvalidType()) // Reject this if we think it is valid.
5784 Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5785 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5786 return nullptr;
5787 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5788 return nullptr;
5789
5790 // The scope passed in may not be a decl scope. Zip up the scope tree until
5791 // we find one that is.
5792 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5793 (S->getFlags() & Scope::TemplateParamScope) != 0)
5794 S = S->getParent();
5795
5796 DeclContext *DC = CurContext;
5797 if (D.getCXXScopeSpec().isInvalid())
5798 D.setInvalidType();
5799 else if (D.getCXXScopeSpec().isSet()) {
5800 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5801 UPPC_DeclarationQualifier))
5802 return nullptr;
5803
5804 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5805 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5806 if (!DC || isa<EnumDecl>(DC)) {
5807 // If we could not compute the declaration context, it's because the
5808 // declaration context is dependent but does not refer to a class,
5809 // class template, or class template partial specialization. Complain
5810 // and return early, to avoid the coming semantic disaster.
5811 Diag(D.getIdentifierLoc(),
5812 diag::err_template_qualified_declarator_no_match)
5813 << D.getCXXScopeSpec().getScopeRep()
5814 << D.getCXXScopeSpec().getRange();
5815 return nullptr;
5816 }
5817 bool IsDependentContext = DC->isDependentContext();
5818
5819 if (!IsDependentContext &&
5820 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5821 return nullptr;
5822
5823 // If a class is incomplete, do not parse entities inside it.
5824 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5825 Diag(D.getIdentifierLoc(),
5826 diag::err_member_def_undefined_record)
5827 << Name << DC << D.getCXXScopeSpec().getRange();
5828 return nullptr;
5829 }
5830 if (!D.getDeclSpec().isFriendSpecified()) {
5831 if (diagnoseQualifiedDeclaration(
5832 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5833 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5834 if (DC->isRecord())
5835 return nullptr;
5836
5837 D.setInvalidType();
5838 }
5839 }
5840
5841 // Check whether we need to rebuild the type of the given
5842 // declaration in the current instantiation.
5843 if (EnteringContext && IsDependentContext &&
5844 TemplateParamLists.size() != 0) {
5845 ContextRAII SavedContext(*this, DC);
5846 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5847 D.setInvalidType();
5848 }
5849 }
5850
5851 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5852 QualType R = TInfo->getType();
5853
5854 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5855 UPPC_DeclarationType))
5856 D.setInvalidType();
5857
5858 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5859 forRedeclarationInCurContext());
5860
5861 // See if this is a redefinition of a variable in the same scope.
5862 if (!D.getCXXScopeSpec().isSet()) {
5863 bool IsLinkageLookup = false;
5864 bool CreateBuiltins = false;
5865
5866 // If the declaration we're planning to build will be a function
5867 // or object with linkage, then look for another declaration with
5868 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5869 //
5870 // If the declaration we're planning to build will be declared with
5871 // external linkage in the translation unit, create any builtin with
5872 // the same name.
5873 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5874 /* Do nothing*/;
5875 else if (CurContext->isFunctionOrMethod() &&
5876 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5877 R->isFunctionType())) {
5878 IsLinkageLookup = true;
5879 CreateBuiltins =
5880 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5881 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5882 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5883 CreateBuiltins = true;
5884
5885 if (IsLinkageLookup) {
5886 Previous.clear(LookupRedeclarationWithLinkage);
5887 Previous.setRedeclarationKind(ForExternalRedeclaration);
5888 }
5889
5890 LookupName(Previous, S, CreateBuiltins);
5891 } else { // Something like "int foo::x;"
5892 LookupQualifiedName(Previous, DC);
5893
5894 // C++ [dcl.meaning]p1:
5895 // When the declarator-id is qualified, the declaration shall refer to a
5896 // previously declared member of the class or namespace to which the
5897 // qualifier refers (or, in the case of a namespace, of an element of the
5898 // inline namespace set of that namespace (7.3.1)) or to a specialization
5899 // thereof; [...]
5900 //
5901 // Note that we already checked the context above, and that we do not have
5902 // enough information to make sure that Previous contains the declaration
5903 // we want to match. For example, given:
5904 //
5905 // class X {
5906 // void f();
5907 // void f(float);
5908 // };
5909 //
5910 // void X::f(int) { } // ill-formed
5911 //
5912 // In this case, Previous will point to the overload set
5913 // containing the two f's declared in X, but neither of them
5914 // matches.
5915
5916 // C++ [dcl.meaning]p1:
5917 // [...] the member shall not merely have been introduced by a
5918 // using-declaration in the scope of the class or namespace nominated by
5919 // the nested-name-specifier of the declarator-id.
5920 RemoveUsingDecls(Previous);
5921 }
5922
5923 if (Previous.isSingleResult() &&
5924 Previous.getFoundDecl()->isTemplateParameter()) {
5925 // Maybe we will complain about the shadowed template parameter.
5926 if (!D.isInvalidType())
5927 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5928 Previous.getFoundDecl());
5929
5930 // Just pretend that we didn't see the previous declaration.
5931 Previous.clear();
5932 }
5933
5934 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5935 // Forget that the previous declaration is the injected-class-name.
5936 Previous.clear();
5937
5938 // In C++, the previous declaration we find might be a tag type
5939 // (class or enum). In this case, the new declaration will hide the
5940 // tag type. Note that this applies to functions, function templates, and
5941 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5942 if (Previous.isSingleTagDecl() &&
5943 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5944 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5945 Previous.clear();
5946
5947 // Check that there are no default arguments other than in the parameters
5948 // of a function declaration (C++ only).
5949 if (getLangOpts().CPlusPlus)
5950 CheckExtraCXXDefaultArguments(D);
5951
5952 NamedDecl *New;
5953
5954 bool AddToScope = true;
5955 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5956 if (TemplateParamLists.size()) {
5957 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5958 return nullptr;
5959 }
5960
5961 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5962 } else if (R->isFunctionType()) {
5963 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5964 TemplateParamLists,
5965 AddToScope);
5966 } else {
5967 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5968 AddToScope);
5969 }
5970
5971 if (!New)
5972 return nullptr;
5973
5974 // If this has an identifier and is not a function template specialization,
5975 // add it to the scope stack.
5976 if (New->getDeclName() && AddToScope)
5977 PushOnScopeChains(New, S);
5978
5979 if (isInOpenMPDeclareTargetContext())
5980 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5981
5982 return New;
5983}
5984
5985/// Helper method to turn variable array types into constant array
5986/// types in certain situations which would otherwise be errors (for
5987/// GCC compatibility).
5988static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5989 ASTContext &Context,
5990 bool &SizeIsNegative,
5991 llvm::APSInt &Oversized) {
5992 // This method tries to turn a variable array into a constant
5993 // array even when the size isn't an ICE. This is necessary
5994 // for compatibility with code that depends on gcc's buggy
5995 // constant expression folding, like struct {char x[(int)(char*)2];}
5996 SizeIsNegative = false;
5997 Oversized = 0;
5998
5999 if (T->isDependentType())
6000 return QualType();
6001
6002 QualifierCollector Qs;
6003 const Type *Ty = Qs.strip(T);
6004
6005 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6006 QualType Pointee = PTy->getPointeeType();
6007 QualType FixedType =
6008 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6009 Oversized);
6010 if (FixedType.isNull()) return FixedType;
6011 FixedType = Context.getPointerType(FixedType);
6012 return Qs.apply(Context, FixedType);
6013 }
6014 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6015 QualType Inner = PTy->getInnerType();
6016 QualType FixedType =
6017 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6018 Oversized);
6019 if (FixedType.isNull()) return FixedType;
6020 FixedType = Context.getParenType(FixedType);
6021 return Qs.apply(Context, FixedType);
6022 }
6023
6024 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6025 if (!VLATy)
6026 return QualType();
6027
6028 QualType ElemTy = VLATy->getElementType();
6029 if (ElemTy->isVariablyModifiedType()) {
6030 ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6031 SizeIsNegative, Oversized);
6032 if (ElemTy.isNull())
6033 return QualType();
6034 }
6035
6036 Expr::EvalResult Result;
6037 if (!VLATy->getSizeExpr() ||
6038 !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6039 return QualType();
6040
6041 llvm::APSInt Res = Result.Val.getInt();
6042
6043 // Check whether the array size is negative.
6044 if (Res.isSigned() && Res.isNegative()) {
6045 SizeIsNegative = true;
6046 return QualType();
6047 }
6048
6049 // Check whether the array is too large to be addressed.
6050 unsigned ActiveSizeBits =
6051 (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6052 !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6053 ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6054 : Res.getActiveBits();
6055 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6056 Oversized = Res;
6057 return QualType();
6058 }
6059
6060 QualType FoldedArrayType = Context.getConstantArrayType(
6061 ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6062 return Qs.apply(Context, FoldedArrayType);
6063}
6064
6065static void
6066FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
6067 SrcTL = SrcTL.getUnqualifiedLoc();
6068 DstTL = DstTL.getUnqualifiedLoc();
6069 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6070 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6071 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6072 DstPTL.getPointeeLoc());
6073 DstPTL.setStarLoc(SrcPTL.getStarLoc());
6074 return;
6075 }
6076 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6077 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6078 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6079 DstPTL.getInnerLoc());
6080 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6081 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6082 return;
6083 }
6084 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6085 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6086 TypeLoc SrcElemTL = SrcATL.getElementLoc();
6087 TypeLoc DstElemTL = DstATL.getElementLoc();
6088 if (VariableArrayTypeLoc SrcElemATL =
6089 SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6090 ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6091 FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6092 } else {
6093 DstElemTL.initializeFullCopy(SrcElemTL);
6094 }
6095 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6096 DstATL.setSizeExpr(SrcATL.getSizeExpr());
6097 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6098}
6099
6100/// Helper method to turn variable array types into constant array
6101/// types in certain situations which would otherwise be errors (for
6102/// GCC compatibility).
6103static TypeSourceInfo*
6104TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
6105 ASTContext &Context,
6106 bool &SizeIsNegative,
6107 llvm::APSInt &Oversized) {
6108 QualType FixedTy
6109 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6110 SizeIsNegative, Oversized);
6111 if (FixedTy.isNull())
6112 return nullptr;
6113 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6114 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
6115 FixedTInfo->getTypeLoc());
6116 return FixedTInfo;
6117}
6118
6119/// Attempt to fold a variable-sized type to a constant-sized type, returning
6120/// true if we were successful.
6121bool Sema::tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
6122 QualType &T, SourceLocation Loc,
6123 unsigned FailedFoldDiagID) {
6124 bool SizeIsNegative;
6125 llvm::APSInt Oversized;
6126 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
6127 TInfo, Context, SizeIsNegative, Oversized);
6128 if (FixedTInfo) {
6129 Diag(Loc, diag::ext_vla_folded_to_constant);
6130 TInfo = FixedTInfo;
6131 T = FixedTInfo->getType();
6132 return true;
6133 }
6134
6135 if (SizeIsNegative)
6136 Diag(Loc, diag::err_typecheck_negative_array_size);
6137 else if (Oversized.getBoolValue())
6138 Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6139 else if (FailedFoldDiagID)
6140 Diag(Loc, FailedFoldDiagID);
6141 return false;
6142}
6143
6144/// Register the given locally-scoped extern "C" declaration so
6145/// that it can be found later for redeclarations. We include any extern "C"
6146/// declaration that is not visible in the translation unit here, not just
6147/// function-scope declarations.
6148void
6149Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
6150 if (!getLangOpts().CPlusPlus &&
6151 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
6152 // Don't need to track declarations in the TU in C.
6153 return;
6154
6155 // Note that we have a locally-scoped external with this name.
6156 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
6157}
6158
6159NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
6160 // FIXME: We can have multiple results via __attribute__((overloadable)).
6161 auto Result = Context.getExternCContextDecl()->lookup(Name);
6162 return Result.empty() ? nullptr : *Result.begin();
6163}
6164
6165/// Diagnose function specifiers on a declaration of an identifier that
6166/// does not identify a function.
6167void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
6168 // FIXME: We should probably indicate the identifier in question to avoid
6169 // confusion for constructs like "virtual int a(), b;"
6170 if (DS.isVirtualSpecified())
6171 Diag(DS.getVirtualSpecLoc(),
6172 diag::err_virtual_non_function);
6173
6174 if (DS.hasExplicitSpecifier())
6175 Diag(DS.getExplicitSpecLoc(),
6176 diag::err_explicit_non_function);
6177
6178 if (DS.isNoreturnSpecified())
6179 Diag(DS.getNoreturnSpecLoc(),
6180 diag::err_noreturn_non_function);
6181}
6182
6183NamedDecl*
6184Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
6185 TypeSourceInfo *TInfo, LookupResult &Previous) {
6186 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6187 if (D.getCXXScopeSpec().isSet()) {
6188 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6189 << D.getCXXScopeSpec().getRange();
6190 D.setInvalidType();
6191 // Pretend we didn't see the scope specifier.
6192 DC = CurContext;
6193 Previous.clear();
6194 }
6195
6196 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6197
6198 if (D.getDeclSpec().isInlineSpecified())
6199 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6200 << getLangOpts().CPlusPlus17;
6201 if (D.getDeclSpec().hasConstexprSpecifier())
6202 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6203 << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6204
6205 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
6206 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
6207 Diag(D.getName().StartLocation,
6208 diag::err_deduction_guide_invalid_specifier)
6209 << "typedef";
6210 else
6211 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6212 << D.getName().getSourceRange();
6213 return nullptr;
6214 }
6215
6216 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6217 if (!NewTD) return nullptr;
6218
6219 // Handle attributes prior to checking for duplicates in MergeVarDecl
6220 ProcessDeclAttributes(S, NewTD, D);
6221
6222 CheckTypedefForVariablyModifiedType(S, NewTD);
6223
6224 bool Redeclaration = D.isRedeclaration();
6225 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6226 D.setRedeclaration(Redeclaration);
6227 return ND;
6228}
6229
6230void
6231Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
6232 // C99 6.7.7p2: If a typedef name specifies a variably modified type
6233 // then it shall have block scope.
6234 // Note that variably modified types must be fixed before merging the decl so
6235 // that redeclarations will match.
6236 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6237 QualType T = TInfo->getType();
6238 if (T->isVariablyModifiedType()) {
6239 setFunctionHasBranchProtectedScope();
6240
6241 if (S->getFnParent() == nullptr) {
6242 bool SizeIsNegative;
6243 llvm::APSInt Oversized;
6244 TypeSourceInfo *FixedTInfo =
6245 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6246 SizeIsNegative,
6247 Oversized);
6248 if (FixedTInfo) {
6249 Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6250 NewTD->setTypeSourceInfo(FixedTInfo);
6251 } else {
6252 if (SizeIsNegative)
6253 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6254 else if (T->isVariableArrayType())
6255 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6256 else if (Oversized.getBoolValue())
6257 Diag(NewTD->getLocation(), diag::err_array_too_large)
6258 << toString(Oversized, 10);
6259 else
6260 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6261 NewTD->setInvalidDecl();
6262 }
6263 }
6264 }
6265}
6266
6267/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6268/// declares a typedef-name, either using the 'typedef' type specifier or via
6269/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6270NamedDecl*
6271Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
6272 LookupResult &Previous, bool &Redeclaration) {
6273
6274 // Find the shadowed declaration before filtering for scope.
6275 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6276
6277 // Merge the decl with the existing one if appropriate. If the decl is
6278 // in an outer scope, it isn't the same thing.
6279 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6280 /*AllowInlineNamespace*/false);
6281 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
6282 if (!Previous.empty()) {
6283 Redeclaration = true;
6284 MergeTypedefNameDecl(S, NewTD, Previous);
6285 } else {
6286 inferGslPointerAttribute(NewTD);
6287 }
6288
6289 if (ShadowedDecl && !Redeclaration)
6290 CheckShadow(NewTD, ShadowedDecl, Previous);
6291
6292 // If this is the C FILE type, notify the AST context.
6293 if (IdentifierInfo *II = NewTD->getIdentifier())
6294 if (!NewTD->isInvalidDecl() &&
6295 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6296 if (II->isStr("FILE"))
6297 Context.setFILEDecl(NewTD);
6298 else if (II->isStr("jmp_buf"))
6299 Context.setjmp_bufDecl(NewTD);
6300 else if (II->isStr("sigjmp_buf"))
6301 Context.setsigjmp_bufDecl(NewTD);
6302 else if (II->isStr("ucontext_t"))
6303 Context.setucontext_tDecl(NewTD);
6304 }
6305
6306 return NewTD;
6307}
6308
6309/// Determines whether the given declaration is an out-of-scope
6310/// previous declaration.
6311///
6312/// This routine should be invoked when name lookup has found a
6313/// previous declaration (PrevDecl) that is not in the scope where a
6314/// new declaration by the same name is being introduced. If the new
6315/// declaration occurs in a local scope, previous declarations with
6316/// linkage may still be considered previous declarations (C99
6317/// 6.2.2p4-5, C++ [basic.link]p6).
6318///
6319/// \param PrevDecl the previous declaration found by name
6320/// lookup
6321///
6322/// \param DC the context in which the new declaration is being
6323/// declared.
6324///
6325/// \returns true if PrevDecl is an out-of-scope previous declaration
6326/// for a new delcaration with the same name.
6327static bool
6328isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
6329 ASTContext &Context) {
6330 if (!PrevDecl)
6331 return false;
6332
6333 if (!PrevDecl->hasLinkage())
6334 return false;
6335
6336 if (Context.getLangOpts().CPlusPlus) {
6337 // C++ [basic.link]p6:
6338 // If there is a visible declaration of an entity with linkage
6339 // having the same name and type, ignoring entities declared
6340 // outside the innermost enclosing namespace scope, the block
6341 // scope declaration declares that same entity and receives the
6342 // linkage of the previous declaration.
6343 DeclContext *OuterContext = DC->getRedeclContext();
6344 if (!OuterContext->isFunctionOrMethod())
6345 // This rule only applies to block-scope declarations.
6346 return false;
6347
6348 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6349 if (PrevOuterContext->isRecord())
6350 // We found a member function: ignore it.
6351 return false;
6352
6353 // Find the innermost enclosing namespace for the new and
6354 // previous declarations.
6355 OuterContext = OuterContext->getEnclosingNamespaceContext();
6356 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6357
6358 // The previous declaration is in a different namespace, so it
6359 // isn't the same function.
6360 if (!OuterContext->Equals(PrevOuterContext))
6361 return false;
6362 }
6363
6364 return true;
6365}
6366
6367static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D) {
6368 CXXScopeSpec &SS = D.getCXXScopeSpec();
6369 if (!SS.isSet()) return;
6370 DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
6371}
6372
6373bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
6374 QualType type = decl->getType();
6375 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6376 if (lifetime == Qualifiers::OCL_Autoreleasing) {
6377 // Various kinds of declaration aren't allowed to be __autoreleasing.
6378 unsigned kind = -1U;
6379 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6380 if (var->hasAttr<BlocksAttr>())
6381 kind = 0; // __block
6382 else if (!var->hasLocalStorage())
6383 kind = 1; // global
6384 } else if (isa<ObjCIvarDecl>(decl)) {
6385 kind = 3; // ivar
6386 } else if (isa<FieldDecl>(decl)) {
6387 kind = 2; // field
6388 }
6389
6390 if (kind != -1U) {
6391 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6392 << kind;
6393 }
6394 } else if (lifetime == Qualifiers::OCL_None) {
6395 // Try to infer lifetime.
6396 if (!type->isObjCLifetimeType())
6397 return false;
6398
6399 lifetime = type->getObjCARCImplicitLifetime();
6400 type = Context.getLifetimeQualifiedType(type, lifetime);
6401 decl->setType(type);
6402 }
6403
6404 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6405 // Thread-local variables cannot have lifetime.
6406 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6407 var->getTLSKind()) {
6408 Diag(var->getLocation(), diag::err_arc_thread_ownership)
6409 << var->getType();
6410 return true;
6411 }
6412 }
6413
6414 return false;
6415}
6416
6417void Sema::deduceOpenCLAddressSpace(ValueDecl *Decl) {
6418 if (Decl->getType().hasAddressSpace())
6419 return;
6420 if (Decl->getType()->isDependentType())
6421 return;
6422 if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6423 QualType Type = Var->getType();
6424 if (Type->isSamplerT() || Type->isVoidType())
6425 return;
6426 LangAS ImplAS = LangAS::opencl_private;
6427 // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6428 // __opencl_c_program_scope_global_variables feature, the address space
6429 // for a variable at program scope or a static or extern variable inside
6430 // a function are inferred to be __global.
6431 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6432 Var->hasGlobalStorage())
6433 ImplAS = LangAS::opencl_global;
6434 // If the original type from a decayed type is an array type and that array
6435 // type has no address space yet, deduce it now.
6436 if (auto DT = dyn_cast<DecayedType>(Type)) {
6437 auto OrigTy = DT->getOriginalType();
6438 if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6439 // Add the address space to the original array type and then propagate
6440 // that to the element type through `getAsArrayType`.
6441 OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6442 OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6443 // Re-generate the decayed type.
6444 Type = Context.getDecayedType(OrigTy);
6445 }
6446 }
6447 Type = Context.getAddrSpaceQualType(Type, ImplAS);
6448 // Apply any qualifiers (including address space) from the array type to
6449 // the element type. This implements C99 6.7.3p8: "If the specification of
6450 // an array type includes any type qualifiers, the element type is so
6451 // qualified, not the array type."
6452 if (Type->isArrayType())
6453 Type = QualType(Context.getAsArrayType(Type), 0);
6454 Decl->setType(Type);
6455 }
6456}
6457
6458static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
6459 // Ensure that an auto decl is deduced otherwise the checks below might cache
6460 // the wrong linkage.
6461 assert(S.ParsingInitForAutoVars.count(&ND) == 0)((void)0);
6462
6463 // 'weak' only applies to declarations with external linkage.
6464 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6465 if (!ND.isExternallyVisible()) {
6466 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6467 ND.dropAttr<WeakAttr>();
6468 }
6469 }
6470 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6471 if (ND.isExternallyVisible()) {
6472 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6473 ND.dropAttr<WeakRefAttr>();
6474 ND.dropAttr<AliasAttr>();
6475 }
6476 }
6477
6478 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6479 if (VD->hasInit()) {
6480 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6481 assert(VD->isThisDeclarationADefinition() &&((void)0)
6482 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")((void)0);
6483 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6484 VD->dropAttr<AliasAttr>();
6485 }
6486 }
6487 }
6488
6489 // 'selectany' only applies to externally visible variable declarations.
6490 // It does not apply to functions.
6491 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6492 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6493 S.Diag(Attr->getLocation(),
6494 diag::err_attribute_selectany_non_extern_data);
6495 ND.dropAttr<SelectAnyAttr>();
6496 }
6497 }
6498
6499 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6500 auto *VD = dyn_cast<VarDecl>(&ND);
6501 bool IsAnonymousNS = false;
6502 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6503 if (VD) {
6504 const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6505 while (NS && !IsAnonymousNS) {
6506 IsAnonymousNS = NS->isAnonymousNamespace();
6507 NS = dyn_cast<NamespaceDecl>(NS->getParent());
6508 }
6509 }
6510 // dll attributes require external linkage. Static locals may have external
6511 // linkage but still cannot be explicitly imported or exported.
6512 // In Microsoft mode, a variable defined in anonymous namespace must have
6513 // external linkage in order to be exported.
6514 bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6515 if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6516 (!AnonNSInMicrosoftMode &&
6517 (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6518 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6519 << &ND << Attr;
6520 ND.setInvalidDecl();
6521 }
6522 }
6523
6524 // Check the attributes on the function type, if any.
6525 if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6526 // Don't declare this variable in the second operand of the for-statement;
6527 // GCC miscompiles that by ending its lifetime before evaluating the
6528 // third operand. See gcc.gnu.org/PR86769.
6529 AttributedTypeLoc ATL;
6530 for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6531 (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6532 TL = ATL.getModifiedLoc()) {
6533 // The [[lifetimebound]] attribute can be applied to the implicit object
6534 // parameter of a non-static member function (other than a ctor or dtor)
6535 // by applying it to the function type.
6536 if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6537 const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6538 if (!MD || MD->isStatic()) {
6539 S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6540 << !MD << A->getRange();
6541 } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6542 S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6543 << isa<CXXDestructorDecl>(MD) << A->getRange();
6544 }
6545 }
6546 }
6547 }
6548}
6549
6550static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
6551 NamedDecl *NewDecl,
6552 bool IsSpecialization,
6553 bool IsDefinition) {
6554 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6555 return;
6556
6557 bool IsTemplate = false;
6558 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6559 OldDecl = OldTD->getTemplatedDecl();
6560 IsTemplate = true;
6561 if (!IsSpecialization)
6562 IsDefinition = false;
6563 }
6564 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6565 NewDecl = NewTD->getTemplatedDecl();
6566 IsTemplate = true;
6567 }
6568
6569 if (!OldDecl || !NewDecl)
6570 return;
6571
6572 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6573 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6574 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6575 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6576
6577 // dllimport and dllexport are inheritable attributes so we have to exclude
6578 // inherited attribute instances.
6579 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6580 (NewExportAttr && !NewExportAttr->isInherited());
6581
6582 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6583 // the only exception being explicit specializations.
6584 // Implicitly generated declarations are also excluded for now because there
6585 // is no other way to switch these to use dllimport or dllexport.
6586 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6587
6588 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6589 // Allow with a warning for free functions and global variables.
6590 bool JustWarn = false;
6591 if (!OldDecl->isCXXClassMember()) {
6592 auto *VD = dyn_cast<VarDecl>(OldDecl);
6593 if (VD && !VD->getDescribedVarTemplate())
6594 JustWarn = true;
6595 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6596 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6597 JustWarn = true;
6598 }
6599
6600 // We cannot change a declaration that's been used because IR has already
6601 // been emitted. Dllimported functions will still work though (modulo
6602 // address equality) as they can use the thunk.
6603 if (OldDecl->isUsed())
6604 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6605 JustWarn = false;
6606
6607 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6608 : diag::err_attribute_dll_redeclaration;
6609 S.Diag(NewDecl->getLocation(), DiagID)
6610 << NewDecl
6611 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6612 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6613 if (!JustWarn) {
6614 NewDecl->setInvalidDecl();
6615 return;
6616 }
6617 }
6618
6619 // A redeclaration is not allowed to drop a dllimport attribute, the only
6620 // exceptions being inline function definitions (except for function
6621 // templates), local extern declarations, qualified friend declarations or
6622 // special MSVC extension: in the last case, the declaration is treated as if
6623 // it were marked dllexport.
6624 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6625 bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6626 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6627 // Ignore static data because out-of-line definitions are diagnosed
6628 // separately.
6629 IsStaticDataMember = VD->isStaticDataMember();
6630 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6631 VarDecl::DeclarationOnly;
6632 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6633 IsInline = FD->isInlined();
6634 IsQualifiedFriend = FD->getQualifier() &&
6635 FD->getFriendObjectKind() == Decl::FOK_Declared;
6636 }
6637
6638 if (OldImportAttr && !HasNewAttr &&
6639 (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6640 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6641 if (IsMicrosoftABI && IsDefinition) {
6642 S.Diag(NewDecl->getLocation(),
6643 diag::warn_redeclaration_without_import_attribute)
6644 << NewDecl;
6645 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6646 NewDecl->dropAttr<DLLImportAttr>();
6647 NewDecl->addAttr(
6648 DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6649 } else {
6650 S.Diag(NewDecl->getLocation(),
6651 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6652 << NewDecl << OldImportAttr;
6653 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6654 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6655 OldDecl->dropAttr<DLLImportAttr>();
6656 NewDecl->dropAttr<DLLImportAttr>();
6657 }
6658 } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6659 // In MinGW, seeing a function declared inline drops the dllimport
6660 // attribute.
6661 OldDecl->dropAttr<DLLImportAttr>();
6662 NewDecl->dropAttr<DLLImportAttr>();
6663 S.Diag(NewDecl->getLocation(),
6664 diag::warn_dllimport_dropped_from_inline_function)
6665 << NewDecl << OldImportAttr;
6666 }
6667
6668 // A specialization of a class template member function is processed here
6669 // since it's a redeclaration. If the parent class is dllexport, the
6670 // specialization inherits that attribute. This doesn't happen automatically
6671 // since the parent class isn't instantiated until later.
6672 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6673 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6674 !NewImportAttr && !NewExportAttr) {
6675 if (const DLLExportAttr *ParentExportAttr =
6676 MD->getParent()->getAttr<DLLExportAttr>()) {
6677 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6678 NewAttr->setInherited(true);
6679 NewDecl->addAttr(NewAttr);
6680 }
6681 }
6682 }
6683}
6684
6685/// Given that we are within the definition of the given function,
6686/// will that definition behave like C99's 'inline', where the
6687/// definition is discarded except for optimization purposes?
6688static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6689 // Try to avoid calling GetGVALinkageForFunction.
6690
6691 // All cases of this require the 'inline' keyword.
6692 if (!FD->isInlined()) return false;
6693
6694 // This is only possible in C++ with the gnu_inline attribute.
6695 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6696 return false;
6697
6698 // Okay, go ahead and call the relatively-more-expensive function.
6699 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6700}
6701
6702/// Determine whether a variable is extern "C" prior to attaching
6703/// an initializer. We can't just call isExternC() here, because that
6704/// will also compute and cache whether the declaration is externally
6705/// visible, which might change when we attach the initializer.
6706///
6707/// This can only be used if the declaration is known to not be a
6708/// redeclaration of an internal linkage declaration.
6709///
6710/// For instance:
6711///
6712/// auto x = []{};
6713///
6714/// Attaching the initializer here makes this declaration not externally
6715/// visible, because its type has internal linkage.
6716///
6717/// FIXME: This is a hack.
6718template<typename T>
6719static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6720 if (S.getLangOpts().CPlusPlus) {
6721 // In C++, the overloadable attribute negates the effects of extern "C".
6722 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6723 return false;
6724
6725 // So do CUDA's host/device attributes.
6726 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6727 D->template hasAttr<CUDAHostAttr>()))
6728 return false;
6729 }
6730 return D->isExternC();
6731}
6732
6733static bool shouldConsiderLinkage(const VarDecl *VD) {
6734 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6735 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6736 isa<OMPDeclareMapperDecl>(DC))
6737 return VD->hasExternalStorage();
6738 if (DC->isFileContext())
6739 return true;
6740 if (DC->isRecord())
6741 return false;
6742 if (isa<RequiresExprBodyDecl>(DC))
6743 return false;
6744 llvm_unreachable("Unexpected context")__builtin_unreachable();
6745}
6746
6747static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6748 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6749 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6750 isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6751 return true;
6752 if (DC->isRecord())
6753 return false;
6754 llvm_unreachable("Unexpected context")__builtin_unreachable();
6755}
6756
6757static bool hasParsedAttr(Scope *S, const Declarator &PD,
6758 ParsedAttr::Kind Kind) {
6759 // Check decl attributes on the DeclSpec.
6760 if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6761 return true;
6762
6763 // Walk the declarator structure, checking decl attributes that were in a type
6764 // position to the decl itself.
6765 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6766 if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6767 return true;
6768 }
6769
6770 // Finally, check attributes on the decl itself.
6771 return PD.getAttributes().hasAttribute(Kind);
6772}
6773
6774/// Adjust the \c DeclContext for a function or variable that might be a
6775/// function-local external declaration.
6776bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6777 if (!DC->isFunctionOrMethod())
6778 return false;
6779
6780 // If this is a local extern function or variable declared within a function
6781 // template, don't add it into the enclosing namespace scope until it is
6782 // instantiated; it might have a dependent type right now.
6783 if (DC->isDependentContext())
6784 return true;
6785
6786 // C++11 [basic.link]p7:
6787 // When a block scope declaration of an entity with linkage is not found to
6788 // refer to some other declaration, then that entity is a member of the
6789 // innermost enclosing namespace.
6790 //
6791 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6792 // semantically-enclosing namespace, not a lexically-enclosing one.
6793 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6794 DC = DC->getParent();
6795 return true;
6796}
6797
6798/// Returns true if given declaration has external C language linkage.
6799static bool isDeclExternC(const Decl *D) {
6800 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6801 return FD->isExternC();
6802 if (const auto *VD = dyn_cast<VarDecl>(D))
6803 return VD->isExternC();
6804
6805 llvm_unreachable("Unknown type of decl!")__builtin_unreachable();
6806}
6807
6808/// Returns true if there hasn't been any invalid type diagnosed.
6809static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6810 DeclContext *DC = NewVD->getDeclContext();
6811 QualType R = NewVD->getType();
6812
6813 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6814 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6815 // argument.
6816 if (R->isImageType() || R->isPipeType()) {
6817 Se.Diag(NewVD->getLocation(),
6818 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6819 << R;
6820 NewVD->setInvalidDecl();
6821 return false;
6822 }
6823
6824 // OpenCL v1.2 s6.9.r:
6825 // The event type cannot be used to declare a program scope variable.
6826 // OpenCL v2.0 s6.9.q:
6827 // The clk_event_t and reserve_id_t types cannot be declared in program
6828 // scope.
6829 if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6830 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6831 Se.Diag(NewVD->getLocation(),
6832 diag::err_invalid_type_for_program_scope_var)
6833 << R;
6834 NewVD->setInvalidDecl();
6835 return false;
6836 }
6837 }
6838
6839 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6840 if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
6841 Se.getLangOpts())) {
6842 QualType NR = R.getCanonicalType();
6843 while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
6844 NR->isReferenceType()) {
6845 if (NR->isFunctionPointerType() || NR->isMemberFunctionPointerType() ||
6846 NR->isFunctionReferenceType()) {
6847 Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
6848 << NR->isReferenceType();
6849 NewVD->setInvalidDecl();
6850 return false;
6851 }
6852 NR = NR->getPointeeType();
6853 }
6854 }
6855
6856 if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
6857 Se.getLangOpts())) {
6858 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6859 // half array type (unless the cl_khr_fp16 extension is enabled).
6860 if (Se.Context.getBaseElementType(R)->isHalfType()) {
6861 Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
6862 NewVD->setInvalidDecl();
6863 return false;
6864 }
6865 }
6866
6867 // OpenCL v1.2 s6.9.r:
6868 // The event type cannot be used with the __local, __constant and __global
6869 // address space qualifiers.
6870 if (R->isEventT()) {
6871 if (R.getAddressSpace() != LangAS::opencl_private) {
6872 Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
6873 NewVD->setInvalidDecl();
6874 return false;
6875 }
6876 }
6877
6878 if (R->isSamplerT()) {
6879 // OpenCL v1.2 s6.9.b p4:
6880 // The sampler type cannot be used with the __local and __global address
6881 // space qualifiers.
6882 if (R.getAddressSpace() == LangAS::opencl_local ||
6883 R.getAddressSpace() == LangAS::opencl_global) {
6884 Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
6885 NewVD->setInvalidDecl();
6886 }
6887
6888 // OpenCL v1.2 s6.12.14.1:
6889 // A global sampler must be declared with either the constant address
6890 // space qualifier or with the const qualifier.
6891 if (DC->isTranslationUnit() &&
6892 !(R.getAddressSpace() == LangAS::opencl_constant ||
6893 R.isConstQualified())) {
6894 Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
6895 NewVD->setInvalidDecl();
6896 }
6897 if (NewVD->isInvalidDecl())
6898 return false;
6899 }
6900
6901 return true;
6902}
6903
6904template <typename AttrTy>
6905static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
6906 const TypedefNameDecl *TND = TT->getDecl();
6907 if (const auto *Attribute = TND->getAttr<AttrTy>()) {
6908 AttrTy *Clone = Attribute->clone(S.Context);
6909 Clone->setInherited(true);
6910 D->addAttr(Clone);
6911 }
6912}
6913
6914NamedDecl *Sema::ActOnVariableDeclarator(
6915 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6916 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6917 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6918 QualType R = TInfo->getType();
6919 DeclarationName Name = GetNameForDeclarator(D).getName();
6920
6921 IdentifierInfo *II = Name.getAsIdentifierInfo();
6922
6923 if (D.isDecompositionDeclarator()) {
6924 // Take the name of the first declarator as our name for diagnostic
6925 // purposes.
6926 auto &Decomp = D.getDecompositionDeclarator();
6927 if (!Decomp.bindings().empty()) {
6928 II = Decomp.bindings()[0].Name;
6929 Name = II;
6930 }
6931 } else if (!II) {
6932 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6933 return nullptr;
6934 }
6935
6936
6937 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6938 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6939
6940 // dllimport globals without explicit storage class are treated as extern. We
6941 // have to change the storage class this early to get the right DeclContext.
6942 if (SC == SC_None && !DC->isRecord() &&
6943 hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6944 !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6945 SC = SC_Extern;
6946
6947 DeclContext *OriginalDC = DC;
6948 bool IsLocalExternDecl = SC == SC_Extern &&
6949 adjustContextForLocalExternDecl(DC);
6950
6951 if (SCSpec == DeclSpec::SCS_mutable) {
6952 // mutable can only appear on non-static class members, so it's always
6953 // an error here
6954 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6955 D.setInvalidType();
6956 SC = SC_None;
6957 }
6958
6959 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6960 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6961 D.getDeclSpec().getStorageClassSpecLoc())) {
6962 // In C++11, the 'register' storage class specifier is deprecated.
6963 // Suppress the warning in system macros, it's used in macros in some
6964 // popular C system headers, such as in glibc's htonl() macro.
6965 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6966 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6967 : diag::warn_deprecated_register)
6968 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6969 }
6970
6971 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6972
6973 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6974 // C99 6.9p2: The storage-class specifiers auto and register shall not
6975 // appear in the declaration specifiers in an external declaration.
6976 // Global Register+Asm is a GNU extension we support.
6977 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6978 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6979 D.setInvalidType();
6980 }
6981 }
6982
6983 // If this variable has a VLA type and an initializer, try to
6984 // fold to a constant-sized type. This is otherwise invalid.
6985 if (D.hasInitializer() && R->isVariableArrayType())
6986 tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
6987 /*DiagID=*/0);
6988
6989 bool IsMemberSpecialization = false;
6990 bool IsVariableTemplateSpecialization = false;
6991 bool IsPartialSpecialization = false;
6992 bool IsVariableTemplate = false;
6993 VarDecl *NewVD = nullptr;
6994 VarTemplateDecl *NewTemplate = nullptr;
6995 TemplateParameterList *TemplateParams = nullptr;
6996 if (!getLangOpts().CPlusPlus) {
6997 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
6998 II, R, TInfo, SC);
6999
7000 if (R->getContainedDeducedType())
7001 ParsingInitForAutoVars.insert(NewVD);
7002
7003 if (D.isInvalidType())
7004 NewVD->setInvalidDecl();
7005
7006 if (NewVD->getType().hasNonTrivialToPrimitiveDestructCUnion() &&
7007 NewVD->hasLocalStorage())
7008 checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7009 NTCUC_AutoVar, NTCUK_Destruct);
7010 } else {
7011 bool Invalid = false;
7012
7013 if (DC->isRecord() && !CurContext->isRecord()) {
7014 // This is an out-of-line definition of a static data member.
7015 switch (SC) {
7016 case SC_None:
7017 break;
7018 case SC_Static:
7019 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7020 diag::err_static_out_of_line)
7021 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7022 break;
7023 case SC_Auto:
7024 case SC_Register:
7025 case SC_Extern:
7026 // [dcl.stc] p2: The auto or register specifiers shall be applied only
7027 // to names of variables declared in a block or to function parameters.
7028 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7029 // of class members
7030
7031 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7032 diag::err_storage_class_for_static_member)
7033 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7034 break;
7035 case SC_PrivateExtern:
7036 llvm_unreachable("C storage class in c++!")__builtin_unreachable();
7037 }
7038 }
7039
7040 if (SC == SC_Static && CurContext->isRecord()) {
7041 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7042 // Walk up the enclosing DeclContexts to check for any that are
7043 // incompatible with static data members.
7044 const DeclContext *FunctionOrMethod = nullptr;
7045 const CXXRecordDecl *AnonStruct = nullptr;
7046 for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7047 if (Ctxt->isFunctionOrMethod()) {
7048 FunctionOrMethod = Ctxt;
7049 break;
7050 }
7051 const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7052 if (ParentDecl && !ParentDecl->getDeclName()) {
7053 AnonStruct = ParentDecl;
7054 break;
7055 }
7056 }
7057 if (FunctionOrMethod) {
7058 // C++ [class.static.data]p5: A local class shall not have static data
7059 // members.
7060 Diag(D.getIdentifierLoc(),
7061 diag::err_static_data_member_not_allowed_in_local_class)
7062 << Name << RD->getDeclName() << RD->getTagKind();
7063 } else if (AnonStruct) {
7064 // C++ [class.static.data]p4: Unnamed classes and classes contained
7065 // directly or indirectly within unnamed classes shall not contain
7066 // static data members.
7067 Diag(D.getIdentifierLoc(),
7068 diag::err_static_data_member_not_allowed_in_anon_struct)
7069 << Name << AnonStruct->getTagKind();
7070 Invalid = true;
7071 } else if (RD->isUnion()) {
7072 // C++98 [class.union]p1: If a union contains a static data member,
7073 // the program is ill-formed. C++11 drops this restriction.
7074 Diag(D.getIdentifierLoc(),
7075 getLangOpts().CPlusPlus11
7076 ? diag::warn_cxx98_compat_static_data_member_in_union
7077 : diag::ext_static_data_member_in_union) << Name;
7078 }
7079 }
7080 }
7081
7082 // Match up the template parameter lists with the scope specifier, then
7083 // determine whether we have a template or a template specialization.
7084 bool InvalidScope = false;
7085 TemplateParams = MatchTemplateParametersToScopeSpecifier(
7086 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
7087 D.getCXXScopeSpec(),
7088 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
7089 ? D.getName().TemplateId
7090 : nullptr,
7091 TemplateParamLists,
7092 /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7093 Invalid |= InvalidScope;
7094
7095 if (TemplateParams) {
7096 if (!TemplateParams->size() &&
7097 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
7098 // There is an extraneous 'template<>' for this variable. Complain
7099 // about it, but allow the declaration of the variable.
7100 Diag(TemplateParams->getTemplateLoc(),
7101 diag::err_template_variable_noparams)
7102 << II
7103 << SourceRange(TemplateParams->getTemplateLoc(),
7104 TemplateParams->getRAngleLoc());
7105 TemplateParams = nullptr;
7106 } else {
7107 // Check that we can declare a template here.
7108 if (CheckTemplateDeclScope(S, TemplateParams))
7109 return nullptr;
7110
7111 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
7112 // This is an explicit specialization or a partial specialization.
7113 IsVariableTemplateSpecialization = true;
7114 IsPartialSpecialization = TemplateParams->size() > 0;
7115 } else { // if (TemplateParams->size() > 0)
7116 // This is a template declaration.
7117 IsVariableTemplate = true;
7118
7119 // Only C++1y supports variable templates (N3651).
7120 Diag(D.getIdentifierLoc(),
7121 getLangOpts().CPlusPlus14
7122 ? diag::warn_cxx11_compat_variable_template
7123 : diag::ext_variable_template);
7124 }
7125 }
7126 } else {
7127 // Check that we can declare a member specialization here.
7128 if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7129 CheckTemplateDeclScope(S, TemplateParamLists.back()))
7130 return nullptr;
7131 assert((Invalid ||((void)0)
7132 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&((void)0)
7133 "should have a 'template<>' for this decl")((void)0);
7134 }
7135
7136 if (IsVariableTemplateSpecialization) {
7137 SourceLocation TemplateKWLoc =
7138 TemplateParamLists.size() > 0
7139 ? TemplateParamLists[0]->getTemplateLoc()
7140 : SourceLocation();
7141 DeclResult Res = ActOnVarTemplateSpecialization(
7142 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7143 IsPartialSpecialization);
7144 if (Res.isInvalid())
7145 return nullptr;
7146 NewVD = cast<VarDecl>(Res.get());
7147 AddToScope = false;
7148 } else if (D.isDecompositionDeclarator()) {
7149 NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7150 D.getIdentifierLoc(), R, TInfo, SC,
7151 Bindings);
7152 } else
7153 NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7154 D.getIdentifierLoc(), II, R, TInfo, SC);
7155
7156 // If this is supposed to be a variable template, create it as such.
7157 if (IsVariableTemplate) {
7158 NewTemplate =
7159 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7160 TemplateParams, NewVD);
7161 NewVD->setDescribedVarTemplate(NewTemplate);
7162 }
7163
7164 // If this decl has an auto type in need of deduction, make a note of the
7165 // Decl so we can diagnose uses of it in its own initializer.
7166 if (R->getContainedDeducedType())
7167 ParsingInitForAutoVars.insert(NewVD);
7168
7169 if (D.isInvalidType() || Invalid) {
7170 NewVD->setInvalidDecl();
7171 if (NewTemplate)
7172 NewTemplate->setInvalidDecl();
7173 }
7174
7175 SetNestedNameSpecifier(*this, NewVD, D);
7176
7177 // If we have any template parameter lists that don't directly belong to
7178 // the variable (matching the scope specifier), store them.
7179 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7180 if (TemplateParamLists.size() > VDTemplateParamLists)
7181 NewVD->setTemplateParameterListsInfo(
7182 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7183 }
7184
7185 if (D.getDeclSpec().isInlineSpecified()) {
7186 if (!getLangOpts().CPlusPlus) {
7187 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7188 << 0;
7189 } else if (CurContext->isFunctionOrMethod()) {
7190 // 'inline' is not allowed on block scope variable declaration.
7191 Diag(D.getDeclSpec().getInlineSpecLoc(),
7192 diag::err_inline_declaration_block_scope) << Name
7193 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7194 } else {
7195 Diag(D.getDeclSpec().getInlineSpecLoc(),
7196 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7197 : diag::ext_inline_variable);
7198 NewVD->setInlineSpecified();
7199 }
7200 }
7201
7202 // Set the lexical context. If the declarator has a C++ scope specifier, the
7203 // lexical context will be different from the semantic context.
7204 NewVD->setLexicalDeclContext(CurContext);
7205 if (NewTemplate)
7206 NewTemplate->setLexicalDeclContext(CurContext);
7207
7208 if (IsLocalExternDecl) {
7209 if (D.isDecompositionDeclarator())
7210 for (auto *B : Bindings)
7211 B->setLocalExternDecl();
7212 else
7213 NewVD->setLocalExternDecl();
7214 }
7215
7216 bool EmitTLSUnsupportedError = false;
7217 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
7218 // C++11 [dcl.stc]p4:
7219 // When thread_local is applied to a variable of block scope the
7220 // storage-class-specifier static is implied if it does not appear
7221 // explicitly.
7222 // Core issue: 'static' is not implied if the variable is declared
7223 // 'extern'.
7224 if (NewVD->hasLocalStorage() &&
7225 (SCSpec != DeclSpec::SCS_unspecified ||
7226 TSCS != DeclSpec::TSCS_thread_local ||
7227 !DC->isFunctionOrMethod()))
7228 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7229 diag::err_thread_non_global)
7230 << DeclSpec::getSpecifierName(TSCS);
7231 else if (!Context.getTargetInfo().isTLSSupported()) {
7232 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7233 getLangOpts().SYCLIsDevice) {
7234 // Postpone error emission until we've collected attributes required to
7235 // figure out whether it's a host or device variable and whether the
7236 // error should be ignored.
7237 EmitTLSUnsupportedError = true;
7238 // We still need to mark the variable as TLS so it shows up in AST with
7239 // proper storage class for other tools to use even if we're not going
7240 // to emit any code for it.
7241 NewVD->setTSCSpec(TSCS);
7242 } else
7243 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7244 diag::err_thread_unsupported);
7245 } else
7246 NewVD->setTSCSpec(TSCS);
7247 }
7248
7249 switch (D.getDeclSpec().getConstexprSpecifier()) {
7250 case ConstexprSpecKind::Unspecified:
7251 break;
7252
7253 case ConstexprSpecKind::Consteval:
7254 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7255 diag::err_constexpr_wrong_decl_kind)
7256 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7257 LLVM_FALLTHROUGH[[gnu::fallthrough]];
7258
7259 case ConstexprSpecKind::Constexpr:
7260 NewVD->setConstexpr(true);
7261 // C++1z [dcl.spec.constexpr]p1:
7262 // A static data member declared with the constexpr specifier is
7263 // implicitly an inline variable.
7264 if (NewVD->isStaticDataMember() &&
7265 (getLangOpts().CPlusPlus17 ||
7266 Context.getTargetInfo().getCXXABI().isMicrosoft()))
7267 NewVD->setImplicitlyInline();
7268 break;
7269
7270 case ConstexprSpecKind::Constinit:
7271 if (!NewVD->hasGlobalStorage())
7272 Diag(D.getDeclSpec().getConstexprSpecLoc(),
7273 diag::err_constinit_local_variable);
7274 else
7275 NewVD->addAttr(ConstInitAttr::Create(
7276 Context, D.getDeclSpec().getConstexprSpecLoc(),
7277 AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7278 break;
7279 }
7280
7281 // C99 6.7.4p3
7282 // An inline definition of a function with external linkage shall
7283 // not contain a definition of a modifiable object with static or
7284 // thread storage duration...
7285 // We only apply this when the function is required to be defined
7286 // elsewhere, i.e. when the function is not 'extern inline'. Note
7287 // that a local variable with thread storage duration still has to
7288 // be marked 'static'. Also note that it's possible to get these
7289 // semantics in C++ using __attribute__((gnu_inline)).
7290 if (SC == SC_Static && S->getFnParent() != nullptr &&
7291 !NewVD->getType().isConstQualified()) {
7292 FunctionDecl *CurFD = getCurFunctionDecl();
7293 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7294 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7295 diag::warn_static_local_in_extern_inline);
7296 MaybeSuggestAddingStaticToDecl(CurFD);
7297 }
7298 }
7299
7300 if (D.getDeclSpec().isModulePrivateSpecified()) {
7301 if (IsVariableTemplateSpecialization)
7302 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7303 << (IsPartialSpecialization ? 1 : 0)
7304 << FixItHint::CreateRemoval(
7305 D.getDeclSpec().getModulePrivateSpecLoc());
7306 else if (IsMemberSpecialization)
7307 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7308 << 2
7309 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
7310 else if (NewVD->hasLocalStorage())
7311 Diag(NewVD->getLocation(), diag::err_module_private_local)
7312 << 0 << NewVD
7313 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
7314 << FixItHint::CreateRemoval(
7315 D.getDeclSpec().getModulePrivateSpecLoc());
7316 else {
7317 NewVD->setModulePrivate();
7318 if (NewTemplate)
7319 NewTemplate->setModulePrivate();
7320 for (auto *B : Bindings)
7321 B->setModulePrivate();
7322 }
7323 }
7324
7325 if (getLangOpts().OpenCL) {
7326 deduceOpenCLAddressSpace(NewVD);
7327
7328 DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
7329 if (TSC != TSCS_unspecified) {
7330 bool IsCXX = getLangOpts().OpenCLCPlusPlus;
7331 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7332 diag::err_opencl_unknown_type_specifier)
7333 << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
7334 << DeclSpec::getSpecifierName(TSC) << 1;
7335 NewVD->setInvalidDecl();
7336 }
7337 }
7338
7339 // Handle attributes prior to checking for duplicates in MergeVarDecl
7340 ProcessDeclAttributes(S, NewVD, D);
7341
7342 // FIXME: This is probably the wrong location to be doing this and we should
7343 // probably be doing this for more attributes (especially for function
7344 // pointer attributes such as format, warn_unused_result, etc.). Ideally
7345 // the code to copy attributes would be generated by TableGen.
7346 if (R->isFunctionPointerType())
7347 if (const auto *TT = R->getAs<TypedefType>())
7348 copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7349
7350 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7351 getLangOpts().SYCLIsDevice) {
7352 if (EmitTLSUnsupportedError &&
7353 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7354 (getLangOpts().OpenMPIsDevice &&
7355 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7356 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7357 diag::err_thread_unsupported);
7358
7359 if (EmitTLSUnsupportedError &&
7360 (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7361 targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7362 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7363 // storage [duration]."
7364 if (SC == SC_None && S->getFnParent() != nullptr &&
7365 (NewVD->hasAttr<CUDASharedAttr>() ||
7366 NewVD->hasAttr<CUDAConstantAttr>())) {
7367 NewVD->setStorageClass(SC_Static);
7368 }
7369 }
7370
7371 // Ensure that dllimport globals without explicit storage class are treated as
7372 // extern. The storage class is set above using parsed attributes. Now we can
7373 // check the VarDecl itself.
7374 assert(!NewVD->hasAttr<DLLImportAttr>() ||((void)0)
7375 NewVD->getAttr<DLLImportAttr>()->isInherited() ||((void)0)
7376 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)((void)0);
7377
7378 // In auto-retain/release, infer strong retension for variables of
7379 // retainable type.
7380 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7381 NewVD->setInvalidDecl();
7382
7383 // Handle GNU asm-label extension (encoded as an attribute).
7384 if (Expr *E = (Expr*)D.getAsmLabel()) {
7385 // The parser guarantees this is a string.
7386 StringLiteral *SE = cast<StringLiteral>(E);
7387 StringRef Label = SE->getString();
7388 if (S->getFnParent() != nullptr) {
7389 switch (SC) {
7390 case SC_None:
7391 case SC_Auto:
7392 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7393 break;
7394 case SC_Register:
7395 // Local Named register
7396 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7397 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7398 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7399 break;
7400 case SC_Static:
7401 case SC_Extern:
7402 case SC_PrivateExtern:
7403 break;
7404 }
7405 } else if (SC == SC_Register) {
7406 // Global Named register
7407 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7408 const auto &TI = Context.getTargetInfo();
7409 bool HasSizeMismatch;
7410
7411 if (!TI.isValidGCCRegisterName(Label))
7412 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7413 else if (!TI.validateGlobalRegisterVariable(Label,
7414 Context.getTypeSize(R),
7415 HasSizeMismatch))
7416 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7417 else if (HasSizeMismatch)
7418 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7419 }
7420
7421 if (!R->isIntegralType(Context) && !R->isPointerType()) {
7422 Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7423 NewVD->setInvalidDecl(true);
7424 }
7425 }
7426
7427 NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7428 /*IsLiteralLabel=*/true,
7429 SE->getStrTokenLoc(0)));
7430 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7431 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7432 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7433 if (I != ExtnameUndeclaredIdentifiers.end()) {
7434 if (isDeclExternC(NewVD)) {
7435 NewVD->addAttr(I->second);
7436 ExtnameUndeclaredIdentifiers.erase(I);
7437 } else
7438 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7439 << /*Variable*/1 << NewVD;
7440 }
7441 }
7442
7443 // Find the shadowed declaration before filtering for scope.
7444 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7445 ? getShadowedDeclaration(NewVD, Previous)
7446 : nullptr;
7447
7448 // Don't consider existing declarations that are in a different
7449 // scope and are out-of-semantic-context declarations (if the new
7450 // declaration has linkage).
7451 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7452 D.getCXXScopeSpec().isNotEmpty() ||
7453 IsMemberSpecialization ||
7454 IsVariableTemplateSpecialization);
7455
7456 // Check whether the previous declaration is in the same block scope. This
7457 // affects whether we merge types with it, per C++11 [dcl.array]p3.
7458 if (getLangOpts().CPlusPlus &&
7459 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7460 NewVD->setPreviousDeclInSameBlockScope(
7461 Previous.isSingleResult() && !Previous.isShadowed() &&
7462 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7463
7464 if (!getLangOpts().CPlusPlus) {
7465 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7466 } else {
7467 // If this is an explicit specialization of a static data member, check it.
7468 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7469 CheckMemberSpecialization(NewVD, Previous))
7470 NewVD->setInvalidDecl();
7471
7472 // Merge the decl with the existing one if appropriate.
7473 if (!Previous.empty()) {
7474 if (Previous.isSingleResult() &&
7475 isa<FieldDecl>(Previous.getFoundDecl()) &&
7476 D.getCXXScopeSpec().isSet()) {
7477 // The user tried to define a non-static data member
7478 // out-of-line (C++ [dcl.meaning]p1).
7479 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7480 << D.getCXXScopeSpec().getRange();
7481 Previous.clear();
7482 NewVD->setInvalidDecl();
7483 }
7484 } else if (D.getCXXScopeSpec().isSet()) {
7485 // No previous declaration in the qualifying scope.
7486 Diag(D.getIdentifierLoc(), diag::err_no_member)
7487 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7488 << D.getCXXScopeSpec().getRange();
7489 NewVD->setInvalidDecl();
7490 }
7491
7492 if (!IsVariableTemplateSpecialization)
7493 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7494
7495 if (NewTemplate) {
7496 VarTemplateDecl *PrevVarTemplate =
7497 NewVD->getPreviousDecl()
7498 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
7499 : nullptr;
7500
7501 // Check the template parameter list of this declaration, possibly
7502 // merging in the template parameter list from the previous variable
7503 // template declaration.
7504 if (CheckTemplateParameterList(
7505 TemplateParams,
7506 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7507 : nullptr,
7508 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7509 DC->isDependentContext())
7510 ? TPC_ClassTemplateMember
7511 : TPC_VarTemplate))
7512 NewVD->setInvalidDecl();
7513
7514 // If we are providing an explicit specialization of a static variable
7515 // template, make a note of that.
7516 if (PrevVarTemplate &&
7517 PrevVarTemplate->getInstantiatedFromMemberTemplate())
7518 PrevVarTemplate->setMemberSpecialization();
7519 }
7520 }
7521
7522 // Diagnose shadowed variables iff this isn't a redeclaration.
7523 if (ShadowedDecl && !D.isRedeclaration())
7524 CheckShadow(NewVD, ShadowedDecl, Previous);
7525
7526 ProcessPragmaWeak(S, NewVD);
7527
7528 // If this is the first declaration of an extern C variable, update
7529 // the map of such variables.
7530 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7531 isIncompleteDeclExternC(*this, NewVD))
7532 RegisterLocallyScopedExternCDecl(NewVD, S);
7533
7534 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7535 MangleNumberingContext *MCtx;
7536 Decl *ManglingContextDecl;
7537 std::tie(MCtx, ManglingContextDecl) =
7538 getCurrentMangleNumberContext(NewVD->getDeclContext());
7539 if (MCtx) {
7540 Context.setManglingNumber(
7541 NewVD, MCtx->getManglingNumber(
7542 NewVD, getMSManglingNumber(getLangOpts(), S)));
7543 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7544 }
7545 }
7546
7547 // Special handling of variable named 'main'.
7548 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7549 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
7550 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7551
7552 // C++ [basic.start.main]p3
7553 // A program that declares a variable main at global scope is ill-formed.
7554 if (getLangOpts().CPlusPlus)
7555 Diag(D.getBeginLoc(), diag::err_main_global_variable);
7556
7557 // In C, and external-linkage variable named main results in undefined
7558 // behavior.
7559 else if (NewVD->hasExternalFormalLinkage())
7560 Diag(D.getBeginLoc(), diag::warn_main_redefined);
7561 }
7562
7563 if (D.isRedeclaration() && !Previous.empty()) {
7564 NamedDecl *Prev = Previous.getRepresentativeDecl();
7565 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7566 D.isFunctionDefinition());
7567 }
7568
7569 if (NewTemplate) {
7570 if (NewVD->isInvalidDecl())
7571 NewTemplate->setInvalidDecl();
7572 ActOnDocumentableDecl(NewTemplate);
7573 return NewTemplate;
7574 }
7575
7576 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7577 CompleteMemberSpecialization(NewVD, Previous);
7578
7579 return NewVD;
7580}
7581
7582/// Enum describing the %select options in diag::warn_decl_shadow.
7583enum ShadowedDeclKind {
7584 SDK_Local,
7585 SDK_Global,
7586 SDK_StaticMember,
7587 SDK_Field,
7588 SDK_Typedef,
7589 SDK_Using,
7590 SDK_StructuredBinding
7591};
7592
7593/// Determine what kind of declaration we're shadowing.
7594static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
7595 const DeclContext *OldDC) {
7596 if (isa<TypeAliasDecl>(ShadowedDecl))
7597 return SDK_Using;
7598 else if (isa<TypedefDecl>(ShadowedDecl))
7599 return SDK_Typedef;
7600 else if (isa<BindingDecl>(ShadowedDecl))
7601 return SDK_StructuredBinding;
7602 else if (isa<RecordDecl>(OldDC))
7603 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7604
7605 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7606}
7607
7608/// Return the location of the capture if the given lambda captures the given
7609/// variable \p VD, or an invalid source location otherwise.
7610static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
7611 const VarDecl *VD) {
7612 for (const Capture &Capture : LSI->Captures) {
7613 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7614 return Capture.getLocation();
7615 }
7616 return SourceLocation();
7617}
7618
7619static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
7620 const LookupResult &R) {
7621 // Only diagnose if we're shadowing an unambiguous field or variable.
7622 if (R.getResultKind() != LookupResult::Found)
7623 return false;
7624
7625 // Return false if warning is ignored.
7626 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7627}
7628
7629/// Return the declaration shadowed by the given variable \p D, or null
7630/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7631NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7632 const LookupResult &R) {
7633 if (!shouldWarnIfShadowedDecl(Diags, R))
7634 return nullptr;
7635
7636 // Don't diagnose declarations at file scope.
7637 if (D->hasGlobalStorage())
7638 return nullptr;
7639
7640 NamedDecl *ShadowedDecl = R.getFoundDecl();
7641 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7642 : nullptr;
7643}
7644
7645/// Return the declaration shadowed by the given typedef \p D, or null
7646/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7647NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7648 const LookupResult &R) {
7649 // Don't warn if typedef declaration is part of a class
7650 if (D->getDeclContext()->isRecord())
7651 return nullptr;
7652
7653 if (!shouldWarnIfShadowedDecl(Diags, R))
7654 return nullptr;
7655
7656 NamedDecl *ShadowedDecl = R.getFoundDecl();
7657 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7658}
7659
7660/// Return the declaration shadowed by the given variable \p D, or null
7661/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7662NamedDecl *Sema::getShadowedDeclaration(const BindingDecl *D,
7663 const LookupResult &R) {
7664 if (!shouldWarnIfShadowedDecl(Diags, R))
7665 return nullptr;
7666
7667 NamedDecl *ShadowedDecl = R.getFoundDecl();
7668 return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7669 : nullptr;
7670}
7671
7672/// Diagnose variable or built-in function shadowing. Implements
7673/// -Wshadow.
7674///
7675/// This method is called whenever a VarDecl is added to a "useful"
7676/// scope.
7677///
7678/// \param ShadowedDecl the declaration that is shadowed by the given variable
7679/// \param R the lookup of the name
7680///
7681void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7682 const LookupResult &R) {
7683 DeclContext *NewDC = D->getDeclContext();
7684
7685 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7686 // Fields are not shadowed by variables in C++ static methods.
7687 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7688 if (MD->isStatic())
7689 return;
7690
7691 // Fields shadowed by constructor parameters are a special case. Usually
7692 // the constructor initializes the field with the parameter.
7693 if (isa<CXXConstructorDecl>(NewDC))
7694 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7695 // Remember that this was shadowed so we can either warn about its
7696 // modification or its existence depending on warning settings.
7697 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7698 return;
7699 }
7700 }
7701
7702 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7703 if (shadowedVar->isExternC()) {
7704 // For shadowing external vars, make sure that we point to the global
7705 // declaration, not a locally scoped extern declaration.
7706 for (auto I : shadowedVar->redecls())
7707 if (I->isFileVarDecl()) {
7708 ShadowedDecl = I;
7709 break;
7710 }
7711 }
7712
7713 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7714
7715 unsigned WarningDiag = diag::warn_decl_shadow;
7716 SourceLocation CaptureLoc;
7717 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7718 isa<CXXMethodDecl>(NewDC)) {
7719 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7720 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7721 if (RD->getLambdaCaptureDefault() == LCD_None) {
7722 // Try to avoid warnings for lambdas with an explicit capture list.
7723 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7724 // Warn only when the lambda captures the shadowed decl explicitly.
7725 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7726 if (CaptureLoc.isInvalid())
7727 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7728 } else {
7729 // Remember that this was shadowed so we can avoid the warning if the
7730 // shadowed decl isn't captured and the warning settings allow it.
7731 cast<LambdaScopeInfo>(getCurFunction())
7732 ->ShadowingDecls.push_back(
7733 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7734 return;
7735 }
7736 }
7737
7738 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7739 // A variable can't shadow a local variable in an enclosing scope, if
7740 // they are separated by a non-capturing declaration context.
7741 for (DeclContext *ParentDC = NewDC;
7742 ParentDC && !ParentDC->Equals(OldDC);
7743 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7744 // Only block literals, captured statements, and lambda expressions
7745 // can capture; other scopes don't.
7746 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7747 !isLambdaCallOperator(ParentDC)) {
7748 return;
7749 }
7750 }
7751 }
7752 }
7753 }
7754
7755 // Only warn about certain kinds of shadowing for class members.
7756 if (NewDC && NewDC->isRecord()) {
7757 // In particular, don't warn about shadowing non-class members.
7758 if (!OldDC->isRecord())
7759 return;
7760
7761 // TODO: should we warn about static data members shadowing
7762 // static data members from base classes?
7763
7764 // TODO: don't diagnose for inaccessible shadowed members.
7765 // This is hard to do perfectly because we might friend the
7766 // shadowing context, but that's just a false negative.
7767 }
7768
7769
7770 DeclarationName Name = R.getLookupName();
7771
7772 // Emit warning and note.
7773 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7774 return;
7775 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7776 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7777 if (!CaptureLoc.isInvalid())
7778 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7779 << Name << /*explicitly*/ 1;
7780 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7781}
7782
7783/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7784/// when these variables are captured by the lambda.
7785void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7786 for (const auto &Shadow : LSI->ShadowingDecls) {
7787 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7788 // Try to avoid the warning when the shadowed decl isn't captured.
7789 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7790 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7791 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7792 ? diag::warn_decl_shadow_uncaptured_local
7793 : diag::warn_decl_shadow)
7794 << Shadow.VD->getDeclName()
7795 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7796 if (!CaptureLoc.isInvalid())
7797 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7798 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7799 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7800 }
7801}
7802
7803/// Check -Wshadow without the advantage of a previous lookup.
7804void Sema::CheckShadow(Scope *S, VarDecl *D) {
7805 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7806 return;
7807
7808 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7809 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7810 LookupName(R, S);
7811 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7812 CheckShadow(D, ShadowedDecl, R);
7813}
7814
7815/// Check if 'E', which is an expression that is about to be modified, refers
7816/// to a constructor parameter that shadows a field.
7817void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7818 // Quickly ignore expressions that can't be shadowing ctor parameters.
7819 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7820 return;
7821 E = E->IgnoreParenImpCasts();
7822 auto *DRE = dyn_cast<DeclRefExpr>(E);
7823 if (!DRE)
7824 return;
7825 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7826 auto I = ShadowingDecls.find(D);
7827 if (I == ShadowingDecls.end())
7828 return;
7829 const NamedDecl *ShadowedDecl = I->second;
7830 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7831 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7832 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7833 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7834
7835 // Avoid issuing multiple warnings about the same decl.
7836 ShadowingDecls.erase(I);
7837}
7838
7839/// Check for conflict between this global or extern "C" declaration and
7840/// previous global or extern "C" declarations. This is only used in C++.
7841template<typename T>
7842static bool checkGlobalOrExternCConflict(
7843 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7844 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")((void)0);
7845 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7846
7847 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7848 // The common case: this global doesn't conflict with any extern "C"
7849 // declaration.
7850 return false;
7851 }
7852
7853 if (Prev) {
7854 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7855 // Both the old and new declarations have C language linkage. This is a
7856 // redeclaration.
7857 Previous.clear();
7858 Previous.addDecl(Prev);
7859 return true;
7860 }
7861
7862 // This is a global, non-extern "C" declaration, and there is a previous
7863 // non-global extern "C" declaration. Diagnose if this is a variable
7864 // declaration.
7865 if (!isa<VarDecl>(ND))
7866 return false;
7867 } else {
7868 // The declaration is extern "C". Check for any declaration in the
7869 // translation unit which might conflict.
7870 if (IsGlobal) {
7871 // We have already performed the lookup into the translation unit.
7872 IsGlobal = false;
7873 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7874 I != E; ++I) {
7875 if (isa<VarDecl>(*I)) {
7876 Prev = *I;
7877 break;
7878 }
7879 }
7880 } else {
7881 DeclContext::lookup_result R =
7882 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7883 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7884 I != E; ++I) {
7885 if (isa<VarDecl>(*I)) {
7886 Prev = *I;
7887 break;
7888 }
7889 // FIXME: If we have any other entity with this name in global scope,
7890 // the declaration is ill-formed, but that is a defect: it breaks the
7891 // 'stat' hack, for instance. Only variables can have mangled name
7892 // clashes with extern "C" declarations, so only they deserve a
7893 // diagnostic.
7894 }
7895 }
7896
7897 if (!Prev)
7898 return false;
7899 }
7900
7901 // Use the first declaration's location to ensure we point at something which
7902 // is lexically inside an extern "C" linkage-spec.
7903 assert(Prev && "should have found a previous declaration to diagnose")((void)0);
7904 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7905 Prev = FD->getFirstDecl();
7906 else
7907 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7908
7909 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7910 << IsGlobal << ND;
7911 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7912 << IsGlobal;
7913 return false;
7914}
7915
7916/// Apply special rules for handling extern "C" declarations. Returns \c true
7917/// if we have found that this is a redeclaration of some prior entity.
7918///
7919/// Per C++ [dcl.link]p6:
7920/// Two declarations [for a function or variable] with C language linkage
7921/// with the same name that appear in different scopes refer to the same
7922/// [entity]. An entity with C language linkage shall not be declared with
7923/// the same name as an entity in global scope.
7924template<typename T>
7925static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7926 LookupResult &Previous) {
7927 if (!S.getLangOpts().CPlusPlus) {
7928 // In C, when declaring a global variable, look for a corresponding 'extern'
7929 // variable declared in function scope. We don't need this in C++, because
7930 // we find local extern decls in the surrounding file-scope DeclContext.
7931 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7932 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7933 Previous.clear();
7934 Previous.addDecl(Prev);
7935 return true;
7936 }
7937 }
7938 return false;
7939 }
7940
7941 // A declaration in the translation unit can conflict with an extern "C"
7942 // declaration.
7943 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7944 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7945
7946 // An extern "C" declaration can conflict with a declaration in the
7947 // translation unit or can be a redeclaration of an extern "C" declaration
7948 // in another scope.
7949 if (isIncompleteDeclExternC(S,ND))
7950 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7951
7952 // Neither global nor extern "C": nothing to do.
7953 return false;
7954}
7955
7956void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7957 // If the decl is already known invalid, don't check it.
7958 if (NewVD->isInvalidDecl())
7959 return;
7960
7961 QualType T = NewVD->getType();
7962
7963 // Defer checking an 'auto' type until its initializer is attached.
7964 if (T->isUndeducedType())
7965 return;
7966
7967 if (NewVD->hasAttrs())
7968 CheckAlignasUnderalignment(NewVD);
7969
7970 if (T->isObjCObjectType()) {
7971 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7972 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7973 T = Context.getObjCObjectPointerType(T);
7974 NewVD->setType(T);
7975 }
7976
7977 // Emit an error if an address space was applied to decl with local storage.
7978 // This includes arrays of objects with address space qualifiers, but not
7979 // automatic variables that point to other address spaces.
7980 // ISO/IEC TR 18037 S5.1.2
7981 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7982 T.getAddressSpace() != LangAS::Default) {
7983 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7984 NewVD->setInvalidDecl();
7985 return;
7986 }
7987
7988 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7989 // scope.
7990 if (getLangOpts().OpenCLVersion == 120 &&
7991 !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
7992 getLangOpts()) &&
7993 NewVD->isStaticLocal()) {
7994 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7995 NewVD->setInvalidDecl();
7996 return;
7997 }
7998
7999 if (getLangOpts().OpenCL) {
8000 if (!diagnoseOpenCLTypes(*this, NewVD))
8001 return;
8002
8003 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8004 if (NewVD->hasAttr<BlocksAttr>()) {
8005 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8006 return;
8007 }
8008
8009 if (T->isBlockPointerType()) {
8010 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8011 // can't use 'extern' storage class.
8012 if (!T.isConstQualified()) {
8013 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8014 << 0 /*const*/;
8015 NewVD->setInvalidDecl();
8016 return;
8017 }
8018 if (NewVD->hasExternalStorage()) {
8019 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8020 NewVD->setInvalidDecl();
8021 return;
8022 }
8023 }
8024
8025 // FIXME: Adding local AS in C++ for OpenCL might make sense.
8026 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8027 NewVD->hasExternalStorage()) {
8028 if (!T->isSamplerT() && !T->isDependentType() &&
8029 !(T.getAddressSpace() == LangAS::opencl_constant ||
8030 (T.getAddressSpace() == LangAS::opencl_global &&
8031 getOpenCLOptions().areProgramScopeVariablesSupported(
8032 getLangOpts())))) {
8033 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8034 if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8035 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8036 << Scope << "global or constant";
8037 else
8038 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8039 << Scope << "constant";
8040 NewVD->setInvalidDecl();
8041 return;
8042 }
8043 } else {
8044 if (T.getAddressSpace() == LangAS::opencl_global) {
8045 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8046 << 1 /*is any function*/ << "global";
8047 NewVD->setInvalidDecl();
8048 return;
8049 }
8050 if (T.getAddressSpace() == LangAS::opencl_constant ||
8051 T.getAddressSpace() == LangAS::opencl_local) {
8052 FunctionDecl *FD = getCurFunctionDecl();
8053 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8054 // in functions.
8055 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8056 if (T.getAddressSpace() == LangAS::opencl_constant)
8057 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8058 << 0 /*non-kernel only*/ << "constant";
8059 else
8060 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8061 << 0 /*non-kernel only*/ << "local";
8062 NewVD->setInvalidDecl();
8063 return;
8064 }
8065 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8066 // in the outermost scope of a kernel function.
8067 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8068 if (!getCurScope()->isFunctionScope()) {
8069 if (T.getAddressSpace() == LangAS::opencl_constant)
8070 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8071 << "constant";
8072 else
8073 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8074 << "local";
8075 NewVD->setInvalidDecl();
8076 return;
8077 }
8078 }
8079 } else if (T.getAddressSpace() != LangAS::opencl_private &&
8080 // If we are parsing a template we didn't deduce an addr
8081 // space yet.
8082 T.getAddressSpace() != LangAS::Default) {
8083 // Do not allow other address spaces on automatic variable.
8084 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8085 NewVD->setInvalidDecl();
8086 return;
8087 }
8088 }
8089 }
8090
8091 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8092 && !NewVD->hasAttr<BlocksAttr>()) {
8093 if (getLangOpts().getGC() != LangOptions::NonGC)
8094 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8095 else {
8096 assert(!getLangOpts().ObjCAutoRefCount)((void)0);
8097 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8098 }
8099 }
8100
8101 bool isVM = T->isVariablyModifiedType();
8102 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8103 NewVD->hasAttr<BlocksAttr>())
8104 setFunctionHasBranchProtectedScope();
8105
8106 if ((isVM && NewVD->hasLinkage()) ||
8107 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8108 bool SizeIsNegative;
8109 llvm::APSInt Oversized;
8110 TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
8111 NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8112 QualType FixedT;
8113 if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8114 FixedT = FixedTInfo->getType();
8115 else if (FixedTInfo) {
8116 // Type and type-as-written are canonically different. We need to fix up
8117 // both types separately.
8118 FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8119 Oversized);
8120 }
8121 if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8122 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8123 // FIXME: This won't give the correct result for
8124 // int a[10][n];
8125 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8126
8127 if (NewVD->isFileVarDecl())
8128 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8129 << SizeRange;
8130 else if (NewVD->isStaticLocal())
8131 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8132 << SizeRange;
8133 else
8134 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8135 << SizeRange;
8136 NewVD->setInvalidDecl();
8137 return;
8138 }
8139
8140 if (!FixedTInfo) {
8141 if (NewVD->isFileVarDecl())
8142 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8143 else
8144 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8145 NewVD->setInvalidDecl();
8146 return;
8147 }
8148
8149 Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8150 NewVD->setType(FixedT);
8151 NewVD->setTypeSourceInfo(FixedTInfo);
8152 }
8153
8154 if (T->isVoidType()) {
8155 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8156 // of objects and functions.
8157 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8158 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8159 << T;
8160 NewVD->setInvalidDecl();
8161 return;
8162 }
8163 }
8164
8165 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8166 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8167 NewVD->setInvalidDecl();
8168 return;
8169 }
8170
8171 if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8172 Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8173 NewVD->setInvalidDecl();
8174 return;
8175 }
8176
8177 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8178 Diag(NewVD->getLocation(), diag::err_block_on_vm);
8179 NewVD->setInvalidDecl();
8180 return;
8181 }
8182
8183 if (NewVD->isConstexpr() && !T->isDependentType() &&
8184 RequireLiteralType(NewVD->getLocation(), T,
8185 diag::err_constexpr_var_non_literal)) {
8186 NewVD->setInvalidDecl();
8187 return;
8188 }
8189
8190 // PPC MMA non-pointer types are not allowed as non-local variable types.
8191 if (Context.getTargetInfo().getTriple().isPPC64() &&
8192 !NewVD->isLocalVarDecl() &&
8193 CheckPPCMMAType(T, NewVD->getLocation())) {
8194 NewVD->setInvalidDecl();
8195 return;
8196 }
8197}
8198
8199/// Perform semantic checking on a newly-created variable
8200/// declaration.
8201///
8202/// This routine performs all of the type-checking required for a
8203/// variable declaration once it has been built. It is used both to
8204/// check variables after they have been parsed and their declarators
8205/// have been translated into a declaration, and to check variables
8206/// that have been instantiated from a template.
8207///
8208/// Sets NewVD->isInvalidDecl() if an error was encountered.
8209///
8210/// Returns true if the variable declaration is a redeclaration.
8211bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
8212 CheckVariableDeclarationType(NewVD);
8213
8214 // If the decl is already known invalid, don't check it.
8215 if (NewVD->isInvalidDecl())
8216 return false;
8217
8218 // If we did not find anything by this name, look for a non-visible
8219 // extern "C" declaration with the same name.
8220 if (Previous.empty() &&
8221 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
8222 Previous.setShadowed();
8223
8224 if (!Previous.empty()) {
8225 MergeVarDecl(NewVD, Previous);
8226 return true;
8227 }
8228 return false;
8229}
8230
8231/// AddOverriddenMethods - See if a method overrides any in the base classes,
8232/// and if so, check that it's a valid override and remember it.
8233bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
8234 llvm::SmallPtrSet<const CXXMethodDecl*, 4> Overridden;
8235
8236 // Look for methods in base classes that this method might override.
8237 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8238 /*DetectVirtual=*/false);
8239 auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8240 CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8241 DeclarationName Name = MD->getDeclName();
8242
8243 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8244 // We really want to find the base class destructor here.
8245 QualType T = Context.getTypeDeclType(BaseRecord);
8246 CanQualType CT = Context.getCanonicalType(T);
8247 Name = Context.DeclarationNames.getCXXDestructorName(CT);
8248 }
8249
8250 for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8251 CXXMethodDecl *BaseMD =
8252 dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8253 if (!BaseMD || !BaseMD->isVirtual() ||
8254 IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8255 /*ConsiderCudaAttrs=*/true,
8256 // C++2a [class.virtual]p2 does not consider requires
8257 // clauses when overriding.
8258 /*ConsiderRequiresClauses=*/false))
8259 continue;
8260
8261 if (Overridden.insert(BaseMD).second) {
8262 MD->addOverriddenMethod(BaseMD);
8263 CheckOverridingFunctionReturnType(MD, BaseMD);
8264 CheckOverridingFunctionAttributes(MD, BaseMD);
8265 CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8266 CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8267 }
8268
8269 // A method can only override one function from each base class. We
8270 // don't track indirectly overridden methods from bases of bases.
8271 return true;
8272 }
8273
8274 return false;
8275 };
8276
8277 DC->lookupInBases(VisitBase, Paths);
8278 return !Overridden.empty();
8279}
8280
8281namespace {
8282 // Struct for holding all of the extra arguments needed by
8283 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8284 struct ActOnFDArgs {
8285 Scope *S;
8286 Declarator &D;
8287 MultiTemplateParamsArg TemplateParamLists;
8288 bool AddToScope;
8289 };
8290} // end anonymous namespace
8291
8292namespace {
8293
8294// Callback to only accept typo corrections that have a non-zero edit distance.
8295// Also only accept corrections that have the same parent decl.
8296class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8297 public:
8298 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8299 CXXRecordDecl *Parent)
8300 : Context(Context), OriginalFD(TypoFD),
8301 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8302
8303 bool ValidateCandidate(const TypoCorrection &candidate) override {
8304 if (candidate.getEditDistance() == 0)
8305 return false;
8306
8307 SmallVector<unsigned, 1> MismatchedParams;
8308 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8309 CDeclEnd = candidate.end();
8310 CDecl != CDeclEnd; ++CDecl) {
8311 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8312
8313 if (FD && !FD->hasBody() &&
8314 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8315 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8316 CXXRecordDecl *Parent = MD->getParent();
8317 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8318 return true;
8319 } else if (!ExpectedParent) {
8320 return true;
8321 }
8322 }
8323 }
8324
8325 return false;
8326 }
8327
8328 std::unique_ptr<CorrectionCandidateCallback> clone() override {
8329 return std::make_unique<DifferentNameValidatorCCC>(*this);
8330 }
8331
8332 private:
8333 ASTContext &Context;
8334 FunctionDecl *OriginalFD;
8335 CXXRecordDecl *ExpectedParent;
8336};
8337
8338} // end anonymous namespace
8339
8340void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
8341 TypoCorrectedFunctionDefinitions.insert(F);
8342}
8343
8344/// Generate diagnostics for an invalid function redeclaration.
8345///
8346/// This routine handles generating the diagnostic messages for an invalid
8347/// function redeclaration, including finding possible similar declarations
8348/// or performing typo correction if there are no previous declarations with
8349/// the same name.
8350///
8351/// Returns a NamedDecl iff typo correction was performed and substituting in
8352/// the new declaration name does not cause new errors.
8353static NamedDecl *DiagnoseInvalidRedeclaration(
8354 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8355 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8356 DeclarationName Name = NewFD->getDeclName();
8357 DeclContext *NewDC = NewFD->getDeclContext();
8358 SmallVector<unsigned, 1> MismatchedParams;
8359 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
8360 TypoCorrection Correction;
8361 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8362 unsigned DiagMsg =
8363 IsLocalFriend ? diag::err_no_matching_local_friend :
8364 NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8365 diag::err_member_decl_does_not_match;
8366 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8367 IsLocalFriend ? Sema::LookupLocalFriendName
8368 : Sema::LookupOrdinaryName,
8369 Sema::ForVisibleRedeclaration);
8370
8371 NewFD->setInvalidDecl();
8372 if (IsLocalFriend)
8373 SemaRef.LookupName(Prev, S);
8374 else
8375 SemaRef.LookupQualifiedName(Prev, NewDC);
8376 assert(!Prev.isAmbiguous() &&((void)0)
8377 "Cannot have an ambiguity in previous-declaration lookup")((void)0);
8378 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8379 DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8380 MD ? MD->getParent() : nullptr);
8381 if (!Prev.empty()) {
8382 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8383 Func != FuncEnd; ++Func) {
8384 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8385 if (FD &&
8386 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8387 // Add 1 to the index so that 0 can mean the mismatch didn't
8388 // involve a parameter
8389 unsigned ParamNum =
8390 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8391 NearMatches.push_back(std::make_pair(FD, ParamNum));
8392 }
8393 }
8394 // If the qualified name lookup yielded nothing, try typo correction
8395 } else if ((Correction = SemaRef.CorrectTypo(
8396 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8397 &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8398 IsLocalFriend ? nullptr : NewDC))) {
8399 // Set up everything for the call to ActOnFunctionDeclarator
8400 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8401 ExtraArgs.D.getIdentifierLoc());
8402 Previous.clear();
8403 Previous.setLookupName(Correction.getCorrection());
8404 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8405 CDeclEnd = Correction.end();
8406 CDecl != CDeclEnd; ++CDecl) {
8407 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8408 if (FD && !FD->hasBody() &&
8409 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8410 Previous.addDecl(FD);
8411 }
8412 }
8413 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8414
8415 NamedDecl *Result;
8416 // Retry building the function declaration with the new previous
8417 // declarations, and with errors suppressed.
8418 {
8419 // Trap errors.
8420 Sema::SFINAETrap Trap(SemaRef);
8421
8422 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8423 // pieces need to verify the typo-corrected C++ declaration and hopefully
8424 // eliminate the need for the parameter pack ExtraArgs.
8425 Result = SemaRef.ActOnFunctionDeclarator(
8426 ExtraArgs.S, ExtraArgs.D,
8427 Correction.getCorrectionDecl()->getDeclContext(),
8428 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8429 ExtraArgs.AddToScope);
8430
8431 if (Trap.hasErrorOccurred())
8432 Result = nullptr;
8433 }
8434
8435 if (Result) {
8436 // Determine which correction we picked.
8437 Decl *Canonical = Result->getCanonicalDecl();
8438 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8439 I != E; ++I)
8440 if ((*I)->getCanonicalDecl() == Canonical)
8441 Correction.setCorrectionDecl(*I);
8442
8443 // Let Sema know about the correction.
8444 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8445 SemaRef.diagnoseTypo(
8446 Correction,
8447 SemaRef.PDiag(IsLocalFriend
8448 ? diag::err_no_matching_local_friend_suggest
8449 : diag::err_member_decl_does_not_match_suggest)
8450 << Name << NewDC << IsDefinition);
8451 return Result;
8452 }
8453
8454 // Pretend the typo correction never occurred
8455 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8456 ExtraArgs.D.getIdentifierLoc());
8457 ExtraArgs.D.setRedeclaration(wasRedeclaration);
8458 Previous.clear();
8459 Previous.setLookupName(Name);
8460 }
8461
8462 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8463 << Name << NewDC << IsDefinition << NewFD->getLocation();
8464
8465 bool NewFDisConst = false;
8466 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8467 NewFDisConst = NewMD->isConst();
8468
8469 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8470 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8471 NearMatch != NearMatchEnd; ++NearMatch) {
8472 FunctionDecl *FD = NearMatch->first;
8473 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8474 bool FDisConst = MD && MD->isConst();
8475 bool IsMember = MD || !IsLocalFriend;
8476
8477 // FIXME: These notes are poorly worded for the local friend case.
8478 if (unsigned Idx = NearMatch->second) {
8479 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8480 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8481 if (Loc.isInvalid()) Loc = FD->getLocation();
8482 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8483 : diag::note_local_decl_close_param_match)
8484 << Idx << FDParam->getType()
8485 << NewFD->getParamDecl(Idx - 1)->getType();
8486 } else if (FDisConst != NewFDisConst) {
8487 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8488 << NewFDisConst << FD->getSourceRange().getEnd();
8489 } else
8490 SemaRef.Diag(FD->getLocation(),
8491 IsMember ? diag::note_member_def_close_match
8492 : diag::note_local_decl_close_match);
8493 }
8494 return nullptr;
8495}
8496
8497static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
8498 switch (D.getDeclSpec().getStorageClassSpec()) {
8499 default: llvm_unreachable("Unknown storage class!")__builtin_unreachable();
8500 case DeclSpec::SCS_auto:
8501 case DeclSpec::SCS_register:
8502 case DeclSpec::SCS_mutable:
8503 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8504 diag::err_typecheck_sclass_func);
8505 D.getMutableDeclSpec().ClearStorageClassSpecs();
8506 D.setInvalidType();
8507 break;
8508 case DeclSpec::SCS_unspecified: break;
8509 case DeclSpec::SCS_extern:
8510 if (D.getDeclSpec().isExternInLinkageSpec())
8511 return SC_None;
8512 return SC_Extern;
8513 case DeclSpec::SCS_static: {
8514 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8515 // C99 6.7.1p5:
8516 // The declaration of an identifier for a function that has
8517 // block scope shall have no explicit storage-class specifier
8518 // other than extern
8519 // See also (C++ [dcl.stc]p4).
8520 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8521 diag::err_static_block_func);
8522 break;
8523 } else
8524 return SC_Static;
8525 }
8526 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
8527 }
8528
8529 // No explicit storage class has already been returned
8530 return SC_None;
8531}
8532
8533static FunctionDecl *CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
8534 DeclContext *DC, QualType &R,
8535 TypeSourceInfo *TInfo,
8536 StorageClass SC,
8537 bool &IsVirtualOkay) {
8538 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8539 DeclarationName Name = NameInfo.getName();
8540
8541 FunctionDecl *NewFD = nullptr;
8542 bool isInline = D.getDeclSpec().isInlineSpecified();
8543
8544 if (!SemaRef.getLangOpts().CPlusPlus) {
8545 // Determine whether the function was written with a
8546 // prototype. This true when:
8547 // - there is a prototype in the declarator, or
8548 // - the type R of the function is some kind of typedef or other non-
8549 // attributed reference to a type name (which eventually refers to a
8550 // function type).
8551 bool HasPrototype =
8552 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
8553 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
8554
8555 NewFD = FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8556 R, TInfo, SC, isInline, HasPrototype,
8557 ConstexprSpecKind::Unspecified,
8558 /*TrailingRequiresClause=*/nullptr);
8559 if (D.isInvalidType())
8560 NewFD->setInvalidDecl();
8561
8562 return NewFD;
8563 }
8564
8565 ExplicitSpecifier ExplicitSpecifier = D.getDeclSpec().getExplicitSpecifier();
8566
8567 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8568 if (ConstexprKind == ConstexprSpecKind::Constinit) {
8569 SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8570 diag::err_constexpr_wrong_decl_kind)
8571 << static_cast<int>(ConstexprKind);
8572 ConstexprKind = ConstexprSpecKind::Unspecified;
8573 D.getMutableDeclSpec().ClearConstexprSpec();
8574 }
8575 Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8576
8577 // Check that the return type is not an abstract class type.
8578 // For record types, this is done by the AbstractClassUsageDiagnoser once
8579 // the class has been completely parsed.
8580 if (!DC->isRecord() &&
8581 SemaRef.RequireNonAbstractType(
8582 D.getIdentifierLoc(), R->castAs<FunctionType>()->getReturnType(),
8583 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8584 D.setInvalidType();
8585
8586 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8587 // This is a C++ constructor declaration.
8588 assert(DC->isRecord() &&((void)0)
8589 "Constructors can only be declared in a member context")((void)0);
8590
8591 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8592 return CXXConstructorDecl::Create(
8593 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8594 TInfo, ExplicitSpecifier, isInline,
8595 /*isImplicitlyDeclared=*/false, ConstexprKind, InheritedConstructor(),
8596 TrailingRequiresClause);
8597
8598 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8599 // This is a C++ destructor declaration.
8600 if (DC->isRecord()) {
8601 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8602 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8603 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
8604 SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8605 isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8606 TrailingRequiresClause);
8607
8608 // If the destructor needs an implicit exception specification, set it
8609 // now. FIXME: It'd be nice to be able to create the right type to start
8610 // with, but the type needs to reference the destructor declaration.
8611 if (SemaRef.getLangOpts().CPlusPlus11)
8612 SemaRef.AdjustDestructorExceptionSpec(NewDD);
8613
8614 IsVirtualOkay = true;
8615 return NewDD;
8616
8617 } else {
8618 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8619 D.setInvalidType();
8620
8621 // Create a FunctionDecl to satisfy the function definition parsing
8622 // code path.
8623 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8624 D.getIdentifierLoc(), Name, R, TInfo, SC,
8625 isInline,
8626 /*hasPrototype=*/true, ConstexprKind,
8627 TrailingRequiresClause);
8628 }
8629
8630 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8631 if (!DC->isRecord()) {
8632 SemaRef.Diag(D.getIdentifierLoc(),
8633 diag::err_conv_function_not_member);
8634 return nullptr;
8635 }
8636
8637 SemaRef.CheckConversionDeclarator(D, R, SC);
8638 if (D.isInvalidType())
8639 return nullptr;
8640
8641 IsVirtualOkay = true;
8642 return CXXConversionDecl::Create(
8643 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8644 TInfo, isInline, ExplicitSpecifier, ConstexprKind, SourceLocation(),
8645 TrailingRequiresClause);
8646
8647 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8648 if (TrailingRequiresClause)
8649 SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8650 diag::err_trailing_requires_clause_on_deduction_guide)
8651 << TrailingRequiresClause->getSourceRange();
8652 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8653
8654 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8655 ExplicitSpecifier, NameInfo, R, TInfo,
8656 D.getEndLoc());
8657 } else if (DC->isRecord()) {
8658 // If the name of the function is the same as the name of the record,
8659 // then this must be an invalid constructor that has a return type.
8660 // (The parser checks for a return type and makes the declarator a
8661 // constructor if it has no return type).
8662 if (Name.getAsIdentifierInfo() &&
8663 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8664 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8665 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8666 << SourceRange(D.getIdentifierLoc());
8667 return nullptr;
8668 }
8669
8670 // This is a C++ method declaration.
8671 CXXMethodDecl *Ret = CXXMethodDecl::Create(
8672 SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8673 TInfo, SC, isInline, ConstexprKind, SourceLocation(),
8674 TrailingRequiresClause);
8675 IsVirtualOkay = !Ret->isStatic();
8676 return Ret;
8677 } else {
8678 bool isFriend =
8679 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8680 if (!isFriend && SemaRef.CurContext->isRecord())
8681 return nullptr;
8682
8683 // Determine whether the function was written with a
8684 // prototype. This true when:
8685 // - we're in C++ (where every function has a prototype),
8686 return FunctionDecl::Create(SemaRef.Context, DC, D.getBeginLoc(), NameInfo,
8687 R, TInfo, SC, isInline, true /*HasPrototype*/,
8688 ConstexprKind, TrailingRequiresClause);
8689 }
8690}
8691
8692enum OpenCLParamType {
8693 ValidKernelParam,
8694 PtrPtrKernelParam,
8695 PtrKernelParam,
8696 InvalidAddrSpacePtrKernelParam,
8697 InvalidKernelParam,
8698 RecordKernelParam
8699};
8700
8701static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty) {
8702 // Size dependent types are just typedefs to normal integer types
8703 // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8704 // integers other than by their names.
8705 StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8706
8707 // Remove typedefs one by one until we reach a typedef
8708 // for a size dependent type.
8709 QualType DesugaredTy = Ty;
8710 do {
8711 ArrayRef<StringRef> Names(SizeTypeNames);
8712 auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8713 if (Names.end() != Match)
8714 return true;
8715
8716 Ty = DesugaredTy;
8717 DesugaredTy = Ty.getSingleStepDesugaredType(C);
8718 } while (DesugaredTy != Ty);
8719
8720 return false;
8721}
8722
8723static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8724 if (PT->isDependentType())
8725 return InvalidKernelParam;
8726
8727 if (PT->isPointerType() || PT->isReferenceType()) {
8728 QualType PointeeType = PT->getPointeeType();
8729 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8730 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8731 PointeeType.getAddressSpace() == LangAS::Default)
8732 return InvalidAddrSpacePtrKernelParam;
8733
8734 if (PointeeType->isPointerType()) {
8735 // This is a pointer to pointer parameter.
8736 // Recursively check inner type.
8737 OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8738 if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8739 ParamKind == InvalidKernelParam)
8740 return ParamKind;
8741
8742 return PtrPtrKernelParam;
8743 }
8744
8745 // C++ for OpenCL v1.0 s2.4:
8746 // Moreover the types used in parameters of the kernel functions must be:
8747 // Standard layout types for pointer parameters. The same applies to
8748 // reference if an implementation supports them in kernel parameters.
8749 if (S.getLangOpts().OpenCLCPlusPlus &&
8750 !S.getOpenCLOptions().isAvailableOption(
8751 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8752 !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8753 !PointeeType->isStandardLayoutType())
8754 return InvalidKernelParam;
8755
8756 return PtrKernelParam;
8757 }
8758
8759 // OpenCL v1.2 s6.9.k:
8760 // Arguments to kernel functions in a program cannot be declared with the
8761 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8762 // uintptr_t or a struct and/or union that contain fields declared to be one
8763 // of these built-in scalar types.
8764 if (isOpenCLSizeDependentType(S.getASTContext(), PT))
8765 return InvalidKernelParam;
8766
8767 if (PT->isImageType())
8768 return PtrKernelParam;
8769
8770 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8771 return InvalidKernelParam;
8772
8773 // OpenCL extension spec v1.2 s9.5:
8774 // This extension adds support for half scalar and vector types as built-in
8775 // types that can be used for arithmetic operations, conversions etc.
8776 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8777 PT->isHalfType())
8778 return InvalidKernelParam;
8779
8780 // Look into an array argument to check if it has a forbidden type.
8781 if (PT->isArrayType()) {
8782 const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8783 // Call ourself to check an underlying type of an array. Since the
8784 // getPointeeOrArrayElementType returns an innermost type which is not an
8785 // array, this recursive call only happens once.
8786 return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8787 }
8788
8789 // C++ for OpenCL v1.0 s2.4:
8790 // Moreover the types used in parameters of the kernel functions must be:
8791 // Trivial and standard-layout types C++17 [basic.types] (plain old data
8792 // types) for parameters passed by value;
8793 if (S.getLangOpts().OpenCLCPlusPlus &&
8794 !S.getOpenCLOptions().isAvailableOption(
8795 "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8796 !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8797 return InvalidKernelParam;
8798
8799 if (PT->isRecordType())
8800 return RecordKernelParam;
8801
8802 return ValidKernelParam;
8803}
8804
8805static void checkIsValidOpenCLKernelParameter(
8806 Sema &S,
8807 Declarator &D,
8808 ParmVarDecl *Param,
8809 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8810 QualType PT = Param->getType();
8811
8812 // Cache the valid types we encounter to avoid rechecking structs that are
8813 // used again
8814 if (ValidTypes.count(PT.getTypePtr()))
8815 return;
8816
8817 switch (getOpenCLKernelParameterType(S, PT)) {
8818 case PtrPtrKernelParam:
8819 // OpenCL v3.0 s6.11.a:
8820 // A kernel function argument cannot be declared as a pointer to a pointer
8821 // type. [...] This restriction only applies to OpenCL C 1.2 or below.
8822 if (S.getLangOpts().OpenCLVersion <= 120 &&
8823 !S.getLangOpts().OpenCLCPlusPlus) {
8824 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8825 D.setInvalidType();
8826 return;
8827 }
8828
8829 ValidTypes.insert(PT.getTypePtr());
8830 return;
8831
8832 case InvalidAddrSpacePtrKernelParam:
8833 // OpenCL v1.0 s6.5:
8834 // __kernel function arguments declared to be a pointer of a type can point
8835 // to one of the following address spaces only : __global, __local or
8836 // __constant.
8837 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8838 D.setInvalidType();
8839 return;
8840
8841 // OpenCL v1.2 s6.9.k:
8842 // Arguments to kernel functions in a program cannot be declared with the
8843 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8844 // uintptr_t or a struct and/or union that contain fields declared to be
8845 // one of these built-in scalar types.
8846
8847 case InvalidKernelParam:
8848 // OpenCL v1.2 s6.8 n:
8849 // A kernel function argument cannot be declared
8850 // of event_t type.
8851 // Do not diagnose half type since it is diagnosed as invalid argument
8852 // type for any function elsewhere.
8853 if (!PT->isHalfType()) {
8854 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8855
8856 // Explain what typedefs are involved.
8857 const TypedefType *Typedef = nullptr;
8858 while ((Typedef = PT->getAs<TypedefType>())) {
8859 SourceLocation Loc = Typedef->getDecl()->getLocation();
8860 // SourceLocation may be invalid for a built-in type.
8861 if (Loc.isValid())
8862 S.Diag(Loc, diag::note_entity_declared_at) << PT;
8863 PT = Typedef->desugar();
8864 }
8865 }
8866
8867 D.setInvalidType();
8868 return;
8869
8870 case PtrKernelParam:
8871 case ValidKernelParam:
8872 ValidTypes.insert(PT.getTypePtr());
8873 return;
8874
8875 case RecordKernelParam:
8876 break;
8877 }
8878
8879 // Track nested structs we will inspect
8880 SmallVector<const Decl *, 4> VisitStack;
8881
8882 // Track where we are in the nested structs. Items will migrate from
8883 // VisitStack to HistoryStack as we do the DFS for bad field.
8884 SmallVector<const FieldDecl *, 4> HistoryStack;
8885 HistoryStack.push_back(nullptr);
8886
8887 // At this point we already handled everything except of a RecordType or
8888 // an ArrayType of a RecordType.
8889 assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.")((void)0);
8890 const RecordType *RecTy =
8891 PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8892 const RecordDecl *OrigRecDecl = RecTy->getDecl();
8893
8894 VisitStack.push_back(RecTy->getDecl());
8895 assert(VisitStack.back() && "First decl null?")((void)0);
8896
8897 do {
8898 const Decl *Next = VisitStack.pop_back_val();
8899 if (!Next) {
8900 assert(!HistoryStack.empty())((void)0);
8901 // Found a marker, we have gone up a level
8902 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8903 ValidTypes.insert(Hist->getType().getTypePtr());
8904
8905 continue;
8906 }
8907
8908 // Adds everything except the original parameter declaration (which is not a
8909 // field itself) to the history stack.
8910 const RecordDecl *RD;
8911 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8912 HistoryStack.push_back(Field);
8913
8914 QualType FieldTy = Field->getType();
8915 // Other field types (known to be valid or invalid) are handled while we
8916 // walk around RecordDecl::fields().
8917 assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&((void)0)
8918 "Unexpected type.")((void)0);
8919 const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8920
8921 RD = FieldRecTy->castAs<RecordType>()->getDecl();
8922 } else {
8923 RD = cast<RecordDecl>(Next);
8924 }
8925
8926 // Add a null marker so we know when we've gone back up a level
8927 VisitStack.push_back(nullptr);
8928
8929 for (const auto *FD : RD->fields()) {
8930 QualType QT = FD->getType();
8931
8932 if (ValidTypes.count(QT.getTypePtr()))
8933 continue;
8934
8935 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8936 if (ParamType == ValidKernelParam)
8937 continue;
8938
8939 if (ParamType == RecordKernelParam) {
8940 VisitStack.push_back(FD);
8941 continue;
8942 }
8943
8944 // OpenCL v1.2 s6.9.p:
8945 // Arguments to kernel functions that are declared to be a struct or union
8946 // do not allow OpenCL objects to be passed as elements of the struct or
8947 // union.
8948 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8949 ParamType == InvalidAddrSpacePtrKernelParam) {
8950 S.Diag(Param->getLocation(),
8951 diag::err_record_with_pointers_kernel_param)
8952 << PT->isUnionType()
8953 << PT;
8954 } else {
8955 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8956 }
8957
8958 S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8959 << OrigRecDecl->getDeclName();
8960
8961 // We have an error, now let's go back up through history and show where
8962 // the offending field came from
8963 for (ArrayRef<const FieldDecl *>::const_iterator
8964 I = HistoryStack.begin() + 1,
8965 E = HistoryStack.end();
8966 I != E; ++I) {
8967 const FieldDecl *OuterField = *I;
8968 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8969 << OuterField->getType();
8970 }
8971
8972 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8973 << QT->isPointerType()
8974 << QT;
8975 D.setInvalidType();
8976 return;
8977 }
8978 } while (!VisitStack.empty());
8979}
8980
8981/// Find the DeclContext in which a tag is implicitly declared if we see an
8982/// elaborated type specifier in the specified context, and lookup finds
8983/// nothing.
8984static DeclContext *getTagInjectionContext(DeclContext *DC) {
8985 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8986 DC = DC->getParent();
8987 return DC;
8988}
8989
8990/// Find the Scope in which a tag is implicitly declared if we see an
8991/// elaborated type specifier in the specified context, and lookup finds
8992/// nothing.
8993static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8994 while (S->isClassScope() ||
8995 (LangOpts.CPlusPlus &&
8996 S->isFunctionPrototypeScope()) ||
8997 ((S->getFlags() & Scope::DeclScope) == 0) ||
8998 (S->getEntity() && S->getEntity()->isTransparentContext()))
8999 S = S->getParent();
9000 return S;
9001}
9002
9003NamedDecl*
9004Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
9005 TypeSourceInfo *TInfo, LookupResult &Previous,
9006 MultiTemplateParamsArg TemplateParamListsRef,
9007 bool &AddToScope) {
9008 QualType R = TInfo->getType();
9009
9010 assert(R->isFunctionType())((void)0);
9011 if (R.getCanonicalType()->castAs<FunctionType>()->getCmseNSCallAttr())
9012 Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9013
9014 SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9015 for (TemplateParameterList *TPL : TemplateParamListsRef)
9016 TemplateParamLists.push_back(TPL);
9017 if (TemplateParameterList *Invented = D.getInventedTemplateParameterList()) {
9018 if (!TemplateParamLists.empty() &&
9019 Invented->getDepth() == TemplateParamLists.back()->getDepth())
9020 TemplateParamLists.back() = Invented;
9021 else
9022 TemplateParamLists.push_back(Invented);
9023 }
9024
9025 // TODO: consider using NameInfo for diagnostic.
9026 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9027 DeclarationName Name = NameInfo.getName();
9028 StorageClass SC = getFunctionStorageClass(*this, D);
9029
9030 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
9031 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
9032 diag::err_invalid_thread)
9033 << DeclSpec::getSpecifierName(TSCS);
9034
9035 if (D.isFirstDeclarationOfMember())
9036 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9037 D.getIdentifierLoc());
9038
9039 bool isFriend = false;
9040 FunctionTemplateDecl *FunctionTemplate = nullptr;
9041 bool isMemberSpecialization = false;
9042 bool isFunctionTemplateSpecialization = false;
9043
9044 bool isDependentClassScopeExplicitSpecialization = false;
9045 bool HasExplicitTemplateArgs = false;
9046 TemplateArgumentListInfo TemplateArgs;
9047
9048 bool isVirtualOkay = false;
9049
9050 DeclContext *OriginalDC = DC;
9051 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9052
9053 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9054 isVirtualOkay);
9055 if (!NewFD) return nullptr;
9056
9057 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9058 NewFD->setTopLevelDeclInObjCContainer();
9059
9060 // Set the lexical context. If this is a function-scope declaration, or has a
9061 // C++ scope specifier, or is the object of a friend declaration, the lexical
9062 // context will be different from the semantic context.
9063 NewFD->setLexicalDeclContext(CurContext);
9064
9065 if (IsLocalExternDecl)
9066 NewFD->setLocalExternDecl();
9067
9068 if (getLangOpts().CPlusPlus) {
9069 bool isInline = D.getDeclSpec().isInlineSpecified();
9070 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9071 bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9072 isFriend = D.getDeclSpec().isFriendSpecified();
9073 if (isFriend && !isInline && D.isFunctionDefinition()) {
9074 // C++ [class.friend]p5
9075 // A function can be defined in a friend declaration of a
9076 // class . . . . Such a function is implicitly inline.
9077 NewFD->setImplicitlyInline();
9078 }
9079
9080 // If this is a method defined in an __interface, and is not a constructor
9081 // or an overloaded operator, then set the pure flag (isVirtual will already
9082 // return true).
9083 if (const CXXRecordDecl *Parent =
9084 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9085 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9086 NewFD->setPure(true);
9087
9088 // C++ [class.union]p2
9089 // A union can have member functions, but not virtual functions.
9090 if (isVirtual && Parent->isUnion())
9091 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9092 }
9093
9094 SetNestedNameSpecifier(*this, NewFD, D);
9095 isMemberSpecialization = false;
9096 isFunctionTemplateSpecialization = false;
9097 if (D.isInvalidType())
9098 NewFD->setInvalidDecl();
9099
9100 // Match up the template parameter lists with the scope specifier, then
9101 // determine whether we have a template or a template specialization.
9102 bool Invalid = false;
9103 TemplateParameterList *TemplateParams =
9104 MatchTemplateParametersToScopeSpecifier(
9105 D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
9106 D.getCXXScopeSpec(),
9107 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
9108 ? D.getName().TemplateId
9109 : nullptr,
9110 TemplateParamLists, isFriend, isMemberSpecialization,
9111 Invalid);
9112 if (TemplateParams) {
9113 // Check that we can declare a template here.
9114 if (CheckTemplateDeclScope(S, TemplateParams))
9115 NewFD->setInvalidDecl();
9116
9117 if (TemplateParams->size() > 0) {
9118 // This is a function template
9119
9120 // A destructor cannot be a template.
9121 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9122 Diag(NewFD->getLocation(), diag::err_destructor_template);
9123 NewFD->setInvalidDecl();
9124 }
9125
9126 // If we're adding a template to a dependent context, we may need to
9127 // rebuilding some of the types used within the template parameter list,
9128 // now that we know what the current instantiation is.
9129 if (DC->isDependentContext()) {
9130 ContextRAII SavedContext(*this, DC);
9131 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9132 Invalid = true;
9133 }
9134
9135 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9136 NewFD->getLocation(),
9137 Name, TemplateParams,
9138 NewFD);
9139 FunctionTemplate->setLexicalDeclContext(CurContext);
9140 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9141
9142 // For source fidelity, store the other template param lists.
9143 if (TemplateParamLists.size() > 1) {
9144 NewFD->setTemplateParameterListsInfo(Context,
9145 ArrayRef<TemplateParameterList *>(TemplateParamLists)
9146 .drop_back(1));
9147 }
9148 } else {
9149 // This is a function template specialization.
9150 isFunctionTemplateSpecialization = true;
9151 // For source fidelity, store all the template param lists.
9152 if (TemplateParamLists.size() > 0)
9153 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9154
9155 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9156 if (isFriend) {
9157 // We want to remove the "template<>", found here.
9158 SourceRange RemoveRange = TemplateParams->getSourceRange();
9159
9160 // If we remove the template<> and the name is not a
9161 // template-id, we're actually silently creating a problem:
9162 // the friend declaration will refer to an untemplated decl,
9163 // and clearly the user wants a template specialization. So
9164 // we need to insert '<>' after the name.
9165 SourceLocation InsertLoc;
9166 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
9167 InsertLoc = D.getName().getSourceRange().getEnd();
9168 InsertLoc = getLocForEndOfToken(InsertLoc);
9169 }
9170
9171 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9172 << Name << RemoveRange
9173 << FixItHint::CreateRemoval(RemoveRange)
9174 << FixItHint::CreateInsertion(InsertLoc, "<>");
9175 }
9176 }
9177 } else {
9178 // Check that we can declare a template here.
9179 if (!TemplateParamLists.empty() && isMemberSpecialization &&
9180 CheckTemplateDeclScope(S, TemplateParamLists.back()))
9181 NewFD->setInvalidDecl();
9182
9183 // All template param lists were matched against the scope specifier:
9184 // this is NOT (an explicit specialization of) a template.
9185 if (TemplateParamLists.size() > 0)
9186 // For source fidelity, store all the template param lists.
9187 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9188 }
9189
9190 if (Invalid) {
9191 NewFD->setInvalidDecl();
9192 if (FunctionTemplate)
9193 FunctionTemplate->setInvalidDecl();
9194 }
9195
9196 // C++ [dcl.fct.spec]p5:
9197 // The virtual specifier shall only be used in declarations of
9198 // nonstatic class member functions that appear within a
9199 // member-specification of a class declaration; see 10.3.
9200 //
9201 if (isVirtual && !NewFD->isInvalidDecl()) {
9202 if (!isVirtualOkay) {
9203 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9204 diag::err_virtual_non_function);
9205 } else if (!CurContext->isRecord()) {
9206 // 'virtual' was specified outside of the class.
9207 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9208 diag::err_virtual_out_of_class)
9209 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9210 } else if (NewFD->getDescribedFunctionTemplate()) {
9211 // C++ [temp.mem]p3:
9212 // A member function template shall not be virtual.
9213 Diag(D.getDeclSpec().getVirtualSpecLoc(),
9214 diag::err_virtual_member_function_template)
9215 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
9216 } else {
9217 // Okay: Add virtual to the method.
9218 NewFD->setVirtualAsWritten(true);
9219 }
9220
9221 if (getLangOpts().CPlusPlus14 &&
9222 NewFD->getReturnType()->isUndeducedType())
9223 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9224 }
9225
9226 if (getLangOpts().CPlusPlus14 &&
9227 (NewFD->isDependentContext() ||
9228 (isFriend && CurContext->isDependentContext())) &&
9229 NewFD->getReturnType()->isUndeducedType()) {
9230 // If the function template is referenced directly (for instance, as a
9231 // member of the current instantiation), pretend it has a dependent type.
9232 // This is not really justified by the standard, but is the only sane
9233 // thing to do.
9234 // FIXME: For a friend function, we have not marked the function as being
9235 // a friend yet, so 'isDependentContext' on the FD doesn't work.
9236 const FunctionProtoType *FPT =
9237 NewFD->getType()->castAs<FunctionProtoType>();
9238 QualType Result =
9239 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
9240 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9241 FPT->getExtProtoInfo()));
9242 }
9243
9244 // C++ [dcl.fct.spec]p3:
9245 // The inline specifier shall not appear on a block scope function
9246 // declaration.
9247 if (isInline && !NewFD->isInvalidDecl()) {
9248 if (CurContext->isFunctionOrMethod()) {
9249 // 'inline' is not allowed on block scope function declaration.
9250 Diag(D.getDeclSpec().getInlineSpecLoc(),
9251 diag::err_inline_declaration_block_scope) << Name
9252 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
9253 }
9254 }
9255
9256 // C++ [dcl.fct.spec]p6:
9257 // The explicit specifier shall be used only in the declaration of a
9258 // constructor or conversion function within its class definition;
9259 // see 12.3.1 and 12.3.2.
9260 if (hasExplicit && !NewFD->isInvalidDecl() &&
9261 !isa<CXXDeductionGuideDecl>(NewFD)) {
9262 if (!CurContext->isRecord()) {
9263 // 'explicit' was specified outside of the class.
9264 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9265 diag::err_explicit_out_of_class)
9266 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9267 } else if (!isa<CXXConstructorDecl>(NewFD) &&
9268 !isa<CXXConversionDecl>(NewFD)) {
9269 // 'explicit' was specified on a function that wasn't a constructor
9270 // or conversion function.
9271 Diag(D.getDeclSpec().getExplicitSpecLoc(),
9272 diag::err_explicit_non_ctor_or_conv_function)
9273 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecRange());
9274 }
9275 }
9276
9277 ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9278 if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9279 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9280 // are implicitly inline.
9281 NewFD->setImplicitlyInline();
9282
9283 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9284 // be either constructors or to return a literal type. Therefore,
9285 // destructors cannot be declared constexpr.
9286 if (isa<CXXDestructorDecl>(NewFD) &&
9287 (!getLangOpts().CPlusPlus20 ||
9288 ConstexprKind == ConstexprSpecKind::Consteval)) {
9289 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9290 << static_cast<int>(ConstexprKind);
9291 NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9292 ? ConstexprSpecKind::Unspecified
9293 : ConstexprSpecKind::Constexpr);
9294 }
9295 // C++20 [dcl.constexpr]p2: An allocation function, or a
9296 // deallocation function shall not be declared with the consteval
9297 // specifier.
9298 if (ConstexprKind == ConstexprSpecKind::Consteval &&
9299 (NewFD->getOverloadedOperator() == OO_New ||
9300 NewFD->getOverloadedOperator() == OO_Array_New ||
9301 NewFD->getOverloadedOperator() == OO_Delete ||
9302 NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9303 Diag(D.getDeclSpec().getConstexprSpecLoc(),
9304 diag::err_invalid_consteval_decl_kind)
9305 << NewFD;
9306 NewFD->setConstexprKind(ConstexprSpecKind::Constexpr);
9307 }
9308 }
9309
9310 // If __module_private__ was specified, mark the function accordingly.
9311 if (D.getDeclSpec().isModulePrivateSpecified()) {
9312 if (isFunctionTemplateSpecialization) {
9313 SourceLocation ModulePrivateLoc
9314 = D.getDeclSpec().getModulePrivateSpecLoc();
9315 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9316 << 0
9317 << FixItHint::CreateRemoval(ModulePrivateLoc);
9318 } else {
9319 NewFD->setModulePrivate();
9320 if (FunctionTemplate)
9321 FunctionTemplate->setModulePrivate();
9322 }
9323 }
9324
9325 if (isFriend) {
9326 if (FunctionTemplate) {
9327 FunctionTemplate->setObjectOfFriendDecl();
9328 FunctionTemplate->setAccess(AS_public);
9329 }
9330 NewFD->setObjectOfFriendDecl();
9331 NewFD->setAccess(AS_public);
9332 }
9333
9334 // If a function is defined as defaulted or deleted, mark it as such now.
9335 // We'll do the relevant checks on defaulted / deleted functions later.
9336 switch (D.getFunctionDefinitionKind()) {
9337 case FunctionDefinitionKind::Declaration:
9338 case FunctionDefinitionKind::Definition:
9339 break;
9340
9341 case FunctionDefinitionKind::Defaulted:
9342 NewFD->setDefaulted();
9343 break;
9344
9345 case FunctionDefinitionKind::Deleted:
9346 NewFD->setDeletedAsWritten();
9347 break;
9348 }
9349
9350 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9351 D.isFunctionDefinition()) {
9352 // C++ [class.mfct]p2:
9353 // A member function may be defined (8.4) in its class definition, in
9354 // which case it is an inline member function (7.1.2)
9355 NewFD->setImplicitlyInline();
9356 }
9357
9358 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9359 !CurContext->isRecord()) {
9360 // C++ [class.static]p1:
9361 // A data or function member of a class may be declared static
9362 // in a class definition, in which case it is a static member of
9363 // the class.
9364
9365 // Complain about the 'static' specifier if it's on an out-of-line
9366 // member function definition.
9367
9368 // MSVC permits the use of a 'static' storage specifier on an out-of-line
9369 // member function template declaration and class member template
9370 // declaration (MSVC versions before 2015), warn about this.
9371 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
9372 ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9373 cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9374 (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9375 ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9376 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
9377 }
9378
9379 // C++11 [except.spec]p15:
9380 // A deallocation function with no exception-specification is treated
9381 // as if it were specified with noexcept(true).
9382 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9383 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9384 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9385 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9386 NewFD->setType(Context.getFunctionType(
9387 FPT->getReturnType(), FPT->getParamTypes(),
9388 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
9389 }
9390
9391 // Filter out previous declarations that don't match the scope.
9392 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9393 D.getCXXScopeSpec().isNotEmpty() ||
9394 isMemberSpecialization ||
9395 isFunctionTemplateSpecialization);
9396
9397 // Handle GNU asm-label extension (encoded as an attribute).
9398 if (Expr *E = (Expr*) D.getAsmLabel()) {
9399 // The parser guarantees this is a string.
9400 StringLiteral *SE = cast<StringLiteral>(E);
9401 NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9402 /*IsLiteralLabel=*/true,
9403 SE->getStrTokenLoc(0)));
9404 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9405 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9406 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9407 if (I != ExtnameUndeclaredIdentifiers.end()) {
9408 if (isDeclExternC(NewFD)) {
9409 NewFD->addAttr(I->second);
9410 ExtnameUndeclaredIdentifiers.erase(I);
9411 } else
9412 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9413 << /*Variable*/0 << NewFD;
9414 }
9415 }
9416
9417 // Copy the parameter declarations from the declarator D to the function
9418 // declaration NewFD, if they are available. First scavenge them into Params.
9419 SmallVector<ParmVarDecl*, 16> Params;
9420 unsigned FTIIdx;
9421 if (D.isFunctionDeclarator(FTIIdx)) {
9422 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
9423
9424 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9425 // function that takes no arguments, not a function that takes a
9426 // single void argument.
9427 // We let through "const void" here because Sema::GetTypeForDeclarator
9428 // already checks for that case.
9429 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9430 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9431 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9432 assert(Param->getDeclContext() != NewFD && "Was set before ?")((void)0);
9433 Param->setDeclContext(NewFD);
9434 Params.push_back(Param);
9435
9436 if (Param->isInvalidDecl())
9437 NewFD->setInvalidDecl();
9438 }
9439 }
9440
9441 if (!getLangOpts().CPlusPlus) {
9442 // In C, find all the tag declarations from the prototype and move them
9443 // into the function DeclContext. Remove them from the surrounding tag
9444 // injection context of the function, which is typically but not always
9445 // the TU.
9446 DeclContext *PrototypeTagContext =
9447 getTagInjectionContext(NewFD->getLexicalDeclContext());
9448 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9449 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9450
9451 // We don't want to reparent enumerators. Look at their parent enum
9452 // instead.
9453 if (!TD) {
9454 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9455 TD = cast<EnumDecl>(ECD->getDeclContext());
9456 }
9457 if (!TD)
9458 continue;
9459 DeclContext *TagDC = TD->getLexicalDeclContext();
9460 if (!TagDC->containsDecl(TD))
9461 continue;
9462 TagDC->removeDecl(TD);
9463 TD->setDeclContext(NewFD);
9464 NewFD->addDecl(TD);
9465
9466 // Preserve the lexical DeclContext if it is not the surrounding tag
9467 // injection context of the FD. In this example, the semantic context of
9468 // E will be f and the lexical context will be S, while both the
9469 // semantic and lexical contexts of S will be f:
9470 // void f(struct S { enum E { a } f; } s);
9471 if (TagDC != PrototypeTagContext)
9472 TD->setLexicalDeclContext(TagDC);
9473 }
9474 }
9475 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9476 // When we're declaring a function with a typedef, typeof, etc as in the
9477 // following example, we'll need to synthesize (unnamed)
9478 // parameters for use in the declaration.
9479 //
9480 // @code
9481 // typedef void fn(int);
9482 // fn f;
9483 // @endcode
9484
9485 // Synthesize a parameter for each argument type.
9486 for (const auto &AI : FT->param_types()) {
9487 ParmVarDecl *Param =
9488 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9489 Param->setScopeInfo(0, Params.size());
9490 Params.push_back(Param);
9491 }
9492 } else {
9493 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&((void)0)
9494 "Should not need args for typedef of non-prototype fn")((void)0);
9495 }
9496
9497 // Finally, we know we have the right number of parameters, install them.
9498 NewFD->setParams(Params);
9499
9500 if (D.getDeclSpec().isNoreturnSpecified())
9501 NewFD->addAttr(C11NoReturnAttr::Create(Context,
9502 D.getDeclSpec().getNoreturnSpecLoc(),
9503 AttributeCommonInfo::AS_Keyword));
9504
9505 // Functions returning a variably modified type violate C99 6.7.5.2p2
9506 // because all functions have linkage.
9507 if (!NewFD->isInvalidDecl() &&
9508 NewFD->getReturnType()->isVariablyModifiedType()) {
9509 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9510 NewFD->setInvalidDecl();
9511 }
9512
9513 // Apply an implicit SectionAttr if '#pragma clang section text' is active
9514 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9515 !NewFD->hasAttr<SectionAttr>())
9516 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9517 Context, PragmaClangTextSection.SectionName,
9518 PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9519
9520 // Apply an implicit SectionAttr if #pragma code_seg is active.
9521 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9522 !NewFD->hasAttr<SectionAttr>()) {
9523 NewFD->addAttr(SectionAttr::CreateImplicit(
9524 Context, CodeSegStack.CurrentValue->getString(),
9525 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9526 SectionAttr::Declspec_allocate));
9527 if (UnifySection(CodeSegStack.CurrentValue->getString(),
9528 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
9529 ASTContext::PSF_Read,
9530 NewFD))
9531 NewFD->dropAttr<SectionAttr>();
9532 }
9533
9534 // Apply an implicit CodeSegAttr from class declspec or
9535 // apply an implicit SectionAttr from #pragma code_seg if active.
9536 if (!NewFD->hasAttr<CodeSegAttr>()) {
9537 if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9538 D.isFunctionDefinition())) {
9539 NewFD->addAttr(SAttr);
9540 }
9541 }
9542
9543 // Handle attributes.
9544 ProcessDeclAttributes(S, NewFD, D);
9545
9546 if (getLangOpts().OpenCL) {
9547 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9548 // type declaration will generate a compilation error.
9549 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9550 if (AddressSpace != LangAS::Default) {
9551 Diag(NewFD->getLocation(),
9552 diag::err_opencl_return_value_with_address_space);
9553 NewFD->setInvalidDecl();
9554 }
9555 }
9556
9557 if (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice))
9558 checkDeviceDecl(NewFD, D.getBeginLoc());
9559
9560 if (!getLangOpts().CPlusPlus) {
9561 // Perform semantic checking on the function declaration.
9562 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9563 CheckMain(NewFD, D.getDeclSpec());
9564
9565 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9566 CheckMSVCRTEntryPoint(NewFD);
9567
9568 if (!NewFD->isInvalidDecl())
9569 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9570 isMemberSpecialization));
9571 else if (!Previous.empty())
9572 // Recover gracefully from an invalid redeclaration.
9573 D.setRedeclaration(true);
9574 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||((void)0)
9575 Previous.getResultKind() != LookupResult::FoundOverloaded) &&((void)0)
9576 "previous declaration set still overloaded")((void)0);
9577
9578 // Diagnose no-prototype function declarations with calling conventions that
9579 // don't support variadic calls. Only do this in C and do it after merging
9580 // possibly prototyped redeclarations.
9581 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9582 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9583 CallingConv CC = FT->getExtInfo().getCC();
9584 if (!supportsVariadicCall(CC)) {
9585 // Windows system headers sometimes accidentally use stdcall without
9586 // (void) parameters, so we relax this to a warning.
9587 int DiagID =
9588 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9589 Diag(NewFD->getLocation(), DiagID)
9590 << FunctionType::getNameForCallConv(CC);
9591 }
9592 }
9593
9594 if (NewFD->getReturnType().hasNonTrivialToPrimitiveDestructCUnion() ||
9595 NewFD->getReturnType().hasNonTrivialToPrimitiveCopyCUnion())
9596 checkNonTrivialCUnion(NewFD->getReturnType(),
9597 NewFD->getReturnTypeSourceRange().getBegin(),
9598 NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9599 } else {
9600 // C++11 [replacement.functions]p3:
9601 // The program's definitions shall not be specified as inline.
9602 //
9603 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9604 //
9605 // Suppress the diagnostic if the function is __attribute__((used)), since
9606 // that forces an external definition to be emitted.
9607 if (D.getDeclSpec().isInlineSpecified() &&
9608 NewFD->isReplaceableGlobalAllocationFunction() &&
9609 !NewFD->hasAttr<UsedAttr>())
9610 Diag(D.getDeclSpec().getInlineSpecLoc(),
9611 diag::ext_operator_new_delete_declared_inline)
9612 << NewFD->getDeclName();
9613
9614 // If the declarator is a template-id, translate the parser's template
9615 // argument list into our AST format.
9616 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
9617 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9618 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9619 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9620 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9621 TemplateId->NumArgs);
9622 translateTemplateArguments(TemplateArgsPtr,
9623 TemplateArgs);
9624
9625 HasExplicitTemplateArgs = true;
9626
9627 if (NewFD->isInvalidDecl()) {
9628 HasExplicitTemplateArgs = false;
9629 } else if (FunctionTemplate) {
9630 // Function template with explicit template arguments.
9631 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9632 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9633
9634 HasExplicitTemplateArgs = false;
9635 } else {
9636 assert((isFunctionTemplateSpecialization ||((void)0)
9637 D.getDeclSpec().isFriendSpecified()) &&((void)0)
9638 "should have a 'template<>' for this decl")((void)0);
9639 // "friend void foo<>(int);" is an implicit specialization decl.
9640 isFunctionTemplateSpecialization = true;
9641 }
9642 } else if (isFriend && isFunctionTemplateSpecialization) {
9643 // This combination is only possible in a recovery case; the user
9644 // wrote something like:
9645 // template <> friend void foo(int);
9646 // which we're recovering from as if the user had written:
9647 // friend void foo<>(int);
9648 // Go ahead and fake up a template id.
9649 HasExplicitTemplateArgs = true;
9650 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9651 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9652 }
9653
9654 // We do not add HD attributes to specializations here because
9655 // they may have different constexpr-ness compared to their
9656 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9657 // may end up with different effective targets. Instead, a
9658 // specialization inherits its target attributes from its template
9659 // in the CheckFunctionTemplateSpecialization() call below.
9660 if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9661 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9662
9663 // If it's a friend (and only if it's a friend), it's possible
9664 // that either the specialized function type or the specialized
9665 // template is dependent, and therefore matching will fail. In
9666 // this case, don't check the specialization yet.
9667 if (isFunctionTemplateSpecialization && isFriend &&
9668 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9669 TemplateSpecializationType::anyInstantiationDependentTemplateArguments(
9670 TemplateArgs.arguments()))) {
9671 assert(HasExplicitTemplateArgs &&((void)0)
9672 "friend function specialization without template args")((void)0);
9673 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9674 Previous))
9675 NewFD->setInvalidDecl();
9676 } else if (isFunctionTemplateSpecialization) {
9677 if (CurContext->isDependentContext() && CurContext->isRecord()
9678 && !isFriend) {
9679 isDependentClassScopeExplicitSpecialization = true;
9680 } else if (!NewFD->isInvalidDecl() &&
9681 CheckFunctionTemplateSpecialization(
9682 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9683 Previous))
9684 NewFD->setInvalidDecl();
9685
9686 // C++ [dcl.stc]p1:
9687 // A storage-class-specifier shall not be specified in an explicit
9688 // specialization (14.7.3)
9689 FunctionTemplateSpecializationInfo *Info =
9690 NewFD->getTemplateSpecializationInfo();
9691 if (Info && SC != SC_None) {
9692 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9693 Diag(NewFD->getLocation(),
9694 diag::err_explicit_specialization_inconsistent_storage_class)
9695 << SC
9696 << FixItHint::CreateRemoval(
9697 D.getDeclSpec().getStorageClassSpecLoc());
9698
9699 else
9700 Diag(NewFD->getLocation(),
9701 diag::ext_explicit_specialization_storage_class)
9702 << FixItHint::CreateRemoval(
9703 D.getDeclSpec().getStorageClassSpecLoc());
9704 }
9705 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9706 if (CheckMemberSpecialization(NewFD, Previous))
9707 NewFD->setInvalidDecl();
9708 }
9709
9710 // Perform semantic checking on the function declaration.
9711 if (!isDependentClassScopeExplicitSpecialization) {
9712 if (!NewFD->isInvalidDecl() && NewFD->isMain())
9713 CheckMain(NewFD, D.getDeclSpec());
9714
9715 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9716 CheckMSVCRTEntryPoint(NewFD);
9717
9718 if (!NewFD->isInvalidDecl())
9719 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9720 isMemberSpecialization));
9721 else if (!Previous.empty())
9722 // Recover gracefully from an invalid redeclaration.
9723 D.setRedeclaration(true);
9724 }
9725
9726 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||((void)0)
9727 Previous.getResultKind() != LookupResult::FoundOverloaded) &&((void)0)
9728 "previous declaration set still overloaded")((void)0);
9729
9730 NamedDecl *PrincipalDecl = (FunctionTemplate
9731 ? cast<NamedDecl>(FunctionTemplate)
9732 : NewFD);
9733
9734 if (isFriend && NewFD->getPreviousDecl()) {
9735 AccessSpecifier Access = AS_public;
9736 if (!NewFD->isInvalidDecl())
9737 Access = NewFD->getPreviousDecl()->getAccess();
9738
9739 NewFD->setAccess(Access);
9740 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9741 }
9742
9743 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9744 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9745 PrincipalDecl->setNonMemberOperator();
9746
9747 // If we have a function template, check the template parameter
9748 // list. This will check and merge default template arguments.
9749 if (FunctionTemplate) {
9750 FunctionTemplateDecl *PrevTemplate =
9751 FunctionTemplate->getPreviousDecl();
9752 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9753 PrevTemplate ? PrevTemplate->getTemplateParameters()
9754 : nullptr,
9755 D.getDeclSpec().isFriendSpecified()
9756 ? (D.isFunctionDefinition()
9757 ? TPC_FriendFunctionTemplateDefinition
9758 : TPC_FriendFunctionTemplate)
9759 : (D.getCXXScopeSpec().isSet() &&
9760 DC && DC->isRecord() &&
9761 DC->isDependentContext())
9762 ? TPC_ClassTemplateMember
9763 : TPC_FunctionTemplate);
9764 }
9765
9766 if (NewFD->isInvalidDecl()) {
9767 // Ignore all the rest of this.
9768 } else if (!D.isRedeclaration()) {
9769 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9770 AddToScope };
9771 // Fake up an access specifier if it's supposed to be a class member.
9772 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9773 NewFD->setAccess(AS_public);
9774
9775 // Qualified decls generally require a previous declaration.
9776 if (D.getCXXScopeSpec().isSet()) {
9777 // ...with the major exception of templated-scope or
9778 // dependent-scope friend declarations.
9779
9780 // TODO: we currently also suppress this check in dependent
9781 // contexts because (1) the parameter depth will be off when
9782 // matching friend templates and (2) we might actually be
9783 // selecting a friend based on a dependent factor. But there
9784 // are situations where these conditions don't apply and we
9785 // can actually do this check immediately.
9786 //
9787 // Unless the scope is dependent, it's always an error if qualified
9788 // redeclaration lookup found nothing at all. Diagnose that now;
9789 // nothing will diagnose that error later.
9790 if (isFriend &&
9791 (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9792 (!Previous.empty() && CurContext->isDependentContext()))) {
9793 // ignore these
9794 } else if (NewFD->isCPUDispatchMultiVersion() ||
9795 NewFD->isCPUSpecificMultiVersion()) {
9796 // ignore this, we allow the redeclaration behavior here to create new
9797 // versions of the function.
9798 } else {
9799 // The user tried to provide an out-of-line definition for a
9800 // function that is a member of a class or namespace, but there
9801 // was no such member function declared (C++ [class.mfct]p2,
9802 // C++ [namespace.memdef]p2). For example:
9803 //
9804 // class X {
9805 // void f() const;
9806 // };
9807 //
9808 // void X::f() { } // ill-formed
9809 //
9810 // Complain about this problem, and attempt to suggest close
9811 // matches (e.g., those that differ only in cv-qualifiers and
9812 // whether the parameter types are references).
9813
9814 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9815 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
9816 AddToScope = ExtraArgs.AddToScope;
9817 return Result;
9818 }
9819 }
9820
9821 // Unqualified local friend declarations are required to resolve
9822 // to something.
9823 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9824 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9825 *this, Previous, NewFD, ExtraArgs, true, S)) {
9826 AddToScope = ExtraArgs.AddToScope;
9827 return Result;
9828 }
9829 }
9830 } else if (!D.isFunctionDefinition() &&
9831 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9832 !isFriend && !isFunctionTemplateSpecialization &&
9833 !isMemberSpecialization) {
9834 // An out-of-line member function declaration must also be a
9835 // definition (C++ [class.mfct]p2).
9836 // Note that this is not the case for explicit specializations of
9837 // function templates or member functions of class templates, per
9838 // C++ [temp.expl.spec]p2. We also allow these declarations as an
9839 // extension for compatibility with old SWIG code which likes to
9840 // generate them.
9841 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9842 << D.getCXXScopeSpec().getRange();
9843 }
9844 }
9845
9846 // If this is the first declaration of a library builtin function, add
9847 // attributes as appropriate.
9848 if (!D.isRedeclaration() &&
9849 NewFD->getDeclContext()->getRedeclContext()->isFileContext()) {
9850 if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
9851 if (unsigned BuiltinID = II->getBuiltinID()) {
9852 if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
9853 // Validate the type matches unless this builtin is specified as
9854 // matching regardless of its declared type.
9855 if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
9856 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9857 } else {
9858 ASTContext::GetBuiltinTypeError Error;
9859 LookupNecessaryTypesForBuiltin(S, BuiltinID);
9860 QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
9861
9862 if (!Error && !BuiltinType.isNull() &&
9863 Context.hasSameFunctionTypeIgnoringExceptionSpec(
9864 NewFD->getType(), BuiltinType))
9865 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9866 }
9867 } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
9868 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9869 // FIXME: We should consider this a builtin only in the std namespace.
9870 NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
9871 }
9872 }
9873 }
9874 }
9875
9876 ProcessPragmaWeak(S, NewFD);
9877 checkAttributesAfterMerging(*this, *NewFD);
9878
9879 AddKnownFunctionAttributes(NewFD);
9880
9881 if (NewFD->hasAttr<OverloadableAttr>() &&
9882 !NewFD->getType()->getAs<FunctionProtoType>()) {
9883 Diag(NewFD->getLocation(),
9884 diag::err_attribute_overloadable_no_prototype)
9885 << NewFD;
9886
9887 // Turn this into a variadic function with no parameters.
9888 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9889 FunctionProtoType::ExtProtoInfo EPI(
9890 Context.getDefaultCallingConvention(true, false));
9891 EPI.Variadic = true;
9892 EPI.ExtInfo = FT->getExtInfo();
9893
9894 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9895 NewFD->setType(R);
9896 }
9897
9898 // If there's a #pragma GCC visibility in scope, and this isn't a class
9899 // member, set the visibility of this function.
9900 if (!DC->isRecord() && NewFD->isExternallyVisible())
9901 AddPushedVisibilityAttribute(NewFD);
9902
9903 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9904 // marking the function.
9905 AddCFAuditedAttribute(NewFD);
9906
9907 // If this is a function definition, check if we have to apply optnone due to
9908 // a pragma.
9909 if(D.isFunctionDefinition())
9910 AddRangeBasedOptnone(NewFD);
9911
9912 // If this is the first declaration of an extern C variable, update
9913 // the map of such variables.
9914 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9915 isIncompleteDeclExternC(*this, NewFD))
9916 RegisterLocallyScopedExternCDecl(NewFD, S);
9917
9918 // Set this FunctionDecl's range up to the right paren.
9919 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9920
9921 if (D.isRedeclaration() && !Previous.empty()) {
9922 NamedDecl *Prev = Previous.getRepresentativeDecl();
9923 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9924 isMemberSpecialization ||
9925 isFunctionTemplateSpecialization,
9926 D.isFunctionDefinition());
9927 }
9928
9929 if (getLangOpts().CUDA) {
9930 IdentifierInfo *II = NewFD->getIdentifier();
9931 if (II && II->isStr(getCudaConfigureFuncName()) &&
9932 !NewFD->isInvalidDecl() &&
9933 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9934 if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
9935 Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9936 << getCudaConfigureFuncName();
9937 Context.setcudaConfigureCallDecl(NewFD);
9938 }
9939
9940 // Variadic functions, other than a *declaration* of printf, are not allowed
9941 // in device-side CUDA code, unless someone passed
9942 // -fcuda-allow-variadic-functions.
9943 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9944 (NewFD->hasAttr<CUDADeviceAttr>() ||
9945 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9946 !(II && II->isStr("printf") && NewFD->isExternC() &&
9947 !D.isFunctionDefinition())) {
9948 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9949 }
9950 }
9951
9952 MarkUnusedFileScopedDecl(NewFD);
9953
9954
9955
9956 if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
9957 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9958 if ((getLangOpts().OpenCLVersion >= 120)
9959 && (SC == SC_Static)) {
9960 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9961 D.setInvalidType();
9962 }
9963
9964 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9965 if (!NewFD->getReturnType()->isVoidType()) {
9966 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9967 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9968 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9969 : FixItHint());
9970 D.setInvalidType();
9971 }
9972
9973 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9974 for (auto Param : NewFD->parameters())
9975 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9976
9977 if (getLangOpts().OpenCLCPlusPlus) {
9978 if (DC->isRecord()) {
9979 Diag(D.getIdentifierLoc(), diag::err_method_kernel);
9980 D.setInvalidType();
9981 }
9982 if (FunctionTemplate) {
9983 Diag(D.getIdentifierLoc(), diag::err_template_kernel);
9984 D.setInvalidType();
9985 }
9986 }
9987 }
9988
9989 if (getLangOpts().CPlusPlus) {
9990 if (FunctionTemplate) {
9991 if (NewFD->isInvalidDecl())
9992 FunctionTemplate->setInvalidDecl();
9993 return FunctionTemplate;
9994 }
9995
9996 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9997 CompleteMemberSpecialization(NewFD, Previous);
9998 }
9999
10000 for (const ParmVarDecl *Param : NewFD->parameters()) {
10001 QualType PT = Param->getType();
10002
10003 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
10004 // types.
10005 if (getLangOpts().OpenCLVersion >= 200 || getLangOpts().OpenCLCPlusPlus) {
10006 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
10007 QualType ElemTy = PipeTy->getElementType();
10008 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10009 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10010 D.setInvalidType();
10011 }
10012 }
10013 }
10014 }
10015
10016 // Here we have an function template explicit specialization at class scope.
10017 // The actual specialization will be postponed to template instatiation
10018 // time via the ClassScopeFunctionSpecializationDecl node.
10019 if (isDependentClassScopeExplicitSpecialization) {
10020 ClassScopeFunctionSpecializationDecl *NewSpec =
10021 ClassScopeFunctionSpecializationDecl::Create(
10022 Context, CurContext, NewFD->getLocation(),
10023 cast<CXXMethodDecl>(NewFD),
10024 HasExplicitTemplateArgs, TemplateArgs);
10025 CurContext->addDecl(NewSpec);
10026 AddToScope = false;
10027 }
10028
10029 // Diagnose availability attributes. Availability cannot be used on functions
10030 // that are run during load/unload.
10031 if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10032 if (NewFD->hasAttr<ConstructorAttr>()) {
10033 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10034 << 1;
10035 NewFD->dropAttr<AvailabilityAttr>();
10036 }
10037 if (NewFD->hasAttr<DestructorAttr>()) {
10038 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10039 << 2;
10040 NewFD->dropAttr<AvailabilityAttr>();
10041 }
10042 }
10043
10044 // Diagnose no_builtin attribute on function declaration that are not a
10045 // definition.
10046 // FIXME: We should really be doing this in
10047 // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10048 // the FunctionDecl and at this point of the code
10049 // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10050 // because Sema::ActOnStartOfFunctionDef has not been called yet.
10051 if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10052 switch (D.getFunctionDefinitionKind()) {
10053 case FunctionDefinitionKind::Defaulted:
10054 case FunctionDefinitionKind::Deleted:
10055 Diag(NBA->getLocation(),
10056 diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10057 << NBA->getSpelling();
10058 break;
10059 case FunctionDefinitionKind::Declaration:
10060 Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10061 << NBA->getSpelling();
10062 break;
10063 case FunctionDefinitionKind::Definition:
10064 break;
10065 }
10066
10067 return NewFD;
10068}
10069
10070/// Return a CodeSegAttr from a containing class. The Microsoft docs say
10071/// when __declspec(code_seg) "is applied to a class, all member functions of
10072/// the class and nested classes -- this includes compiler-generated special
10073/// member functions -- are put in the specified segment."
10074/// The actual behavior is a little more complicated. The Microsoft compiler
10075/// won't check outer classes if there is an active value from #pragma code_seg.
10076/// The CodeSeg is always applied from the direct parent but only from outer
10077/// classes when the #pragma code_seg stack is empty. See:
10078/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10079/// available since MS has removed the page.
10080static Attr *getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD) {
10081 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10082 if (!Method)
10083 return nullptr;
10084 const CXXRecordDecl *Parent = Method->getParent();
10085 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10086 Attr *NewAttr = SAttr->clone(S.getASTContext());
10087 NewAttr->setImplicit(true);
10088 return NewAttr;
10089 }
10090
10091 // The Microsoft compiler won't check outer classes for the CodeSeg
10092 // when the #pragma code_seg stack is active.
10093 if (S.CodeSegStack.CurrentValue)
10094 return nullptr;
10095
10096 while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10097 if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10098 Attr *NewAttr = SAttr->clone(S.getASTContext());
10099 NewAttr->setImplicit(true);
10100 return NewAttr;
10101 }
10102 }
10103 return nullptr;
10104}
10105
10106/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10107/// containing class. Otherwise it will return implicit SectionAttr if the
10108/// function is a definition and there is an active value on CodeSegStack
10109/// (from the current #pragma code-seg value).
10110///
10111/// \param FD Function being declared.
10112/// \param IsDefinition Whether it is a definition or just a declarartion.
10113/// \returns A CodeSegAttr or SectionAttr to apply to the function or
10114/// nullptr if no attribute should be added.
10115Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
10116 bool IsDefinition) {
10117 if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10118 return A;
10119 if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10120 CodeSegStack.CurrentValue)
10121 return SectionAttr::CreateImplicit(
10122 getASTContext(), CodeSegStack.CurrentValue->getString(),
10123 CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10124 SectionAttr::Declspec_allocate);
10125 return nullptr;
10126}
10127
10128/// Determines if we can perform a correct type check for \p D as a
10129/// redeclaration of \p PrevDecl. If not, we can generally still perform a
10130/// best-effort check.
10131///
10132/// \param NewD The new declaration.
10133/// \param OldD The old declaration.
10134/// \param NewT The portion of the type of the new declaration to check.
10135/// \param OldT The portion of the type of the old declaration to check.
10136bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
10137 QualType NewT, QualType OldT) {
10138 if (!NewD->getLexicalDeclContext()->isDependentContext())
10139 return true;
10140
10141 // For dependently-typed local extern declarations and friends, we can't
10142 // perform a correct type check in general until instantiation:
10143 //
10144 // int f();
10145 // template<typename T> void g() { T f(); }
10146 //
10147 // (valid if g() is only instantiated with T = int).
10148 if (NewT->isDependentType() &&
10149 (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10150 return false;
10151
10152 // Similarly, if the previous declaration was a dependent local extern
10153 // declaration, we don't really know its type yet.
10154 if (OldT->isDependentType() && OldD->isLocalExternDecl())
10155 return false;
10156
10157 return true;
10158}
10159
10160/// Checks if the new declaration declared in dependent context must be
10161/// put in the same redeclaration chain as the specified declaration.
10162///
10163/// \param D Declaration that is checked.
10164/// \param PrevDecl Previous declaration found with proper lookup method for the
10165/// same declaration name.
10166/// \returns True if D must be added to the redeclaration chain which PrevDecl
10167/// belongs to.
10168///
10169bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
10170 if (!D->getLexicalDeclContext()->isDependentContext())
10171 return true;
10172
10173 // Don't chain dependent friend function definitions until instantiation, to
10174 // permit cases like
10175 //
10176 // void func();
10177 // template<typename T> class C1 { friend void func() {} };
10178 // template<typename T> class C2 { friend void func() {} };
10179 //
10180 // ... which is valid if only one of C1 and C2 is ever instantiated.
10181 //
10182 // FIXME: This need only apply to function definitions. For now, we proxy
10183 // this by checking for a file-scope function. We do not want this to apply
10184 // to friend declarations nominating member functions, because that gets in
10185 // the way of access checks.
10186 if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10187 return false;
10188
10189 auto *VD = dyn_cast<ValueDecl>(D);
10190 auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10191 return !VD || !PrevVD ||
10192 canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10193 PrevVD->getType());
10194}
10195
10196/// Check the target attribute of the function for MultiVersion
10197/// validity.
10198///
10199/// Returns true if there was an error, false otherwise.
10200static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10201 const auto *TA = FD->getAttr<TargetAttr>();
10202 assert(TA && "MultiVersion Candidate requires a target attribute")((void)0);
10203 ParsedTargetAttr ParseInfo = TA->parse();
10204 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
10205 enum ErrType { Feature = 0, Architecture = 1 };
10206
10207 if (!ParseInfo.Architecture.empty() &&
10208 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10209 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10210 << Architecture << ParseInfo.Architecture;
10211 return true;
10212 }
10213
10214 for (const auto &Feat : ParseInfo.Features) {
10215 auto BareFeat = StringRef{Feat}.substr(1);
10216 if (Feat[0] == '-') {
10217 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10218 << Feature << ("no-" + BareFeat).str();
10219 return true;
10220 }
10221
10222 if (!TargetInfo.validateCpuSupports(BareFeat) ||
10223 !TargetInfo.isValidFeatureName(BareFeat)) {
10224 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10225 << Feature << BareFeat;
10226 return true;
10227 }
10228 }
10229 return false;
10230}
10231
10232// Provide a white-list of attributes that are allowed to be combined with
10233// multiversion functions.
10234static bool AttrCompatibleWithMultiVersion(attr::Kind Kind,
10235 MultiVersionKind MVType) {
10236 // Note: this list/diagnosis must match the list in
10237 // checkMultiversionAttributesAllSame.
10238 switch (Kind) {
10239 default:
10240 return false;
10241 case attr::Used:
10242 return MVType == MultiVersionKind::Target;
10243 case attr::NonNull:
10244 case attr::NoThrow:
10245 return true;
10246 }
10247}
10248
10249static bool checkNonMultiVersionCompatAttributes(Sema &S,
10250 const FunctionDecl *FD,
10251 const FunctionDecl *CausedFD,
10252 MultiVersionKind MVType) {
10253 bool IsCPUSpecificCPUDispatchMVType =
10254 MVType == MultiVersionKind::CPUDispatch ||
10255 MVType == MultiVersionKind::CPUSpecific;
10256 const auto Diagnose = [FD, CausedFD, IsCPUSpecificCPUDispatchMVType](
10257 Sema &S, const Attr *A) {
10258 S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10259 << IsCPUSpecificCPUDispatchMVType << A;
10260 if (CausedFD)
10261 S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10262 return true;
10263 };
10264
10265 for (const Attr *A : FD->attrs()) {
10266 switch (A->getKind()) {
10267 case attr::CPUDispatch:
10268 case attr::CPUSpecific:
10269 if (MVType != MultiVersionKind::CPUDispatch &&
10270 MVType != MultiVersionKind::CPUSpecific)
10271 return Diagnose(S, A);
10272 break;
10273 case attr::Target:
10274 if (MVType != MultiVersionKind::Target)
10275 return Diagnose(S, A);
10276 break;
10277 default:
10278 if (!AttrCompatibleWithMultiVersion(A->getKind(), MVType))
10279 return Diagnose(S, A);
10280 break;
10281 }
10282 }
10283 return false;
10284}
10285
10286bool Sema::areMultiversionVariantFunctionsCompatible(
10287 const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10288 const PartialDiagnostic &NoProtoDiagID,
10289 const PartialDiagnosticAt &NoteCausedDiagIDAt,
10290 const PartialDiagnosticAt &NoSupportDiagIDAt,
10291 const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10292 bool ConstexprSupported, bool CLinkageMayDiffer) {
10293 enum DoesntSupport {
10294 FuncTemplates = 0,
10295 VirtFuncs = 1,
10296 DeducedReturn = 2,
10297 Constructors = 3,
10298 Destructors = 4,
10299 DeletedFuncs = 5,
10300 DefaultedFuncs = 6,
10301 ConstexprFuncs = 7,
10302 ConstevalFuncs = 8,
10303 };
10304 enum Different {
10305 CallingConv = 0,
10306 ReturnType = 1,
10307 ConstexprSpec = 2,
10308 InlineSpec = 3,
10309 StorageClass = 4,
10310 Linkage = 5,
10311 };
10312
10313 if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10314 !OldFD->getType()->getAs<FunctionProtoType>()) {
10315 Diag(OldFD->getLocation(), NoProtoDiagID);
10316 Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10317 return true;
10318 }
10319
10320 if (NoProtoDiagID.getDiagID() != 0 &&
10321 !NewFD->getType()->getAs<FunctionProtoType>())
10322 return Diag(NewFD->getLocation(), NoProtoDiagID);
10323
10324 if (!TemplatesSupported &&
10325 NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
10326 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10327 << FuncTemplates;
10328
10329 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10330 if (NewCXXFD->isVirtual())
10331 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10332 << VirtFuncs;
10333
10334 if (isa<CXXConstructorDecl>(NewCXXFD))
10335 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10336 << Constructors;
10337
10338 if (isa<CXXDestructorDecl>(NewCXXFD))
10339 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10340 << Destructors;
10341 }
10342
10343 if (NewFD->isDeleted())
10344 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10345 << DeletedFuncs;
10346
10347 if (NewFD->isDefaulted())
10348 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10349 << DefaultedFuncs;
10350
10351 if (!ConstexprSupported && NewFD->isConstexpr())
10352 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10353 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10354
10355 QualType NewQType = Context.getCanonicalType(NewFD->getType());
10356 const auto *NewType = cast<FunctionType>(NewQType);
10357 QualType NewReturnType = NewType->getReturnType();
10358
10359 if (NewReturnType->isUndeducedType())
10360 return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10361 << DeducedReturn;
10362
10363 // Ensure the return type is identical.
10364 if (OldFD) {
10365 QualType OldQType = Context.getCanonicalType(OldFD->getType());
10366 const auto *OldType = cast<FunctionType>(OldQType);
10367 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10368 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10369
10370 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10371 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10372
10373 QualType OldReturnType = OldType->getReturnType();
10374
10375 if (OldReturnType != NewReturnType)
10376 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10377
10378 if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10379 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10380
10381 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10382 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10383
10384 if (OldFD->getStorageClass() != NewFD->getStorageClass())
10385 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << StorageClass;
10386
10387 if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10388 return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10389
10390 if (CheckEquivalentExceptionSpec(
10391 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10392 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10393 return true;
10394 }
10395 return false;
10396}
10397
10398static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
10399 const FunctionDecl *NewFD,
10400 bool CausesMV,
10401 MultiVersionKind MVType) {
10402 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10403 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10404 if (OldFD)
10405 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10406 return true;
10407 }
10408
10409 bool IsCPUSpecificCPUDispatchMVType =
10410 MVType == MultiVersionKind::CPUDispatch ||
10411 MVType == MultiVersionKind::CPUSpecific;
10412
10413 if (CausesMV && OldFD &&
10414 checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVType))
10415 return true;
10416
10417 if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVType))
10418 return true;
10419
10420 // Only allow transition to MultiVersion if it hasn't been used.
10421 if (OldFD && CausesMV && OldFD->isUsed(false))
10422 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10423
10424 return S.areMultiversionVariantFunctionsCompatible(
10425 OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10426 PartialDiagnosticAt(NewFD->getLocation(),
10427 S.PDiag(diag::note_multiversioning_caused_here)),
10428 PartialDiagnosticAt(NewFD->getLocation(),
10429 S.PDiag(diag::err_multiversion_doesnt_support)
10430 << IsCPUSpecificCPUDispatchMVType),
10431 PartialDiagnosticAt(NewFD->getLocation(),
10432 S.PDiag(diag::err_multiversion_diff)),
10433 /*TemplatesSupported=*/false,
10434 /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVType,
10435 /*CLinkageMayDiffer=*/false);
10436}
10437
10438/// Check the validity of a multiversion function declaration that is the
10439/// first of its kind. Also sets the multiversion'ness' of the function itself.
10440///
10441/// This sets NewFD->isInvalidDecl() to true if there was an error.
10442///
10443/// Returns true if there was an error, false otherwise.
10444static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD,
10445 MultiVersionKind MVType,
10446 const TargetAttr *TA) {
10447 assert(MVType != MultiVersionKind::None &&((void)0)
10448 "Function lacks multiversion attribute")((void)0);
10449
10450 // Target only causes MV if it is default, otherwise this is a normal
10451 // function.
10452 if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
10453 return false;
10454
10455 if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10456 FD->setInvalidDecl();
10457 return true;
10458 }
10459
10460 if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVType)) {
10461 FD->setInvalidDecl();
10462 return true;
10463 }
10464
10465 FD->setIsMultiVersion();
10466 return false;
10467}
10468
10469static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
10470 for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10471 if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
10472 return true;
10473 }
10474
10475 return false;
10476}
10477
10478static bool CheckTargetCausesMultiVersioning(
10479 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10480 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10481 LookupResult &Previous) {
10482 const auto *OldTA = OldFD->getAttr<TargetAttr>();
10483 ParsedTargetAttr NewParsed = NewTA->parse();
10484 // Sort order doesn't matter, it just needs to be consistent.
10485 llvm::sort(NewParsed.Features);
10486
10487 // If the old decl is NOT MultiVersioned yet, and we don't cause that
10488 // to change, this is a simple redeclaration.
10489 if (!NewTA->isDefaultVersion() &&
10490 (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10491 return false;
10492
10493 // Otherwise, this decl causes MultiVersioning.
10494 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
10495 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10496 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10497 NewFD->setInvalidDecl();
10498 return true;
10499 }
10500
10501 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10502 MultiVersionKind::Target)) {
10503 NewFD->setInvalidDecl();
10504 return true;
10505 }
10506
10507 if (CheckMultiVersionValue(S, NewFD)) {
10508 NewFD->setInvalidDecl();
10509 return true;
10510 }
10511
10512 // If this is 'default', permit the forward declaration.
10513 if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10514 Redeclaration = true;
10515 OldDecl = OldFD;
10516 OldFD->setIsMultiVersion();
10517 NewFD->setIsMultiVersion();
10518 return false;
10519 }
10520
10521 if (CheckMultiVersionValue(S, OldFD)) {
10522 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10523 NewFD->setInvalidDecl();
10524 return true;
10525 }
10526
10527 ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10528
10529 if (OldParsed == NewParsed) {
10530 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10531 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10532 NewFD->setInvalidDecl();
10533 return true;
10534 }
10535
10536 for (const auto *FD : OldFD->redecls()) {
10537 const auto *CurTA = FD->getAttr<TargetAttr>();
10538 // We allow forward declarations before ANY multiversioning attributes, but
10539 // nothing after the fact.
10540 if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
10541 (!CurTA || CurTA->isInherited())) {
10542 S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10543 << 0;
10544 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10545 NewFD->setInvalidDecl();
10546 return true;
10547 }
10548 }
10549
10550 OldFD->setIsMultiVersion();
10551 NewFD->setIsMultiVersion();
10552 Redeclaration = false;
10553 MergeTypeWithPrevious = false;
10554 OldDecl = nullptr;
10555 Previous.clear();
10556 return false;
10557}
10558
10559/// Check the validity of a new function declaration being added to an existing
10560/// multiversioned declaration collection.
10561static bool CheckMultiVersionAdditionalDecl(
10562 Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10563 MultiVersionKind NewMVType, const TargetAttr *NewTA,
10564 const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10565 bool &Redeclaration, NamedDecl *&OldDecl, bool &MergeTypeWithPrevious,
10566 LookupResult &Previous) {
10567
10568 MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
10569 // Disallow mixing of multiversioning types.
10570 if ((OldMVType == MultiVersionKind::Target &&
10571 NewMVType != MultiVersionKind::Target) ||
10572 (NewMVType == MultiVersionKind::Target &&
10573 OldMVType != MultiVersionKind::Target)) {
10574 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10575 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10576 NewFD->setInvalidDecl();
10577 return true;
10578 }
10579
10580 ParsedTargetAttr NewParsed;
10581 if (NewTA) {
10582 NewParsed = NewTA->parse();
10583 llvm::sort(NewParsed.Features);
10584 }
10585
10586 bool UseMemberUsingDeclRules =
10587 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10588
10589 // Next, check ALL non-overloads to see if this is a redeclaration of a
10590 // previous member of the MultiVersion set.
10591 for (NamedDecl *ND : Previous) {
10592 FunctionDecl *CurFD = ND->getAsFunction();
10593 if (!CurFD)
10594 continue;
10595 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10596 continue;
10597
10598 if (NewMVType == MultiVersionKind::Target) {
10599 const auto *CurTA = CurFD->getAttr<TargetAttr>();
10600 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10601 NewFD->setIsMultiVersion();
10602 Redeclaration = true;
10603 OldDecl = ND;
10604 return false;
10605 }
10606
10607 ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10608 if (CurParsed == NewParsed) {
10609 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10610 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10611 NewFD->setInvalidDecl();
10612 return true;
10613 }
10614 } else {
10615 const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10616 const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10617 // Handle CPUDispatch/CPUSpecific versions.
10618 // Only 1 CPUDispatch function is allowed, this will make it go through
10619 // the redeclaration errors.
10620 if (NewMVType == MultiVersionKind::CPUDispatch &&
10621 CurFD->hasAttr<CPUDispatchAttr>()) {
10622 if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10623 std::equal(
10624 CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10625 NewCPUDisp->cpus_begin(),
10626 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10627 return Cur->getName() == New->getName();
10628 })) {
10629 NewFD->setIsMultiVersion();
10630 Redeclaration = true;
10631 OldDecl = ND;
10632 return false;
10633 }
10634
10635 // If the declarations don't match, this is an error condition.
10636 S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10637 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10638 NewFD->setInvalidDecl();
10639 return true;
10640 }
10641 if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10642
10643 if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10644 std::equal(
10645 CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10646 NewCPUSpec->cpus_begin(),
10647 [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10648 return Cur->getName() == New->getName();
10649 })) {
10650 NewFD->setIsMultiVersion();
10651 Redeclaration = true;
10652 OldDecl = ND;
10653 return false;
10654 }
10655
10656 // Only 1 version of CPUSpecific is allowed for each CPU.
10657 for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10658 for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10659 if (CurII == NewII) {
10660 S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10661 << NewII;
10662 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10663 NewFD->setInvalidDecl();
10664 return true;
10665 }
10666 }
10667 }
10668 }
10669 // If the two decls aren't the same MVType, there is no possible error
10670 // condition.
10671 }
10672 }
10673
10674 // Else, this is simply a non-redecl case. Checking the 'value' is only
10675 // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10676 // handled in the attribute adding step.
10677 if (NewMVType == MultiVersionKind::Target &&
10678 CheckMultiVersionValue(S, NewFD)) {
10679 NewFD->setInvalidDecl();
10680 return true;
10681 }
10682
10683 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10684 !OldFD->isMultiVersion(), NewMVType)) {
10685 NewFD->setInvalidDecl();
10686 return true;
10687 }
10688
10689 // Permit forward declarations in the case where these two are compatible.
10690 if (!OldFD->isMultiVersion()) {
10691 OldFD->setIsMultiVersion();
10692 NewFD->setIsMultiVersion();
10693 Redeclaration = true;
10694 OldDecl = OldFD;
10695 return false;
10696 }
10697
10698 NewFD->setIsMultiVersion();
10699 Redeclaration = false;
10700 MergeTypeWithPrevious = false;
10701 OldDecl = nullptr;
10702 Previous.clear();
10703 return false;
10704}
10705
10706
10707/// Check the validity of a mulitversion function declaration.
10708/// Also sets the multiversion'ness' of the function itself.
10709///
10710/// This sets NewFD->isInvalidDecl() to true if there was an error.
10711///
10712/// Returns true if there was an error, false otherwise.
10713static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
10714 bool &Redeclaration, NamedDecl *&OldDecl,
10715 bool &MergeTypeWithPrevious,
10716 LookupResult &Previous) {
10717 const auto *NewTA = NewFD->getAttr<TargetAttr>();
10718 const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10719 const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10720
10721 // Mixing Multiversioning types is prohibited.
10722 if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
10723 (NewCPUDisp && NewCPUSpec)) {
10724 S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10725 NewFD->setInvalidDecl();
10726 return true;
10727 }
10728
10729 MultiVersionKind MVType = NewFD->getMultiVersionKind();
10730
10731 // Main isn't allowed to become a multiversion function, however it IS
10732 // permitted to have 'main' be marked with the 'target' optimization hint.
10733 if (NewFD->isMain()) {
10734 if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
10735 MVType == MultiVersionKind::CPUDispatch ||
10736 MVType == MultiVersionKind::CPUSpecific) {
10737 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10738 NewFD->setInvalidDecl();
10739 return true;
10740 }
10741 return false;
10742 }
10743
10744 if (!OldDecl || !OldDecl->getAsFunction() ||
10745 OldDecl->getDeclContext()->getRedeclContext() !=
10746 NewFD->getDeclContext()->getRedeclContext()) {
10747 // If there's no previous declaration, AND this isn't attempting to cause
10748 // multiversioning, this isn't an error condition.
10749 if (MVType == MultiVersionKind::None)
10750 return false;
10751 return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA);
10752 }
10753
10754 FunctionDecl *OldFD = OldDecl->getAsFunction();
10755
10756 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
10757 return false;
10758
10759 if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
10760 S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10761 << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
10762 NewFD->setInvalidDecl();
10763 return true;
10764 }
10765
10766 // Handle the target potentially causes multiversioning case.
10767 if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
10768 return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10769 Redeclaration, OldDecl,
10770 MergeTypeWithPrevious, Previous);
10771
10772 // At this point, we have a multiversion function decl (in OldFD) AND an
10773 // appropriate attribute in the current function decl. Resolve that these are
10774 // still compatible with previous declarations.
10775 return CheckMultiVersionAdditionalDecl(
10776 S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
10777 OldDecl, MergeTypeWithPrevious, Previous);
10778}
10779
10780/// Perform semantic checking of a new function declaration.
10781///
10782/// Performs semantic analysis of the new function declaration
10783/// NewFD. This routine performs all semantic checking that does not
10784/// require the actual declarator involved in the declaration, and is
10785/// used both for the declaration of functions as they are parsed
10786/// (called via ActOnDeclarator) and for the declaration of functions
10787/// that have been instantiated via C++ template instantiation (called
10788/// via InstantiateDecl).
10789///
10790/// \param IsMemberSpecialization whether this new function declaration is
10791/// a member specialization (that replaces any definition provided by the
10792/// previous declaration).
10793///
10794/// This sets NewFD->isInvalidDecl() to true if there was an error.
10795///
10796/// \returns true if the function declaration is a redeclaration.
10797bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
10798 LookupResult &Previous,
10799 bool IsMemberSpecialization) {
10800 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&((void)0)
10801 "Variably modified return types are not handled here")((void)0);
10802
10803 // Determine whether the type of this function should be merged with
10804 // a previous visible declaration. This never happens for functions in C++,
10805 // and always happens in C if the previous declaration was visible.
10806 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
10807 !Previous.isShadowed();
10808
10809 bool Redeclaration = false;
10810 NamedDecl *OldDecl = nullptr;
10811 bool MayNeedOverloadableChecks = false;
10812
10813 // Merge or overload the declaration with an existing declaration of
10814 // the same name, if appropriate.
10815 if (!Previous.empty()) {
10816 // Determine whether NewFD is an overload of PrevDecl or
10817 // a declaration that requires merging. If it's an overload,
10818 // there's no more work to do here; we'll just add the new
10819 // function to the scope.
10820 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
10821 NamedDecl *Candidate = Previous.getRepresentativeDecl();
10822 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
10823 Redeclaration = true;
10824 OldDecl = Candidate;
10825 }
10826 } else {
10827 MayNeedOverloadableChecks = true;
10828 switch (CheckOverload(S, NewFD, Previous, OldDecl,
10829 /*NewIsUsingDecl*/ false)) {
10830 case Ovl_Match:
10831 Redeclaration = true;
10832 break;
10833
10834 case Ovl_NonFunction:
10835 Redeclaration = true;
10836 break;
10837
10838 case Ovl_Overload:
10839 Redeclaration = false;
10840 break;
10841 }
10842 }
10843 }
10844
10845 // Check for a previous extern "C" declaration with this name.
10846 if (!Redeclaration &&
10847 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
10848 if (!Previous.empty()) {
10849 // This is an extern "C" declaration with the same name as a previous
10850 // declaration, and thus redeclares that entity...
10851 Redeclaration = true;
10852 OldDecl = Previous.getFoundDecl();
10853 MergeTypeWithPrevious = false;
10854
10855 // ... except in the presence of __attribute__((overloadable)).
10856 if (OldDecl->hasAttr<OverloadableAttr>() ||
10857 NewFD->hasAttr<OverloadableAttr>()) {
10858 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10859 MayNeedOverloadableChecks = true;
10860 Redeclaration = false;
10861 OldDecl = nullptr;
10862 }
10863 }
10864 }
10865 }
10866
10867 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
10868 MergeTypeWithPrevious, Previous))
10869 return Redeclaration;
10870
10871 // PPC MMA non-pointer types are not allowed as function return types.
10872 if (Context.getTargetInfo().getTriple().isPPC64() &&
10873 CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
10874 NewFD->setInvalidDecl();
10875 }
10876
10877 // C++11 [dcl.constexpr]p8:
10878 // A constexpr specifier for a non-static member function that is not
10879 // a constructor declares that member function to be const.
10880 //
10881 // This needs to be delayed until we know whether this is an out-of-line
10882 // definition of a static member function.
10883 //
10884 // This rule is not present in C++1y, so we produce a backwards
10885 // compatibility warning whenever it happens in C++11.
10886 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10887 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10888 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10889 !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
10890 CXXMethodDecl *OldMD = nullptr;
10891 if (OldDecl)
10892 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10893 if (!OldMD || !OldMD->isStatic()) {
10894 const FunctionProtoType *FPT =
10895 MD->getType()->castAs<FunctionProtoType>();
10896 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10897 EPI.TypeQuals.addConst();
10898 MD->setType(Context.getFunctionType(FPT->getReturnType(),
10899 FPT->getParamTypes(), EPI));
10900
10901 // Warn that we did this, if we're not performing template instantiation.
10902 // In that case, we'll have warned already when the template was defined.
10903 if (!inTemplateInstantiation()) {
10904 SourceLocation AddConstLoc;
10905 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10906 .IgnoreParens().getAs<FunctionTypeLoc>())
10907 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10908
10909 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10910 << FixItHint::CreateInsertion(AddConstLoc, " const");
10911 }
10912 }
10913 }
10914
10915 if (Redeclaration) {
10916 // NewFD and OldDecl represent declarations that need to be
10917 // merged.
10918 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
10919 NewFD->setInvalidDecl();
10920 return Redeclaration;
10921 }
10922
10923 Previous.clear();
10924 Previous.addDecl(OldDecl);
10925
10926 if (FunctionTemplateDecl *OldTemplateDecl =
10927 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10928 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10929 FunctionTemplateDecl *NewTemplateDecl
10930 = NewFD->getDescribedFunctionTemplate();
10931 assert(NewTemplateDecl && "Template/non-template mismatch")((void)0);
10932
10933 // The call to MergeFunctionDecl above may have created some state in
10934 // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10935 // can add it as a redeclaration.
10936 NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10937
10938 NewFD->setPreviousDeclaration(OldFD);
10939 if (NewFD->isCXXClassMember()) {
10940 NewFD->setAccess(OldTemplateDecl->getAccess());
10941 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10942 }
10943
10944 // If this is an explicit specialization of a member that is a function
10945 // template, mark it as a member specialization.
10946 if (IsMemberSpecialization &&
10947 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10948 NewTemplateDecl->setMemberSpecialization();
10949 assert(OldTemplateDecl->isMemberSpecialization())((void)0);
10950 // Explicit specializations of a member template do not inherit deleted
10951 // status from the parent member template that they are specializing.
10952 if (OldFD->isDeleted()) {
10953 // FIXME: This assert will not hold in the presence of modules.
10954 assert(OldFD->getCanonicalDecl() == OldFD)((void)0);
10955 // FIXME: We need an update record for this AST mutation.
10956 OldFD->setDeletedAsWritten(false);
10957 }
10958 }
10959
10960 } else {
10961 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
10962 auto *OldFD = cast<FunctionDecl>(OldDecl);
10963 // This needs to happen first so that 'inline' propagates.
10964 NewFD->setPreviousDeclaration(OldFD);
10965 if (NewFD->isCXXClassMember())
10966 NewFD->setAccess(OldFD->getAccess());
10967 }
10968 }
10969 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10970 !NewFD->getAttr<OverloadableAttr>()) {
10971 assert((Previous.empty() ||((void)0)
10972 llvm::any_of(Previous,((void)0)
10973 [](const NamedDecl *ND) {((void)0)
10974 return ND->hasAttr<OverloadableAttr>();((void)0)
10975 })) &&((void)0)
10976 "Non-redecls shouldn't happen without overloadable present")((void)0);
10977
10978 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10979 const auto *FD = dyn_cast<FunctionDecl>(ND);
10980 return FD && !FD->hasAttr<OverloadableAttr>();
10981 });
10982
10983 if (OtherUnmarkedIter != Previous.end()) {
10984 Diag(NewFD->getLocation(),
10985 diag::err_attribute_overloadable_multiple_unmarked_overloads);
10986 Diag((*OtherUnmarkedIter)->getLocation(),
10987 diag::note_attribute_overloadable_prev_overload)
10988 << false;
10989
10990 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10991 }
10992 }
10993
10994 if (LangOpts.OpenMP)
10995 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
10996
10997 // Semantic checking for this function declaration (in isolation).
10998
10999 if (getLangOpts().CPlusPlus) {
11000 // C++-specific checks.
11001 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11002 CheckConstructor(Constructor);
11003 } else if (CXXDestructorDecl *Destructor =
11004 dyn_cast<CXXDestructorDecl>(NewFD)) {
11005 CXXRecordDecl *Record = Destructor->getParent();
11006 QualType ClassType = Context.getTypeDeclType(Record);
11007
11008 // FIXME: Shouldn't we be able to perform this check even when the class
11009 // type is dependent? Both gcc and edg can handle that.
11010 if (!ClassType->isDependentType()) {
11011 DeclarationName Name
11012 = Context.DeclarationNames.getCXXDestructorName(
11013 Context.getCanonicalType(ClassType));
11014 if (NewFD->getDeclName() != Name) {
11015 Diag(NewFD->getLocation(), diag::err_destructor_name);
11016 NewFD->setInvalidDecl();
11017 return Redeclaration;
11018 }
11019 }
11020 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11021 if (auto *TD = Guide->getDescribedFunctionTemplate())
11022 CheckDeductionGuideTemplate(TD);
11023
11024 // A deduction guide is not on the list of entities that can be
11025 // explicitly specialized.
11026 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11027 Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11028 << /*explicit specialization*/ 1;
11029 }
11030
11031 // Find any virtual functions that this function overrides.
11032 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11033 if (!Method->isFunctionTemplateSpecialization() &&
11034 !Method->getDescribedFunctionTemplate() &&
11035 Method->isCanonicalDecl()) {
11036 AddOverriddenMethods(Method->getParent(), Method);
11037 }
11038 if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11039 // C++2a [class.virtual]p6
11040 // A virtual method shall not have a requires-clause.
11041 Diag(NewFD->getTrailingRequiresClause()->getBeginLoc(),
11042 diag::err_constrained_virtual_method);
11043
11044 if (Method->isStatic())
11045 checkThisInStaticMemberFunctionType(Method);
11046 }
11047
11048 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11049 ActOnConversionDeclarator(Conversion);
11050
11051 // Extra checking for C++ overloaded operators (C++ [over.oper]).
11052 if (NewFD->isOverloadedOperator() &&
11053 CheckOverloadedOperatorDeclaration(NewFD)) {
11054 NewFD->setInvalidDecl();
11055 return Redeclaration;
11056 }
11057
11058 // Extra checking for C++0x literal operators (C++0x [over.literal]).
11059 if (NewFD->getLiteralIdentifier() &&
11060 CheckLiteralOperatorDeclaration(NewFD)) {
11061 NewFD->setInvalidDecl();
11062 return Redeclaration;
11063 }
11064
11065 // In C++, check default arguments now that we have merged decls. Unless
11066 // the lexical context is the class, because in this case this is done
11067 // during delayed parsing anyway.
11068 if (!CurContext->isRecord())
11069 CheckCXXDefaultArguments(NewFD);
11070
11071 // If this function is declared as being extern "C", then check to see if
11072 // the function returns a UDT (class, struct, or union type) that is not C
11073 // compatible, and if it does, warn the user.
11074 // But, issue any diagnostic on the first declaration only.
11075 if (Previous.empty() && NewFD->isExternC()) {
11076 QualType R = NewFD->getReturnType();
11077 if (R->isIncompleteType() && !R->isVoidType())
11078 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11079 << NewFD << R;
11080 else if (!R.isPODType(Context) && !R->isVoidType() &&
11081 !R->isObjCObjectPointerType())
11082 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11083 }
11084
11085 // C++1z [dcl.fct]p6:
11086 // [...] whether the function has a non-throwing exception-specification
11087 // [is] part of the function type
11088 //
11089 // This results in an ABI break between C++14 and C++17 for functions whose
11090 // declared type includes an exception-specification in a parameter or
11091 // return type. (Exception specifications on the function itself are OK in
11092 // most cases, and exception specifications are not permitted in most other
11093 // contexts where they could make it into a mangling.)
11094 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11095 auto HasNoexcept = [&](QualType T) -> bool {
11096 // Strip off declarator chunks that could be between us and a function
11097 // type. We don't need to look far, exception specifications are very
11098 // restricted prior to C++17.
11099 if (auto *RT = T->getAs<ReferenceType>())
11100 T = RT->getPointeeType();
11101 else if (T->isAnyPointerType())
11102 T = T->getPointeeType();
11103 else if (auto *MPT = T->getAs<MemberPointerType>())
11104 T = MPT->getPointeeType();
11105 if (auto *FPT = T->getAs<FunctionProtoType>())
11106 if (FPT->isNothrow())
11107 return true;
11108 return false;
11109 };
11110
11111 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11112 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11113 for (QualType T : FPT->param_types())
11114 AnyNoexcept |= HasNoexcept(T);
11115 if (AnyNoexcept)
11116 Diag(NewFD->getLocation(),
11117 diag::warn_cxx17_compat_exception_spec_in_signature)
11118 << NewFD;
11119 }
11120
11121 if (!Redeclaration && LangOpts.CUDA)
11122 checkCUDATargetOverload(NewFD, Previous);
11123 }
11124 return Redeclaration;
11125}
11126
11127void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11128 // C++11 [basic.start.main]p3:
11129 // A program that [...] declares main to be inline, static or
11130 // constexpr is ill-formed.
11131 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11132 // appear in a declaration of main.
11133 // static main is not an error under C99, but we should warn about it.
11134 // We accept _Noreturn main as an extension.
11135 if (FD->getStorageClass() == SC_Static)
11136 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11137 ? diag::err_static_main : diag::warn_static_main)
11138 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11139 if (FD->isInlineSpecified())
11140 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11141 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
11142 if (DS.isNoreturnSpecified()) {
11143 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11144 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11145 Diag(NoreturnLoc, diag::ext_noreturn_main);
11146 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11147 << FixItHint::CreateRemoval(NoreturnRange);
11148 }
11149 if (FD->isConstexpr()) {
11150 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11151 << FD->isConsteval()
11152 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
11153 FD->setConstexprKind(ConstexprSpecKind::Unspecified);
11154 }
11155
11156 if (getLangOpts().OpenCL) {
11157 Diag(FD->getLocation(), diag::err_opencl_no_main)
11158 << FD->hasAttr<OpenCLKernelAttr>();
11159 FD->setInvalidDecl();
11160 return;
11161 }
11162
11163 QualType T = FD->getType();
11164 assert(T->isFunctionType() && "function decl is not of function type")((void)0);
11165 const FunctionType* FT = T->castAs<FunctionType>();
11166
11167 // Set default calling convention for main()
11168 if (FT->getCallConv() != CC_C) {
11169 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11170 FD->setType(QualType(FT, 0));
11171 T = Context.getCanonicalType(FD->getType());
11172 }
11173
11174 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11175 // In C with GNU extensions we allow main() to have non-integer return
11176 // type, but we should warn about the extension, and we disable the
11177 // implicit-return-zero rule.
11178
11179 // GCC in C mode accepts qualified 'int'.
11180 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11181 FD->setHasImplicitReturnZero(true);
11182 else {
11183 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11184 SourceRange RTRange = FD->getReturnTypeSourceRange();
11185 if (RTRange.isValid())
11186 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11187 << FixItHint::CreateReplacement(RTRange, "int");
11188 }
11189 } else {
11190 // In C and C++, main magically returns 0 if you fall off the end;
11191 // set the flag which tells us that.
11192 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11193
11194 // All the standards say that main() should return 'int'.
11195 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11196 FD->setHasImplicitReturnZero(true);
11197 else {
11198 // Otherwise, this is just a flat-out error.
11199 SourceRange RTRange = FD->getReturnTypeSourceRange();
11200 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11201 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11202 : FixItHint());
11203 FD->setInvalidDecl(true);
11204 }
11205 }
11206
11207 // Treat protoless main() as nullary.
11208 if (isa<FunctionNoProtoType>(FT)) return;
11209
11210 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11211 unsigned nparams = FTP->getNumParams();
11212 assert(FD->getNumParams() == nparams)((void)0);
11213
11214 bool HasExtraParameters = (nparams > 3);
11215
11216 if (FTP->isVariadic()) {
11217 Diag(FD->getLocation(), diag::ext_variadic_main);
11218 // FIXME: if we had information about the location of the ellipsis, we
11219 // could add a FixIt hint to remove it as a parameter.
11220 }
11221
11222 // Darwin passes an undocumented fourth argument of type char**. If
11223 // other platforms start sprouting these, the logic below will start
11224 // getting shifty.
11225 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11226 HasExtraParameters = false;
11227
11228 if (HasExtraParameters) {
11229 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11230 FD->setInvalidDecl(true);
11231 nparams = 3;
11232 }
11233
11234 // FIXME: a lot of the following diagnostics would be improved
11235 // if we had some location information about types.
11236
11237 QualType CharPP =
11238 Context.getPointerType(Context.getPointerType(Context.CharTy));
11239 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11240
11241 for (unsigned i = 0; i < nparams; ++i) {
11242 QualType AT = FTP->getParamType(i);
11243
11244 bool mismatch = true;
11245
11246 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11247 mismatch = false;
11248 else if (Expected[i] == CharPP) {
11249 // As an extension, the following forms are okay:
11250 // char const **
11251 // char const * const *
11252 // char * const *
11253
11254 QualifierCollector qs;
11255 const PointerType* PT;
11256 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11257 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11258 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11259 Context.CharTy)) {
11260 qs.removeConst();
11261 mismatch = !qs.empty();
11262 }
11263 }
11264
11265 if (mismatch) {
11266 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11267 // TODO: suggest replacing given type with expected type
11268 FD->setInvalidDecl(true);
11269 }
11270 }
11271
11272 if (nparams == 1 && !FD->isInvalidDecl()) {
11273 Diag(FD->getLocation(), diag::warn_main_one_arg);
11274 }
11275
11276 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11277 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11278 FD->setInvalidDecl();
11279 }
11280}
11281
11282static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11283
11284 // Default calling convention for main and wmain is __cdecl
11285 if (FD->getName() == "main" || FD->getName() == "wmain")
11286 return false;
11287
11288 // Default calling convention for MinGW is __cdecl
11289 const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11290 if (T.isWindowsGNUEnvironment())
11291 return false;
11292
11293 // Default calling convention for WinMain, wWinMain and DllMain
11294 // is __stdcall on 32 bit Windows
11295 if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11296 return true;
11297
11298 return false;
11299}
11300
11301void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
11302 QualType T = FD->getType();
11303 assert(T->isFunctionType() && "function decl is not of function type")((void)0);
11304 const FunctionType *FT = T->castAs<FunctionType>();
11305
11306 // Set an implicit return of 'zero' if the function can return some integral,
11307 // enumeration, pointer or nullptr type.
11308 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
11309 FT->getReturnType()->isAnyPointerType() ||
11310 FT->getReturnType()->isNullPtrType())
11311 // DllMain is exempt because a return value of zero means it failed.
11312 if (FD->getName() != "DllMain")
11313 FD->setHasImplicitReturnZero(true);
11314
11315 // Explicity specified calling conventions are applied to MSVC entry points
11316 if (!hasExplicitCallingConv(T)) {
11317 if (isDefaultStdCall(FD, *this)) {
11318 if (FT->getCallConv() != CC_X86StdCall) {
11319 FT = Context.adjustFunctionType(
11320 FT, FT->getExtInfo().withCallingConv(CC_X86StdCall));
11321 FD->setType(QualType(FT, 0));
11322 }
11323 } else if (FT->getCallConv() != CC_C) {
11324 FT = Context.adjustFunctionType(FT,
11325 FT->getExtInfo().withCallingConv(CC_C));
11326 FD->setType(QualType(FT, 0));
11327 }
11328 }
11329
11330 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11331 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11332 FD->setInvalidDecl();
11333 }
11334}
11335
11336bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
11337 // FIXME: Need strict checking. In C89, we need to check for
11338 // any assignment, increment, decrement, function-calls, or
11339 // commas outside of a sizeof. In C99, it's the same list,
11340 // except that the aforementioned are allowed in unevaluated
11341 // expressions. Everything else falls under the
11342 // "may accept other forms of constant expressions" exception.
11343 //
11344 // Regular C++ code will not end up here (exceptions: language extensions,
11345 // OpenCL C++ etc), so the constant expression rules there don't matter.
11346 if (Init->isValueDependent()) {
11347 assert(Init->containsErrors() &&((void)0)
11348 "Dependent code should only occur in error-recovery path.")((void)0);
11349 return true;
11350 }
11351 const Expr *Culprit;
11352 if (Init->isConstantInitializer(Context, false, &Culprit))
11353 return false;
11354 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11355 << Culprit->getSourceRange();
11356 return true;
11357}
11358
11359namespace {
11360 // Visits an initialization expression to see if OrigDecl is evaluated in
11361 // its own initialization and throws a warning if it does.
11362 class SelfReferenceChecker
11363 : public EvaluatedExprVisitor<SelfReferenceChecker> {
11364 Sema &S;
11365 Decl *OrigDecl;
11366 bool isRecordType;
11367 bool isPODType;
11368 bool isReferenceType;
11369
11370 bool isInitList;
11371 llvm::SmallVector<unsigned, 4> InitFieldIndex;
11372
11373 public:
11374 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
11375
11376 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11377 S(S), OrigDecl(OrigDecl) {
11378 isPODType = false;
11379 isRecordType = false;
11380 isReferenceType = false;
11381 isInitList = false;
11382 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11383 isPODType = VD->getType().isPODType(S.Context);
11384 isRecordType = VD->getType()->isRecordType();
11385 isReferenceType = VD->getType()->isReferenceType();
11386 }
11387 }
11388
11389 // For most expressions, just call the visitor. For initializer lists,
11390 // track the index of the field being initialized since fields are
11391 // initialized in order allowing use of previously initialized fields.
11392 void CheckExpr(Expr *E) {
11393 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11394 if (!InitList) {
11395 Visit(E);
11396 return;
11397 }
11398
11399 // Track and increment the index here.
11400 isInitList = true;
11401 InitFieldIndex.push_back(0);
11402 for (auto Child : InitList->children()) {
11403 CheckExpr(cast<Expr>(Child));
11404 ++InitFieldIndex.back();
11405 }
11406 InitFieldIndex.pop_back();
11407 }
11408
11409 // Returns true if MemberExpr is checked and no further checking is needed.
11410 // Returns false if additional checking is required.
11411 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11412 llvm::SmallVector<FieldDecl*, 4> Fields;
11413 Expr *Base = E;
11414 bool ReferenceField = false;
11415
11416 // Get the field members used.
11417 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11418 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11419 if (!FD)
11420 return false;
11421 Fields.push_back(FD);
11422 if (FD->getType()->isReferenceType())
11423 ReferenceField = true;
11424 Base = ME->getBase()->IgnoreParenImpCasts();
11425 }
11426
11427 // Keep checking only if the base Decl is the same.
11428 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11429 if (!DRE || DRE->getDecl() != OrigDecl)
11430 return false;
11431
11432 // A reference field can be bound to an unininitialized field.
11433 if (CheckReference && !ReferenceField)
11434 return true;
11435
11436 // Convert FieldDecls to their index number.
11437 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11438 for (const FieldDecl *I : llvm::reverse(Fields))
11439 UsedFieldIndex.push_back(I->getFieldIndex());
11440
11441 // See if a warning is needed by checking the first difference in index
11442 // numbers. If field being used has index less than the field being
11443 // initialized, then the use is safe.
11444 for (auto UsedIter = UsedFieldIndex.begin(),
11445 UsedEnd = UsedFieldIndex.end(),
11446 OrigIter = InitFieldIndex.begin(),
11447 OrigEnd = InitFieldIndex.end();
11448 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11449 if (*UsedIter < *OrigIter)
11450 return true;
11451 if (*UsedIter > *OrigIter)
11452 break;
11453 }
11454
11455 // TODO: Add a different warning which will print the field names.
11456 HandleDeclRefExpr(DRE);
11457 return true;
11458 }
11459
11460 // For most expressions, the cast is directly above the DeclRefExpr.
11461 // For conditional operators, the cast can be outside the conditional
11462 // operator if both expressions are DeclRefExpr's.
11463 void HandleValue(Expr *E) {
11464 E = E->IgnoreParens();
11465 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11466 HandleDeclRefExpr(DRE);
11467 return;
11468 }
11469
11470 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11471 Visit(CO->getCond());
11472 HandleValue(CO->getTrueExpr());
11473 HandleValue(CO->getFalseExpr());
11474 return;
11475 }
11476
11477 if (BinaryConditionalOperator *BCO =
11478 dyn_cast<BinaryConditionalOperator>(E)) {
11479 Visit(BCO->getCond());
11480 HandleValue(BCO->getFalseExpr());
11481 return;
11482 }
11483
11484 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11485 HandleValue(OVE->getSourceExpr());
11486 return;
11487 }
11488
11489 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11490 if (BO->getOpcode() == BO_Comma) {
11491 Visit(BO->getLHS());
11492 HandleValue(BO->getRHS());
11493 return;
11494 }
11495 }
11496
11497 if (isa<MemberExpr>(E)) {
11498 if (isInitList) {
11499 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11500 false /*CheckReference*/))
11501 return;
11502 }
11503
11504 Expr *Base = E->IgnoreParenImpCasts();
11505 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11506 // Check for static member variables and don't warn on them.
11507 if (!isa<FieldDecl>(ME->getMemberDecl()))
11508 return;
11509 Base = ME->getBase()->IgnoreParenImpCasts();
11510 }
11511 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11512 HandleDeclRefExpr(DRE);
11513 return;
11514 }
11515
11516 Visit(E);
11517 }
11518
11519 // Reference types not handled in HandleValue are handled here since all
11520 // uses of references are bad, not just r-value uses.
11521 void VisitDeclRefExpr(DeclRefExpr *E) {
11522 if (isReferenceType)
11523 HandleDeclRefExpr(E);
11524 }
11525
11526 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11527 if (E->getCastKind() == CK_LValueToRValue) {
11528 HandleValue(E->getSubExpr());
11529 return;
11530 }
11531
11532 Inherited::VisitImplicitCastExpr(E);
11533 }
11534
11535 void VisitMemberExpr(MemberExpr *E) {
11536 if (isInitList) {
11537 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11538 return;
11539 }
11540
11541 // Don't warn on arrays since they can be treated as pointers.
11542 if (E->getType()->canDecayToPointerType()) return;
11543
11544 // Warn when a non-static method call is followed by non-static member
11545 // field accesses, which is followed by a DeclRefExpr.
11546 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11547 bool Warn = (MD && !MD->isStatic());
11548 Expr *Base = E->getBase()->IgnoreParenImpCasts();
11549 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11550 if (!isa<FieldDecl>(ME->getMemberDecl()))
11551 Warn = false;
11552 Base = ME->getBase()->IgnoreParenImpCasts();
11553 }
11554
11555 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11556 if (Warn)
11557 HandleDeclRefExpr(DRE);
11558 return;
11559 }
11560
11561 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11562 // Visit that expression.
11563 Visit(Base);
11564 }
11565
11566 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11567 Expr *Callee = E->getCallee();
11568
11569 if (isa<UnresolvedLookupExpr>(Callee))
11570 return Inherited::VisitCXXOperatorCallExpr(E);
11571
11572 Visit(Callee);
11573 for (auto Arg: E->arguments())
11574 HandleValue(Arg->IgnoreParenImpCasts());
11575 }
11576
11577 void VisitUnaryOperator(UnaryOperator *E) {
11578 // For POD record types, addresses of its own members are well-defined.
11579 if (E->getOpcode() == UO_AddrOf && isRecordType &&
11580 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11581 if (!isPODType)
11582 HandleValue(E->getSubExpr());
11583 return;
11584 }
11585
11586 if (E->isIncrementDecrementOp()) {
11587 HandleValue(E->getSubExpr());
11588 return;
11589 }
11590
11591 Inherited::VisitUnaryOperator(E);
11592 }
11593
11594 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11595
11596 void VisitCXXConstructExpr(CXXConstructExpr *E) {
11597 if (E->getConstructor()->isCopyConstructor()) {
11598 Expr *ArgExpr = E->getArg(0);
11599 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11600 if (ILE->getNumInits() == 1)
11601 ArgExpr = ILE->getInit(0);
11602 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11603 if (ICE->getCastKind() == CK_NoOp)
11604 ArgExpr = ICE->getSubExpr();
11605 HandleValue(ArgExpr);
11606 return;
11607 }
11608 Inherited::VisitCXXConstructExpr(E);
11609 }
11610
11611 void VisitCallExpr(CallExpr *E) {
11612 // Treat std::move as a use.
11613 if (E->isCallToStdMove()) {
11614 HandleValue(E->getArg(0));
11615 return;
11616 }
11617
11618 Inherited::VisitCallExpr(E);
11619 }
11620
11621 void VisitBinaryOperator(BinaryOperator *E) {
11622 if (E->isCompoundAssignmentOp()) {
11623 HandleValue(E->getLHS());
11624 Visit(E->getRHS());
11625 return;
11626 }
11627
11628 Inherited::VisitBinaryOperator(E);
11629 }
11630
11631 // A custom visitor for BinaryConditionalOperator is needed because the
11632 // regular visitor would check the condition and true expression separately
11633 // but both point to the same place giving duplicate diagnostics.
11634 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11635 Visit(E->getCond());
11636 Visit(E->getFalseExpr());
11637 }
11638
11639 void HandleDeclRefExpr(DeclRefExpr *DRE) {
11640 Decl* ReferenceDecl = DRE->getDecl();
11641 if (OrigDecl != ReferenceDecl) return;
11642 unsigned diag;
11643 if (isReferenceType) {
11644 diag = diag::warn_uninit_self_reference_in_reference_init;
11645 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11646 diag = diag::warn_static_self_reference_in_init;
11647 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11648 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11649 DRE->getDecl()->getType()->isRecordType()) {
11650 diag = diag::warn_uninit_self_reference_in_init;
11651 } else {
11652 // Local variables will be handled by the CFG analysis.
11653 return;
11654 }
11655
11656 S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11657 S.PDiag(diag)
11658 << DRE->getDecl() << OrigDecl->getLocation()
11659 << DRE->getSourceRange());
11660 }
11661 };
11662
11663 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11664 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11665 bool DirectInit) {
11666 // Parameters arguments are occassionially constructed with itself,
11667 // for instance, in recursive functions. Skip them.
11668 if (isa<ParmVarDecl>(OrigDecl))
11669 return;
11670
11671 E = E->IgnoreParens();
11672
11673 // Skip checking T a = a where T is not a record or reference type.
11674 // Doing so is a way to silence uninitialized warnings.
11675 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11676 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11677 if (ICE->getCastKind() == CK_LValueToRValue)
11678 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11679 if (DRE->getDecl() == OrigDecl)
11680 return;
11681
11682 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11683 }
11684} // end anonymous namespace
11685
11686namespace {
11687 // Simple wrapper to add the name of a variable or (if no variable is
11688 // available) a DeclarationName into a diagnostic.
11689 struct VarDeclOrName {
11690 VarDecl *VDecl;
11691 DeclarationName Name;
11692
11693 friend const Sema::SemaDiagnosticBuilder &
11694 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11695 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11696 }
11697 };
11698} // end anonymous namespace
11699
11700QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
11701 DeclarationName Name, QualType Type,
11702 TypeSourceInfo *TSI,
11703 SourceRange Range, bool DirectInit,
11704 Expr *Init) {
11705 bool IsInitCapture = !VDecl
22.1
'VDecl' is non-null
22.1
'VDecl' is non-null
22.1
'VDecl' is non-null
;
11706 assert((!VDecl || !VDecl->isInitCapture()) &&((void)0)
11707 "init captures are expected to be deduced prior to initialization")((void)0);
11708
11709 VarDeclOrName VN{VDecl, Name};
11710
11711 DeducedType *Deduced = Type->getContainedDeducedType();
11712 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")((void)0);
11713
11714 // C++11 [dcl.spec.auto]p3
11715 if (!Init) {
23
Assuming 'Init' is non-null
24
Taking false branch
11716 assert(VDecl && "no init for init capture deduction?")((void)0);
11717
11718 // Except for class argument deduction, and then for an initializing
11719 // declaration only, i.e. no static at class scope or extern.
11720 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11721 VDecl->hasExternalStorage() ||
11722 VDecl->isStaticDataMember()) {
11723 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11724 << VDecl->getDeclName() << Type;
11725 return QualType();
11726 }
11727 }
11728
11729 ArrayRef<Expr*> DeduceInits;
11730 if (Init
24.1
'Init' is non-null
24.1
'Init' is non-null
24.1
'Init' is non-null
)
25
Taking true branch
11731 DeduceInits = Init;
26
Value assigned to 'Init'
11732
11733 if (DirectInit) {
27
Assuming 'DirectInit' is true
28
Taking true branch
11734 if (auto *PL
30.1
'PL' is null
30.1
'PL' is null
30.1
'PL' is null
= dyn_cast_or_null<ParenListExpr>(Init))
29
Assuming null pointer is passed into cast
30
Assuming pointer value is null
31
Taking false branch
11735 DeduceInits = PL->exprs();
11736 }
11737
11738 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
32
Assuming 'Deduced' is not a 'DeducedTemplateSpecializationType'
33
Taking false branch
11739 assert(VDecl && "non-auto type for init capture deduction?")((void)0);
11740 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11741 InitializationKind Kind = InitializationKind::CreateForInit(
11742 VDecl->getLocation(), DirectInit, Init);
11743 // FIXME: Initialization should not be taking a mutable list of inits.
11744 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11745 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11746 InitsCopy);
11747 }
11748
11749 if (DirectInit
33.1
'DirectInit' is true
33.1
'DirectInit' is true
33.1
'DirectInit' is true
) {
34
Taking true branch
11750 if (auto *IL = dyn_cast<InitListExpr>(Init))
35
Assuming 'IL' is null
36
Taking false branch
11751 DeduceInits = IL->inits();
11752 }
11753
11754 // Deduction only works if we have exactly one source expression.
11755 if (DeduceInits.empty()) {
37
Assuming the condition is false
38
Taking false branch
11756 // It isn't possible to write this directly, but it is possible to
11757 // end up in this situation with "auto x(some_pack...);"
11758 Diag(Init->getBeginLoc(), IsInitCapture
11759 ? diag::err_init_capture_no_expression
11760 : diag::err_auto_var_init_no_expression)
11761 << VN << Type << Range;
11762 return QualType();
11763 }
11764
11765 if (DeduceInits.size() > 1) {
39
Assuming the condition is false
40
Taking false branch
11766 Diag(DeduceInits[1]->getBeginLoc(),
11767 IsInitCapture ? diag::err_init_capture_multiple_expressions
11768 : diag::err_auto_var_init_multiple_expressions)
11769 << VN << Type << Range;
11770 return QualType();
11771 }
11772
11773 Expr *DeduceInit = DeduceInits[0];
11774 if (DirectInit
40.1
'DirectInit' is true
40.1
'DirectInit' is true
40.1
'DirectInit' is true
&& isa<InitListExpr>(DeduceInit)) {
41
Assuming 'DeduceInit' is not a 'InitListExpr'
42
Taking false branch
11775 Diag(Init->getBeginLoc(), IsInitCapture
11776 ? diag::err_init_capture_paren_braces
11777 : diag::err_auto_var_init_paren_braces)
11778 << isa<InitListExpr>(Init) << VN << Type << Range;
11779 return QualType();
11780 }
11781
11782 // Expressions default to 'id' when we're in a debugger.
11783 bool DefaultedAnyToId = false;
11784 if (getLangOpts().DebuggerCastResultToId &&
43
Assuming field 'DebuggerCastResultToId' is not equal to 0
11785 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
44
Called C++ object pointer is null
11786 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
11787 if (Result.isInvalid()) {
11788 return QualType();
11789 }
11790 Init = Result.get();
11791 DefaultedAnyToId = true;
11792 }
11793
11794 // C++ [dcl.decomp]p1:
11795 // If the assignment-expression [...] has array type A and no ref-qualifier
11796 // is present, e has type cv A
11797 if (VDecl && isa<DecompositionDecl>(VDecl) &&
11798 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
11799 DeduceInit->getType()->isConstantArrayType())
11800 return Context.getQualifiedType(DeduceInit->getType(),
11801 Type.getQualifiers());
11802
11803 QualType DeducedType;
11804 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
11805 if (!IsInitCapture)
11806 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
11807 else if (isa<InitListExpr>(Init))
11808 Diag(Range.getBegin(),
11809 diag::err_init_capture_deduction_failure_from_init_list)
11810 << VN
11811 << (DeduceInit->getType().isNull() ? TSI->getType()
11812 : DeduceInit->getType())
11813 << DeduceInit->getSourceRange();
11814 else
11815 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
11816 << VN << TSI->getType()
11817 << (DeduceInit->getType().isNull() ? TSI->getType()
11818 : DeduceInit->getType())
11819 << DeduceInit->getSourceRange();
11820 }
11821
11822 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
11823 // 'id' instead of a specific object type prevents most of our usual
11824 // checks.
11825 // We only want to warn outside of template instantiations, though:
11826 // inside a template, the 'id' could have come from a parameter.
11827 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
11828 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
11829 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
11830 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
11831 }
11832
11833 return DeducedType;
11834}
11835
11836bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
11837 Expr *Init) {
11838 assert(!Init || !Init->containsErrors())((void)0);
11839 QualType DeducedType = deduceVarTypeFromInitializer(
22
Calling 'Sema::deduceVarTypeFromInitializer'
11840 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
11841 VDecl->getSourceRange(), DirectInit, Init);
11842 if (DeducedType.isNull()) {
11843 VDecl->setInvalidDecl();
11844 return true;
11845 }
11846
11847 VDecl->setType(DeducedType);
11848 assert(VDecl->isLinkageValid())((void)0);
11849
11850 // In ARC, infer lifetime.
11851 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11852 VDecl->setInvalidDecl();
11853
11854 if (getLangOpts().OpenCL)
11855 deduceOpenCLAddressSpace(VDecl);
11856
11857 // If this is a redeclaration, check that the type we just deduced matches
11858 // the previously declared type.
11859 if (VarDecl *Old = VDecl->getPreviousDecl()) {
11860 // We never need to merge the type, because we cannot form an incomplete
11861 // array of auto, nor deduce such a type.
11862 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
11863 }
11864
11865 // Check the deduced type is valid for a variable declaration.
11866 CheckVariableDeclarationType(VDecl);
11867 return VDecl->isInvalidDecl();
11868}
11869
11870void Sema::checkNonTrivialCUnionInInitializer(const Expr *Init,
11871 SourceLocation Loc) {
11872 if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
11873 Init = EWC->getSubExpr();
11874
11875 if (auto *CE = dyn_cast<ConstantExpr>(Init))
11876 Init = CE->getSubExpr();
11877
11878 QualType InitType = Init->getType();
11879 assert((InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||((void)0)
11880 InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&((void)0)
11881 "shouldn't be called if type doesn't have a non-trivial C struct")((void)0);
11882 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
11883 for (auto I : ILE->inits()) {
11884 if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
11885 !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
11886 continue;
11887 SourceLocation SL = I->getExprLoc();
11888 checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
11889 }
11890 return;
11891 }
11892
11893 if (isa<ImplicitValueInitExpr>(Init)) {
11894 if (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
11895 checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
11896 NTCUK_Init);
11897 } else {
11898 // Assume all other explicit initializers involving copying some existing
11899 // object.
11900 // TODO: ignore any explicit initializers where we can guarantee
11901 // copy-elision.
11902 if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
11903 checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
11904 }
11905}
11906
11907namespace {
11908
11909bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
11910 // Ignore unavailable fields. A field can be marked as unavailable explicitly
11911 // in the source code or implicitly by the compiler if it is in a union
11912 // defined in a system header and has non-trivial ObjC ownership
11913 // qualifications. We don't want those fields to participate in determining
11914 // whether the containing union is non-trivial.
11915 return FD->hasAttr<UnavailableAttr>();
11916}
11917
11918struct DiagNonTrivalCUnionDefaultInitializeVisitor
11919 : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11920 void> {
11921 using Super =
11922 DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
11923 void>;
11924
11925 DiagNonTrivalCUnionDefaultInitializeVisitor(
11926 QualType OrigTy, SourceLocation OrigLoc,
11927 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11928 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11929
11930 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
11931 const FieldDecl *FD, bool InNonTrivialUnion) {
11932 if (const auto *AT = S.Context.getAsArrayType(QT))
11933 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11934 InNonTrivialUnion);
11935 return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
11936 }
11937
11938 void visitARCStrong(QualType QT, const FieldDecl *FD,
11939 bool InNonTrivialUnion) {
11940 if (InNonTrivialUnion)
11941 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11942 << 1 << 0 << QT << FD->getName();
11943 }
11944
11945 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11946 if (InNonTrivialUnion)
11947 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
11948 << 1 << 0 << QT << FD->getName();
11949 }
11950
11951 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
11952 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
11953 if (RD->isUnion()) {
11954 if (OrigLoc.isValid()) {
11955 bool IsUnion = false;
11956 if (auto *OrigRD = OrigTy->getAsRecordDecl())
11957 IsUnion = OrigRD->isUnion();
11958 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
11959 << 0 << OrigTy << IsUnion << UseContext;
11960 // Reset OrigLoc so that this diagnostic is emitted only once.
11961 OrigLoc = SourceLocation();
11962 }
11963 InNonTrivialUnion = true;
11964 }
11965
11966 if (InNonTrivialUnion)
11967 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
11968 << 0 << 0 << QT.getUnqualifiedType() << "";
11969
11970 for (const FieldDecl *FD : RD->fields())
11971 if (!shouldIgnoreForRecordTriviality(FD))
11972 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
11973 }
11974
11975 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
11976
11977 // The non-trivial C union type or the struct/union type that contains a
11978 // non-trivial C union.
11979 QualType OrigTy;
11980 SourceLocation OrigLoc;
11981 Sema::NonTrivialCUnionContext UseContext;
11982 Sema &S;
11983};
11984
11985struct DiagNonTrivalCUnionDestructedTypeVisitor
11986 : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
11987 using Super =
11988 DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void>;
11989
11990 DiagNonTrivalCUnionDestructedTypeVisitor(
11991 QualType OrigTy, SourceLocation OrigLoc,
11992 Sema::NonTrivialCUnionContext UseContext, Sema &S)
11993 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
11994
11995 void visitWithKind(QualType::DestructionKind DK, QualType QT,
11996 const FieldDecl *FD, bool InNonTrivialUnion) {
11997 if (const auto *AT = S.Context.getAsArrayType(QT))
11998 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
11999 InNonTrivialUnion);
12000 return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12001 }
12002
12003 void visitARCStrong(QualType QT, const FieldDecl *FD,
12004 bool InNonTrivialUnion) {
12005 if (InNonTrivialUnion)
12006 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12007 << 1 << 1 << QT << FD->getName();
12008 }
12009
12010 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12011 if (InNonTrivialUnion)
12012 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12013 << 1 << 1 << QT << FD->getName();
12014 }
12015
12016 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12017 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12018 if (RD->isUnion()) {
12019 if (OrigLoc.isValid()) {
12020 bool IsUnion = false;
12021 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12022 IsUnion = OrigRD->isUnion();
12023 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12024 << 1 << OrigTy << IsUnion << UseContext;
12025 // Reset OrigLoc so that this diagnostic is emitted only once.
12026 OrigLoc = SourceLocation();
12027 }
12028 InNonTrivialUnion = true;
12029 }
12030
12031 if (InNonTrivialUnion)
12032 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12033 << 0 << 1 << QT.getUnqualifiedType() << "";
12034
12035 for (const FieldDecl *FD : RD->fields())
12036 if (!shouldIgnoreForRecordTriviality(FD))
12037 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12038 }
12039
12040 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12041 void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12042 bool InNonTrivialUnion) {}
12043
12044 // The non-trivial C union type or the struct/union type that contains a
12045 // non-trivial C union.
12046 QualType OrigTy;
12047 SourceLocation OrigLoc;
12048 Sema::NonTrivialCUnionContext UseContext;
12049 Sema &S;
12050};
12051
12052struct DiagNonTrivalCUnionCopyVisitor
12053 : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12054 using Super = CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void>;
12055
12056 DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12057 Sema::NonTrivialCUnionContext UseContext,
12058 Sema &S)
12059 : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12060
12061 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12062 const FieldDecl *FD, bool InNonTrivialUnion) {
12063 if (const auto *AT = S.Context.getAsArrayType(QT))
12064 return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12065 InNonTrivialUnion);
12066 return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12067 }
12068
12069 void visitARCStrong(QualType QT, const FieldDecl *FD,
12070 bool InNonTrivialUnion) {
12071 if (InNonTrivialUnion)
12072 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12073 << 1 << 2 << QT << FD->getName();
12074 }
12075
12076 void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12077 if (InNonTrivialUnion)
12078 S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12079 << 1 << 2 << QT << FD->getName();
12080 }
12081
12082 void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12083 const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12084 if (RD->isUnion()) {
12085 if (OrigLoc.isValid()) {
12086 bool IsUnion = false;
12087 if (auto *OrigRD = OrigTy->getAsRecordDecl())
12088 IsUnion = OrigRD->isUnion();
12089 S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12090 << 2 << OrigTy << IsUnion << UseContext;
12091 // Reset OrigLoc so that this diagnostic is emitted only once.
12092 OrigLoc = SourceLocation();
12093 }
12094 InNonTrivialUnion = true;
12095 }
12096
12097 if (InNonTrivialUnion)
12098 S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12099 << 0 << 2 << QT.getUnqualifiedType() << "";
12100
12101 for (const FieldDecl *FD : RD->fields())
12102 if (!shouldIgnoreForRecordTriviality(FD))
12103 asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12104 }
12105
12106 void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12107 const FieldDecl *FD, bool InNonTrivialUnion) {}
12108 void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12109 void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12110 bool InNonTrivialUnion) {}
12111
12112 // The non-trivial C union type or the struct/union type that contains a
12113 // non-trivial C union.
12114 QualType OrigTy;
12115 SourceLocation OrigLoc;
12116 Sema::NonTrivialCUnionContext UseContext;
12117 Sema &S;
12118};
12119
12120} // namespace
12121
12122void Sema::checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
12123 NonTrivialCUnionContext UseContext,
12124 unsigned NonTrivialKind) {
12125 assert((QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||((void)0)
12126 QT.hasNonTrivialToPrimitiveDestructCUnion() ||((void)0)
12127 QT.hasNonTrivialToPrimitiveCopyCUnion()) &&((void)0)
12128 "shouldn't be called if type doesn't have a non-trivial C union")((void)0);
12129
12130 if ((NonTrivialKind & NTCUK_Init) &&
12131 QT.hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12132 DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12133 .visit(QT, nullptr, false);
12134 if ((NonTrivialKind & NTCUK_Destruct) &&
12135 QT.hasNonTrivialToPrimitiveDestructCUnion())
12136 DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12137 .visit(QT, nullptr, false);
12138 if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12139 DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12140 .visit(QT, nullptr, false);
12141}
12142
12143/// AddInitializerToDecl - Adds the initializer Init to the
12144/// declaration dcl. If DirectInit is true, this is C++ direct
12145/// initialization rather than copy initialization.
12146void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12147 // If there is no declaration, there was an error parsing it. Just ignore
12148 // the initializer.
12149 if (!RealDecl || RealDecl->isInvalidDecl()) {
1
Assuming 'RealDecl' is non-null
2
Assuming the condition is false
3
Taking false branch
12150 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12151 return;
12152 }
12153
12154 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
12155 // Pure-specifiers are handled in ActOnPureSpecifier.
12156 Diag(Method->getLocation(), diag::err_member_function_initialization)
12157 << Method->getDeclName() << Init->getSourceRange();
12158 Method->setInvalidDecl();
12159 return;
12160 }
12161
12162 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
6
Assuming 'RealDecl' is a 'VarDecl'
12163 if (!VDecl
6.1
'VDecl' is non-null
6.1
'VDecl' is non-null
6.1
'VDecl' is non-null
) {
7
Taking false branch
12164 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")((void)0);
12165 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12166 RealDecl->setInvalidDecl();
12167 return;
12168 }
12169
12170 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12171 if (VDecl->getType()->isUndeducedType()) {
8
Calling 'Type::isUndeducedType'
12
Returning from 'Type::isUndeducedType'
13
Taking true branch
12172 // Attempt typo correction early so that the type of the init expression can
12173 // be deduced based on the chosen correction if the original init contains a
12174 // TypoExpr.
12175 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12176 if (!Res.isUsable()) {
14
Calling 'ActionResult::isUsable'
17
Returning from 'ActionResult::isUsable'
18
Taking false branch
12177 // There are unresolved typos in Init, just drop them.
12178 // FIXME: improve the recovery strategy to preserve the Init.
12179 RealDecl->setInvalidDecl();
12180 return;
12181 }
12182 if (Res.get()->containsErrors()) {
19
Assuming the condition is false
20
Taking false branch
12183 // Invalidate the decl as we don't know the type for recovery-expr yet.
12184 RealDecl->setInvalidDecl();
12185 VDecl->setInit(Res.get());
12186 return;
12187 }
12188 Init = Res.get();
12189
12190 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
21
Calling 'Sema::DeduceVariableDeclarationType'
12191 return;
12192 }
12193
12194 // dllimport cannot be used on variable definitions.
12195 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12196 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12197 VDecl->setInvalidDecl();
12198 return;
12199 }
12200
12201 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12202 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12203 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12204 VDecl->setInvalidDecl();
12205 return;
12206 }
12207
12208 if (!VDecl->getType()->isDependentType()) {
12209 // A definition must end up with a complete type, which means it must be
12210 // complete with the restriction that an array type might be completed by
12211 // the initializer; note that later code assumes this restriction.
12212 QualType BaseDeclType = VDecl->getType();
12213 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12214 BaseDeclType = Array->getElementType();
12215 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12216 diag::err_typecheck_decl_incomplete_type)) {
12217 RealDecl->setInvalidDecl();
12218 return;
12219 }
12220
12221 // The variable can not have an abstract class type.
12222 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12223 diag::err_abstract_type_in_decl,
12224 AbstractVariableType))
12225 VDecl->setInvalidDecl();
12226 }
12227
12228 // If adding the initializer will turn this declaration into a definition,
12229 // and we already have a definition for this variable, diagnose or otherwise
12230 // handle the situation.
12231 if (VarDecl *Def = VDecl->getDefinition())
12232 if (Def != VDecl &&
12233 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12234 !VDecl->isThisDeclarationADemotedDefinition() &&
12235 checkVarDeclRedefinition(Def, VDecl))
12236 return;
12237
12238 if (getLangOpts().CPlusPlus) {
12239 // C++ [class.static.data]p4
12240 // If a static data member is of const integral or const
12241 // enumeration type, its declaration in the class definition can
12242 // specify a constant-initializer which shall be an integral
12243 // constant expression (5.19). In that case, the member can appear
12244 // in integral constant expressions. The member shall still be
12245 // defined in a namespace scope if it is used in the program and the
12246 // namespace scope definition shall not contain an initializer.
12247 //
12248 // We already performed a redefinition check above, but for static
12249 // data members we also need to check whether there was an in-class
12250 // declaration with an initializer.
12251 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12252 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12253 << VDecl->getDeclName();
12254 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12255 diag::note_previous_initializer)
12256 << 0;
12257 return;
12258 }
12259
12260 if (VDecl->hasLocalStorage())
12261 setFunctionHasBranchProtectedScope();
12262
12263 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12264 VDecl->setInvalidDecl();
12265 return;
12266 }
12267 }
12268
12269 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12270 // a kernel function cannot be initialized."
12271 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12272 Diag(VDecl->getLocation(), diag::err_local_cant_init);
12273 VDecl->setInvalidDecl();
12274 return;
12275 }
12276
12277 // The LoaderUninitialized attribute acts as a definition (of undef).
12278 if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12279 Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12280 VDecl->setInvalidDecl();
12281 return;
12282 }
12283
12284 // Get the decls type and save a reference for later, since
12285 // CheckInitializerTypes may change it.
12286 QualType DclT = VDecl->getType(), SavT = DclT;
12287
12288 // Expressions default to 'id' when we're in a debugger
12289 // and we are assigning it to a variable of Objective-C pointer type.
12290 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12291 Init->getType() == Context.UnknownAnyTy) {
12292 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12293 if (Result.isInvalid()) {
12294 VDecl->setInvalidDecl();
12295 return;
12296 }
12297 Init = Result.get();
12298 }
12299
12300 // Perform the initialization.
12301 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12302 if (!VDecl->isInvalidDecl()) {
12303 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
12304 InitializationKind Kind = InitializationKind::CreateForInit(
12305 VDecl->getLocation(), DirectInit, Init);
12306
12307 MultiExprArg Args = Init;
12308 if (CXXDirectInit)
12309 Args = MultiExprArg(CXXDirectInit->getExprs(),
12310 CXXDirectInit->getNumExprs());
12311
12312 // Try to correct any TypoExprs in the initialization arguments.
12313 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12314 ExprResult Res = CorrectDelayedTyposInExpr(
12315 Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12316 [this, Entity, Kind](Expr *E) {
12317 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12318 return Init.Failed() ? ExprError() : E;
12319 });
12320 if (Res.isInvalid()) {
12321 VDecl->setInvalidDecl();
12322 } else if (Res.get() != Args[Idx]) {
12323 Args[Idx] = Res.get();
12324 }
12325 }
12326 if (VDecl->isInvalidDecl())
12327 return;
12328
12329 InitializationSequence InitSeq(*this, Entity, Kind, Args,
12330 /*TopLevelOfInitList=*/false,
12331 /*TreatUnavailableAsInvalid=*/false);
12332 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12333 if (Result.isInvalid()) {
12334 // If the provied initializer fails to initialize the var decl,
12335 // we attach a recovery expr for better recovery.
12336 auto RecoveryExpr =
12337 CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12338 if (RecoveryExpr.get())
12339 VDecl->setInit(RecoveryExpr.get());
12340 return;
12341 }
12342
12343 Init = Result.getAs<Expr>();
12344 }
12345
12346 // Check for self-references within variable initializers.
12347 // Variables declared within a function/method body (except for references)
12348 // are handled by a dataflow analysis.
12349 // This is undefined behavior in C++, but valid in C.
12350 if (getLangOpts().CPlusPlus)
12351 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12352 VDecl->getType()->isReferenceType())
12353 CheckSelfReference(*this, RealDecl, Init, DirectInit);
12354
12355 // If the type changed, it means we had an incomplete type that was
12356 // completed by the initializer. For example:
12357 // int ary[] = { 1, 3, 5 };
12358 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12359 if (!VDecl->isInvalidDecl() && (DclT != SavT))
12360 VDecl->setType(DclT);
12361
12362 if (!VDecl->isInvalidDecl()) {
12363 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12364
12365 if (VDecl->hasAttr<BlocksAttr>())
12366 checkRetainCycles(VDecl, Init);
12367
12368 // It is safe to assign a weak reference into a strong variable.
12369 // Although this code can still have problems:
12370 // id x = self.weakProp;
12371 // id y = self.weakProp;
12372 // we do not warn to warn spuriously when 'x' and 'y' are on separate
12373 // paths through the function. This should be revisited if
12374 // -Wrepeated-use-of-weak is made flow-sensitive.
12375 if (FunctionScopeInfo *FSI = getCurFunction())
12376 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12377 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12378 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12379 Init->getBeginLoc()))
12380 FSI->markSafeWeakUse(Init);
12381 }
12382
12383 // The initialization is usually a full-expression.
12384 //
12385 // FIXME: If this is a braced initialization of an aggregate, it is not
12386 // an expression, and each individual field initializer is a separate
12387 // full-expression. For instance, in:
12388 //
12389 // struct Temp { ~Temp(); };
12390 // struct S { S(Temp); };
12391 // struct T { S a, b; } t = { Temp(), Temp() }
12392 //
12393 // we should destroy the first Temp before constructing the second.
12394 ExprResult Result =
12395 ActOnFinishFullExpr(Init, VDecl->getLocation(),
12396 /*DiscardedValue*/ false, VDecl->isConstexpr());
12397 if (Result.isInvalid()) {
12398 VDecl->setInvalidDecl();
12399 return;
12400 }
12401 Init = Result.get();
12402
12403 // Attach the initializer to the decl.
12404 VDecl->setInit(Init);
12405
12406 if (VDecl->isLocalVarDecl()) {
12407 // Don't check the initializer if the declaration is malformed.
12408 if (VDecl->isInvalidDecl()) {
12409 // do nothing
12410
12411 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12412 // This is true even in C++ for OpenCL.
12413 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12414 CheckForConstantInitializer(Init, DclT);
12415
12416 // Otherwise, C++ does not restrict the initializer.
12417 } else if (getLangOpts().CPlusPlus) {
12418 // do nothing
12419
12420 // C99 6.7.8p4: All the expressions in an initializer for an object that has
12421 // static storage duration shall be constant expressions or string literals.
12422 } else if (VDecl->getStorageClass() == SC_Static) {
12423 CheckForConstantInitializer(Init, DclT);
12424
12425 // C89 is stricter than C99 for aggregate initializers.
12426 // C89 6.5.7p3: All the expressions [...] in an initializer list
12427 // for an object that has aggregate or union type shall be
12428 // constant expressions.
12429 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12430 isa<InitListExpr>(Init)) {
12431 const Expr *Culprit;
12432 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12433 Diag(Culprit->getExprLoc(),
12434 diag::ext_aggregate_init_not_constant)
12435 << Culprit->getSourceRange();
12436 }
12437 }
12438
12439 if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12440 if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12441 if (VDecl->hasLocalStorage())
12442 BE->getBlockDecl()->setCanAvoidCopyToHeap();
12443 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12444 VDecl->getLexicalDeclContext()->isRecord()) {
12445 // This is an in-class initialization for a static data member, e.g.,
12446 //
12447 // struct S {
12448 // static const int value = 17;
12449 // };
12450
12451 // C++ [class.mem]p4:
12452 // A member-declarator can contain a constant-initializer only
12453 // if it declares a static member (9.4) of const integral or
12454 // const enumeration type, see 9.4.2.
12455 //
12456 // C++11 [class.static.data]p3:
12457 // If a non-volatile non-inline const static data member is of integral
12458 // or enumeration type, its declaration in the class definition can
12459 // specify a brace-or-equal-initializer in which every initializer-clause
12460 // that is an assignment-expression is a constant expression. A static
12461 // data member of literal type can be declared in the class definition
12462 // with the constexpr specifier; if so, its declaration shall specify a
12463 // brace-or-equal-initializer in which every initializer-clause that is
12464 // an assignment-expression is a constant expression.
12465
12466 // Do nothing on dependent types.
12467 if (DclT->isDependentType()) {
12468
12469 // Allow any 'static constexpr' members, whether or not they are of literal
12470 // type. We separately check that every constexpr variable is of literal
12471 // type.
12472 } else if (VDecl->isConstexpr()) {
12473
12474 // Require constness.
12475 } else if (!DclT.isConstQualified()) {
12476 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12477 << Init->getSourceRange();
12478 VDecl->setInvalidDecl();
12479
12480 // We allow integer constant expressions in all cases.
12481 } else if (DclT->isIntegralOrEnumerationType()) {
12482 // Check whether the expression is a constant expression.
12483 SourceLocation Loc;
12484 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12485 // In C++11, a non-constexpr const static data member with an
12486 // in-class initializer cannot be volatile.
12487 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12488 else if (Init->isValueDependent())
12489 ; // Nothing to check.
12490 else if (Init->isIntegerConstantExpr(Context, &Loc))
12491 ; // Ok, it's an ICE!
12492 else if (Init->getType()->isScopedEnumeralType() &&
12493 Init->isCXX11ConstantExpr(Context))
12494 ; // Ok, it is a scoped-enum constant expression.
12495 else if (Init->isEvaluatable(Context)) {
12496 // If we can constant fold the initializer through heroics, accept it,
12497 // but report this as a use of an extension for -pedantic.
12498 Diag(Loc, diag::ext_in_class_initializer_non_constant)
12499 << Init->getSourceRange();
12500 } else {
12501 // Otherwise, this is some crazy unknown case. Report the issue at the
12502 // location provided by the isIntegerConstantExpr failed check.
12503 Diag(Loc, diag::err_in_class_initializer_non_constant)
12504 << Init->getSourceRange();
12505 VDecl->setInvalidDecl();
12506 }
12507
12508 // We allow foldable floating-point constants as an extension.
12509 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12510 // In C++98, this is a GNU extension. In C++11, it is not, but we support
12511 // it anyway and provide a fixit to add the 'constexpr'.
12512 if (getLangOpts().CPlusPlus11) {
12513 Diag(VDecl->getLocation(),
12514 diag::ext_in_class_initializer_float_type_cxx11)
12515 << DclT << Init->getSourceRange();
12516 Diag(VDecl->getBeginLoc(),
12517 diag::note_in_class_initializer_float_type_cxx11)
12518 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12519 } else {
12520 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12521 << DclT << Init->getSourceRange();
12522
12523 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12524 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12525 << Init->getSourceRange();
12526 VDecl->setInvalidDecl();
12527 }
12528 }
12529
12530 // Suggest adding 'constexpr' in C++11 for literal types.
12531 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12532 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12533 << DclT << Init->getSourceRange()
12534 << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12535 VDecl->setConstexpr(true);
12536
12537 } else {
12538 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12539 << DclT << Init->getSourceRange();
12540 VDecl->setInvalidDecl();
12541 }
12542 } else if (VDecl->isFileVarDecl()) {
12543 // In C, extern is typically used to avoid tentative definitions when
12544 // declaring variables in headers, but adding an intializer makes it a
12545 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12546 // In C++, extern is often used to give implictly static const variables
12547 // external linkage, so don't warn in that case. If selectany is present,
12548 // this might be header code intended for C and C++ inclusion, so apply the
12549 // C++ rules.
12550 if (VDecl->getStorageClass() == SC_Extern &&
12551 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12552 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12553 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12554 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
12555 Diag(VDecl->getLocation(), diag::warn_extern_init);
12556
12557 // In Microsoft C++ mode, a const variable defined in namespace scope has
12558 // external linkage by default if the variable is declared with
12559 // __declspec(dllexport).
12560 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12561 getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12562 VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12563 VDecl->setStorageClass(SC_Extern);
12564
12565 // C99 6.7.8p4. All file scoped initializers need to be constant.
12566 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12567 CheckForConstantInitializer(Init, DclT);
12568 }
12569
12570 QualType InitType = Init->getType();
12571 if (!InitType.isNull() &&
12572 (InitType.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
12573 InitType.hasNonTrivialToPrimitiveCopyCUnion()))
12574 checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12575
12576 // We will represent direct-initialization similarly to copy-initialization:
12577 // int x(1); -as-> int x = 1;
12578 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12579 //
12580 // Clients that want to distinguish between the two forms, can check for
12581 // direct initializer using VarDecl::getInitStyle().
12582 // A major benefit is that clients that don't particularly care about which
12583 // exactly form was it (like the CodeGen) can handle both cases without
12584 // special case code.
12585
12586 // C++ 8.5p11:
12587 // The form of initialization (using parentheses or '=') is generally
12588 // insignificant, but does matter when the entity being initialized has a
12589 // class type.
12590 if (CXXDirectInit) {
12591 assert(DirectInit && "Call-style initializer must be direct init.")((void)0);
12592 VDecl->setInitStyle(VarDecl::CallInit);
12593 } else if (DirectInit) {
12594 // This must be list-initialization. No other way is direct-initialization.
12595 VDecl->setInitStyle(VarDecl::ListInit);
12596 }
12597
12598 if (LangOpts.OpenMP && VDecl->isFileVarDecl())
12599 DeclsToCheckForDeferredDiags.insert(VDecl);
12600 CheckCompleteVariableDeclaration(VDecl);
12601}
12602
12603/// ActOnInitializerError - Given that there was an error parsing an
12604/// initializer for the given declaration, try to return to some form
12605/// of sanity.
12606void Sema::ActOnInitializerError(Decl *D) {
12607 // Our main concern here is re-establishing invariants like "a
12608 // variable's type is either dependent or complete".
12609 if (!D || D->isInvalidDecl()) return;
12610
12611 VarDecl *VD = dyn_cast<VarDecl>(D);
12612 if (!VD) return;
12613
12614 // Bindings are not usable if we can't make sense of the initializer.
12615 if (auto *DD = dyn_cast<DecompositionDecl>(D))
12616 for (auto *BD : DD->bindings())
12617 BD->setInvalidDecl();
12618
12619 // Auto types are meaningless if we can't make sense of the initializer.
12620 if (VD->getType()->isUndeducedType()) {
12621 D->setInvalidDecl();
12622 return;
12623 }
12624
12625 QualType Ty = VD->getType();
12626 if (Ty->isDependentType()) return;
12627
12628 // Require a complete type.
12629 if (RequireCompleteType(VD->getLocation(),
12630 Context.getBaseElementType(Ty),
12631 diag::err_typecheck_decl_incomplete_type)) {
12632 VD->setInvalidDecl();
12633 return;
12634 }
12635
12636 // Require a non-abstract type.
12637 if (RequireNonAbstractType(VD->getLocation(), Ty,
12638 diag::err_abstract_type_in_decl,
12639 AbstractVariableType)) {
12640 VD->setInvalidDecl();
12641 return;
12642 }
12643
12644 // Don't bother complaining about constructors or destructors,
12645 // though.
12646}
12647
12648void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
12649 // If there is no declaration, there was an error parsing it. Just ignore it.
12650 if (!RealDecl)
12651 return;
12652
12653 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12654 QualType Type = Var->getType();
12655
12656 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12657 if (isa<DecompositionDecl>(RealDecl)) {
12658 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12659 Var->setInvalidDecl();
12660 return;
12661 }
12662
12663 if (Type->isUndeducedType() &&
12664 DeduceVariableDeclarationType(Var, false, nullptr))
12665 return;
12666
12667 // C++11 [class.static.data]p3: A static data member can be declared with
12668 // the constexpr specifier; if so, its declaration shall specify
12669 // a brace-or-equal-initializer.
12670 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12671 // the definition of a variable [...] or the declaration of a static data
12672 // member.
12673 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12674 !Var->isThisDeclarationADemotedDefinition()) {
12675 if (Var->isStaticDataMember()) {
12676 // C++1z removes the relevant rule; the in-class declaration is always
12677 // a definition there.
12678 if (!getLangOpts().CPlusPlus17 &&
12679 !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12680 Diag(Var->getLocation(),
12681 diag::err_constexpr_static_mem_var_requires_init)
12682 << Var;
12683 Var->setInvalidDecl();
12684 return;
12685 }
12686 } else {
12687 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12688 Var->setInvalidDecl();
12689 return;
12690 }
12691 }
12692
12693 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12694 // be initialized.
12695 if (!Var->isInvalidDecl() &&
12696 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12697 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12698 bool HasConstExprDefaultConstructor = false;
12699 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12700 for (auto *Ctor : RD->ctors()) {
12701 if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12702 Ctor->getMethodQualifiers().getAddressSpace() ==
12703 LangAS::opencl_constant) {
12704 HasConstExprDefaultConstructor = true;
12705 }
12706 }
12707 }
12708 if (!HasConstExprDefaultConstructor) {
12709 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12710 Var->setInvalidDecl();
12711 return;
12712 }
12713 }
12714
12715 if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12716 if (Var->getStorageClass() == SC_Extern) {
12717 Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12718 << Var;
12719 Var->setInvalidDecl();
12720 return;
12721 }
12722 if (RequireCompleteType(Var->getLocation(), Var->getType(),
12723 diag::err_typecheck_decl_incomplete_type)) {
12724 Var->setInvalidDecl();
12725 return;
12726 }
12727 if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12728 if (!RD->hasTrivialDefaultConstructor()) {
12729 Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12730 Var->setInvalidDecl();
12731 return;
12732 }
12733 }
12734 // The declaration is unitialized, no need for further checks.
12735 return;
12736 }
12737
12738 VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12739 if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12740 Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12741 checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12742 NTCUC_DefaultInitializedObject, NTCUK_Init);
12743
12744
12745 switch (DefKind) {
12746 case VarDecl::Definition:
12747 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12748 break;
12749
12750 // We have an out-of-line definition of a static data member
12751 // that has an in-class initializer, so we type-check this like
12752 // a declaration.
12753 //
12754 LLVM_FALLTHROUGH[[gnu::fallthrough]];
12755
12756 case VarDecl::DeclarationOnly:
12757 // It's only a declaration.
12758
12759 // Block scope. C99 6.7p7: If an identifier for an object is
12760 // declared with no linkage (C99 6.2.2p6), the type for the
12761 // object shall be complete.
12762 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12763 !Var->hasLinkage() && !Var->isInvalidDecl() &&
12764 RequireCompleteType(Var->getLocation(), Type,
12765 diag::err_typecheck_decl_incomplete_type))
12766 Var->setInvalidDecl();
12767
12768 // Make sure that the type is not abstract.
12769 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12770 RequireNonAbstractType(Var->getLocation(), Type,
12771 diag::err_abstract_type_in_decl,
12772 AbstractVariableType))
12773 Var->setInvalidDecl();
12774 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
12775 Var->getStorageClass() == SC_PrivateExtern) {
12776 Diag(Var->getLocation(), diag::warn_private_extern);
12777 Diag(Var->getLocation(), diag::note_private_extern);
12778 }
12779
12780 if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
12781 !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
12782 ExternalDeclarations.push_back(Var);
12783
12784 return;
12785
12786 case VarDecl::TentativeDefinition:
12787 // File scope. C99 6.9.2p2: A declaration of an identifier for an
12788 // object that has file scope without an initializer, and without a
12789 // storage-class specifier or with the storage-class specifier "static",
12790 // constitutes a tentative definition. Note: A tentative definition with
12791 // external linkage is valid (C99 6.2.2p5).
12792 if (!Var->isInvalidDecl()) {
12793 if (const IncompleteArrayType *ArrayT
12794 = Context.getAsIncompleteArrayType(Type)) {
12795 if (RequireCompleteSizedType(
12796 Var->getLocation(), ArrayT->getElementType(),
12797 diag::err_array_incomplete_or_sizeless_type))
12798 Var->setInvalidDecl();
12799 } else if (Var->getStorageClass() == SC_Static) {
12800 // C99 6.9.2p3: If the declaration of an identifier for an object is
12801 // a tentative definition and has internal linkage (C99 6.2.2p3), the
12802 // declared type shall not be an incomplete type.
12803 // NOTE: code such as the following
12804 // static struct s;
12805 // struct s { int a; };
12806 // is accepted by gcc. Hence here we issue a warning instead of
12807 // an error and we do not invalidate the static declaration.
12808 // NOTE: to avoid multiple warnings, only check the first declaration.
12809 if (Var->isFirstDecl())
12810 RequireCompleteType(Var->getLocation(), Type,
12811 diag::ext_typecheck_decl_incomplete_type);
12812 }
12813 }
12814
12815 // Record the tentative definition; we're done.
12816 if (!Var->isInvalidDecl())
12817 TentativeDefinitions.push_back(Var);
12818 return;
12819 }
12820
12821 // Provide a specific diagnostic for uninitialized variable
12822 // definitions with incomplete array type.
12823 if (Type->isIncompleteArrayType()) {
12824 Diag(Var->getLocation(),
12825 diag::err_typecheck_incomplete_array_needs_initializer);
12826 Var->setInvalidDecl();
12827 return;
12828 }
12829
12830 // Provide a specific diagnostic for uninitialized variable
12831 // definitions with reference type.
12832 if (Type->isReferenceType()) {
12833 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
12834 << Var << SourceRange(Var->getLocation(), Var->getLocation());
12835 Var->setInvalidDecl();
12836 return;
12837 }
12838
12839 // Do not attempt to type-check the default initializer for a
12840 // variable with dependent type.
12841 if (Type->isDependentType())
12842 return;
12843
12844 if (Var->isInvalidDecl())
12845 return;
12846
12847 if (!Var->hasAttr<AliasAttr>()) {
12848 if (RequireCompleteType(Var->getLocation(),
12849 Context.getBaseElementType(Type),
12850 diag::err_typecheck_decl_incomplete_type)) {
12851 Var->setInvalidDecl();
12852 return;
12853 }
12854 } else {
12855 return;
12856 }
12857
12858 // The variable can not have an abstract class type.
12859 if (RequireNonAbstractType(Var->getLocation(), Type,
12860 diag::err_abstract_type_in_decl,
12861 AbstractVariableType)) {
12862 Var->setInvalidDecl();
12863 return;
12864 }
12865
12866 // Check for jumps past the implicit initializer. C++0x
12867 // clarifies that this applies to a "variable with automatic
12868 // storage duration", not a "local variable".
12869 // C++11 [stmt.dcl]p3
12870 // A program that jumps from a point where a variable with automatic
12871 // storage duration is not in scope to a point where it is in scope is
12872 // ill-formed unless the variable has scalar type, class type with a
12873 // trivial default constructor and a trivial destructor, a cv-qualified
12874 // version of one of these types, or an array of one of the preceding
12875 // types and is declared without an initializer.
12876 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
12877 if (const RecordType *Record
12878 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
12879 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
12880 // Mark the function (if we're in one) for further checking even if the
12881 // looser rules of C++11 do not require such checks, so that we can
12882 // diagnose incompatibilities with C++98.
12883 if (!CXXRecord->isPOD())
12884 setFunctionHasBranchProtectedScope();
12885 }
12886 }
12887 // In OpenCL, we can't initialize objects in the __local address space,
12888 // even implicitly, so don't synthesize an implicit initializer.
12889 if (getLangOpts().OpenCL &&
12890 Var->getType().getAddressSpace() == LangAS::opencl_local)
12891 return;
12892 // C++03 [dcl.init]p9:
12893 // If no initializer is specified for an object, and the
12894 // object is of (possibly cv-qualified) non-POD class type (or
12895 // array thereof), the object shall be default-initialized; if
12896 // the object is of const-qualified type, the underlying class
12897 // type shall have a user-declared default
12898 // constructor. Otherwise, if no initializer is specified for
12899 // a non- static object, the object and its subobjects, if
12900 // any, have an indeterminate initial value); if the object
12901 // or any of its subobjects are of const-qualified type, the
12902 // program is ill-formed.
12903 // C++0x [dcl.init]p11:
12904 // If no initializer is specified for an object, the object is
12905 // default-initialized; [...].
12906 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
12907 InitializationKind Kind
12908 = InitializationKind::CreateDefault(Var->getLocation());
12909
12910 InitializationSequence InitSeq(*this, Entity, Kind, None);
12911 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
12912
12913 if (Init.get()) {
12914 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
12915 // This is important for template substitution.
12916 Var->setInitStyle(VarDecl::CallInit);
12917 } else if (Init.isInvalid()) {
12918 // If default-init fails, attach a recovery-expr initializer to track
12919 // that initialization was attempted and failed.
12920 auto RecoveryExpr =
12921 CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
12922 if (RecoveryExpr.get())
12923 Var->setInit(RecoveryExpr.get());
12924 }
12925
12926 CheckCompleteVariableDeclaration(Var);
12927 }
12928}
12929
12930void Sema::ActOnCXXForRangeDecl(Decl *D) {
12931 // If there is no declaration, there was an error parsing it. Ignore it.
12932 if (!D)
12933 return;
12934
12935 VarDecl *VD = dyn_cast<VarDecl>(D);
12936 if (!VD) {
12937 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
12938 D->setInvalidDecl();
12939 return;
12940 }
12941
12942 VD->setCXXForRangeDecl(true);
12943
12944 // for-range-declaration cannot be given a storage class specifier.
12945 int Error = -1;
12946 switch (VD->getStorageClass()) {
12947 case SC_None:
12948 break;
12949 case SC_Extern:
12950 Error = 0;
12951 break;
12952 case SC_Static:
12953 Error = 1;
12954 break;
12955 case SC_PrivateExtern:
12956 Error = 2;
12957 break;
12958 case SC_Auto:
12959 Error = 3;
12960 break;
12961 case SC_Register:
12962 Error = 4;
12963 break;
12964 }
12965
12966 // for-range-declaration cannot be given a storage class specifier con't.
12967 switch (VD->getTSCSpec()) {
12968 case TSCS_thread_local:
12969 Error = 6;
12970 break;
12971 case TSCS___thread:
12972 case TSCS__Thread_local:
12973 case TSCS_unspecified:
12974 break;
12975 }
12976
12977 if (Error != -1) {
12978 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
12979 << VD << Error;
12980 D->setInvalidDecl();
12981 }
12982}
12983
12984StmtResult
12985Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
12986 IdentifierInfo *Ident,
12987 ParsedAttributes &Attrs,
12988 SourceLocation AttrEnd) {
12989 // C++1y [stmt.iter]p1:
12990 // A range-based for statement of the form
12991 // for ( for-range-identifier : for-range-initializer ) statement
12992 // is equivalent to
12993 // for ( auto&& for-range-identifier : for-range-initializer ) statement
12994 DeclSpec DS(Attrs.getPool().getFactory());
12995
12996 const char *PrevSpec;
12997 unsigned DiagID;
12998 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
12999 getPrintingPolicy());
13000
13001 Declarator D(DS, DeclaratorContext::ForInit);
13002 D.SetIdentifier(Ident, IdentLoc);
13003 D.takeAttributes(Attrs, AttrEnd);
13004
13005 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13006 IdentLoc);
13007 Decl *Var = ActOnDeclarator(S, D);
13008 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13009 FinalizeDeclaration(Var);
13010 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13011 AttrEnd.isValid() ? AttrEnd : IdentLoc);
13012}
13013
13014void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
13015 if (var->isInvalidDecl()) return;
13016
13017 MaybeAddCUDAConstantAttr(var);
13018
13019 if (getLangOpts().OpenCL) {
13020 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13021 // initialiser
13022 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13023 !var->hasInit()) {
13024 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13025 << 1 /*Init*/;
13026 var->setInvalidDecl();
13027 return;
13028 }
13029 }
13030
13031 // In Objective-C, don't allow jumps past the implicit initialization of a
13032 // local retaining variable.
13033 if (getLangOpts().ObjC &&
13034 var->hasLocalStorage()) {
13035 switch (var->getType().getObjCLifetime()) {
13036 case Qualifiers::OCL_None:
13037 case Qualifiers::OCL_ExplicitNone:
13038 case Qualifiers::OCL_Autoreleasing:
13039 break;
13040
13041 case Qualifiers::OCL_Weak:
13042 case Qualifiers::OCL_Strong:
13043 setFunctionHasBranchProtectedScope();
13044 break;
13045 }
13046 }
13047
13048 if (var->hasLocalStorage() &&
13049 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13050 setFunctionHasBranchProtectedScope();
13051
13052 // Warn about externally-visible variables being defined without a
13053 // prior declaration. We only want to do this for global
13054 // declarations, but we also specifically need to avoid doing it for
13055 // class members because the linkage of an anonymous class can
13056 // change if it's later given a typedef name.
13057 if (var->isThisDeclarationADefinition() &&
13058 var->getDeclContext()->getRedeclContext()->isFileContext() &&
13059 var->isExternallyVisible() && var->hasLinkage() &&
13060 !var->isInline() && !var->getDescribedVarTemplate() &&
13061 !isa<VarTemplatePartialSpecializationDecl>(var) &&
13062 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13063 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13064 var->getLocation())) {
13065 // Find a previous declaration that's not a definition.
13066 VarDecl *prev = var->getPreviousDecl();
13067 while (prev && prev->isThisDeclarationADefinition())
13068 prev = prev->getPreviousDecl();
13069
13070 if (!prev) {
13071 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13072 Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13073 << /* variable */ 0;
13074 }
13075 }
13076
13077 // Cache the result of checking for constant initialization.
13078 Optional<bool> CacheHasConstInit;
13079 const Expr *CacheCulprit = nullptr;
13080 auto checkConstInit = [&]() mutable {
13081 if (!CacheHasConstInit)
13082 CacheHasConstInit = var->getInit()->isConstantInitializer(
13083 Context, var->getType()->isReferenceType(), &CacheCulprit);
13084 return *CacheHasConstInit;
13085 };
13086
13087 if (var->getTLSKind() == VarDecl::TLS_Static) {
13088 if (var->getType().isDestructedType()) {
13089 // GNU C++98 edits for __thread, [basic.start.term]p3:
13090 // The type of an object with thread storage duration shall not
13091 // have a non-trivial destructor.
13092 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13093 if (getLangOpts().CPlusPlus11)
13094 Diag(var->getLocation(), diag::note_use_thread_local);
13095 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13096 if (!checkConstInit()) {
13097 // GNU C++98 edits for __thread, [basic.start.init]p4:
13098 // An object of thread storage duration shall not require dynamic
13099 // initialization.
13100 // FIXME: Need strict checking here.
13101 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13102 << CacheCulprit->getSourceRange();
13103 if (getLangOpts().CPlusPlus11)
13104 Diag(var->getLocation(), diag::note_use_thread_local);
13105 }
13106 }
13107 }
13108
13109
13110 if (!var->getType()->isStructureType() && var->hasInit() &&
13111 isa<InitListExpr>(var->getInit())) {
13112 const auto *ILE = cast<InitListExpr>(var->getInit());
13113 unsigned NumInits = ILE->getNumInits();
13114 if (NumInits > 2)
13115 for (unsigned I = 0; I < NumInits; ++I) {
13116 const auto *Init = ILE->getInit(I);
13117 if (!Init)
13118 break;
13119 const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13120 if (!SL)
13121 break;
13122
13123 unsigned NumConcat = SL->getNumConcatenated();
13124 // Diagnose missing comma in string array initialization.
13125 // Do not warn when all the elements in the initializer are concatenated
13126 // together. Do not warn for macros too.
13127 if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13128 bool OnlyOneMissingComma = true;
13129 for (unsigned J = I + 1; J < NumInits; ++J) {
13130 const auto *Init = ILE->getInit(J);
13131 if (!Init)
13132 break;
13133 const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13134 if (!SLJ || SLJ->getNumConcatenated() > 1) {
13135 OnlyOneMissingComma = false;
13136 break;
13137 }
13138 }
13139
13140 if (OnlyOneMissingComma) {
13141 SmallVector<FixItHint, 1> Hints;
13142 for (unsigned i = 0; i < NumConcat - 1; ++i)
13143 Hints.push_back(FixItHint::CreateInsertion(
13144 PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13145
13146 Diag(SL->getStrTokenLoc(1),
13147 diag::warn_concatenated_literal_array_init)
13148 << Hints;
13149 Diag(SL->getBeginLoc(),
13150 diag::note_concatenated_string_literal_silence);
13151 }
13152 // In any case, stop now.
13153 break;
13154 }
13155 }
13156 }
13157
13158
13159 QualType type = var->getType();
13160
13161 if (var->hasAttr<BlocksAttr>())
13162 getCurFunction()->addByrefBlockVar(var);
13163
13164 Expr *Init = var->getInit();
13165 bool GlobalStorage = var->hasGlobalStorage();
13166 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13167 QualType baseType = Context.getBaseElementType(type);
13168 bool HasConstInit = true;
13169
13170 // Check whether the initializer is sufficiently constant.
13171 if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13172 !Init->isValueDependent() &&
13173 (GlobalStorage || var->isConstexpr() ||
13174 var->mightBeUsableInConstantExpressions(Context))) {
13175 // If this variable might have a constant initializer or might be usable in
13176 // constant expressions, check whether or not it actually is now. We can't
13177 // do this lazily, because the result might depend on things that change
13178 // later, such as which constexpr functions happen to be defined.
13179 SmallVector<PartialDiagnosticAt, 8> Notes;
13180 if (!getLangOpts().CPlusPlus11) {
13181 // Prior to C++11, in contexts where a constant initializer is required,
13182 // the set of valid constant initializers is described by syntactic rules
13183 // in [expr.const]p2-6.
13184 // FIXME: Stricter checking for these rules would be useful for constinit /
13185 // -Wglobal-constructors.
13186 HasConstInit = checkConstInit();
13187
13188 // Compute and cache the constant value, and remember that we have a
13189 // constant initializer.
13190 if (HasConstInit) {
13191 (void)var->checkForConstantInitialization(Notes);
13192 Notes.clear();
13193 } else if (CacheCulprit) {
13194 Notes.emplace_back(CacheCulprit->getExprLoc(),
13195 PDiag(diag::note_invalid_subexpr_in_const_expr));
13196 Notes.back().second << CacheCulprit->getSourceRange();
13197 }
13198 } else {
13199 // Evaluate the initializer to see if it's a constant initializer.
13200 HasConstInit = var->checkForConstantInitialization(Notes);
13201 }
13202
13203 if (HasConstInit) {
13204 // FIXME: Consider replacing the initializer with a ConstantExpr.
13205 } else if (var->isConstexpr()) {
13206 SourceLocation DiagLoc = var->getLocation();
13207 // If the note doesn't add any useful information other than a source
13208 // location, fold it into the primary diagnostic.
13209 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13210 diag::note_invalid_subexpr_in_const_expr) {
13211 DiagLoc = Notes[0].first;
13212 Notes.clear();
13213 }
13214 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13215 << var << Init->getSourceRange();
13216 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13217 Diag(Notes[I].first, Notes[I].second);
13218 } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13219 auto *Attr = var->getAttr<ConstInitAttr>();
13220 Diag(var->getLocation(), diag::err_require_constant_init_failed)
13221 << Init->getSourceRange();
13222 Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13223 << Attr->getRange() << Attr->isConstinit();
13224 for (auto &it : Notes)
13225 Diag(it.first, it.second);
13226 } else if (IsGlobal &&
13227 !getDiagnostics().isIgnored(diag::warn_global_constructor,
13228 var->getLocation())) {
13229 // Warn about globals which don't have a constant initializer. Don't
13230 // warn about globals with a non-trivial destructor because we already
13231 // warned about them.
13232 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13233 if (!(RD && !RD->hasTrivialDestructor())) {
13234 // checkConstInit() here permits trivial default initialization even in
13235 // C++11 onwards, where such an initializer is not a constant initializer
13236 // but nonetheless doesn't require a global constructor.
13237 if (!checkConstInit())
13238 Diag(var->getLocation(), diag::warn_global_constructor)
13239 << Init->getSourceRange();
13240 }
13241 }
13242 }
13243
13244 // Apply section attributes and pragmas to global variables.
13245 if (GlobalStorage && var->isThisDeclarationADefinition() &&
13246 !inTemplateInstantiation()) {
13247 PragmaStack<StringLiteral *> *Stack = nullptr;
13248 int SectionFlags = ASTContext::PSF_Read;
13249 if (var->getType().isConstQualified()) {
13250 if (HasConstInit)
13251 Stack = &ConstSegStack;
13252 else {
13253 Stack = &BSSSegStack;
13254 SectionFlags |= ASTContext::PSF_Write;
13255 }
13256 } else if (var->hasInit() && HasConstInit) {
13257 Stack = &DataSegStack;
13258 SectionFlags |= ASTContext::PSF_Write;
13259 } else {
13260 Stack = &BSSSegStack;
13261 SectionFlags |= ASTContext::PSF_Write;
13262 }
13263 if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13264 if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13265 SectionFlags |= ASTContext::PSF_Implicit;
13266 UnifySection(SA->getName(), SectionFlags, var);
13267 } else if (Stack->CurrentValue) {
13268 SectionFlags |= ASTContext::PSF_Implicit;
13269 auto SectionName = Stack->CurrentValue->getString();
13270 var->addAttr(SectionAttr::CreateImplicit(
13271 Context, SectionName, Stack->CurrentPragmaLocation,
13272 AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13273 if (UnifySection(SectionName, SectionFlags, var))
13274 var->dropAttr<SectionAttr>();
13275 }
13276
13277 // Apply the init_seg attribute if this has an initializer. If the
13278 // initializer turns out to not be dynamic, we'll end up ignoring this
13279 // attribute.
13280 if (CurInitSeg && var->getInit())
13281 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13282 CurInitSegLoc,
13283 AttributeCommonInfo::AS_Pragma));
13284 }
13285
13286 // All the following checks are C++ only.
13287 if (!getLangOpts().CPlusPlus) {
13288 // If this variable must be emitted, add it as an initializer for the
13289 // current module.
13290 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13291 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13292 return;
13293 }
13294
13295 // Require the destructor.
13296 if (!type->isDependentType())
13297 if (const RecordType *recordType = baseType->getAs<RecordType>())
13298 FinalizeVarWithDestructor(var, recordType);
13299
13300 // If this variable must be emitted, add it as an initializer for the current
13301 // module.
13302 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13303 Context.addModuleInitializer(ModuleScopes.back().Module, var);
13304
13305 // Build the bindings if this is a structured binding declaration.
13306 if (auto *DD = dyn_cast<DecompositionDecl>(var))
13307 CheckCompleteDecompositionDeclaration(DD);
13308}
13309
13310/// Check if VD needs to be dllexport/dllimport due to being in a
13311/// dllexport/import function.
13312void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
13313 assert(VD->isStaticLocal())((void)0);
13314
13315 auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13316
13317 // Find outermost function when VD is in lambda function.
13318 while (FD && !getDLLAttr(FD) &&
13319 !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13320 !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13321 FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13322 }
13323
13324 if (!FD)
13325 return;
13326
13327 // Static locals inherit dll attributes from their function.
13328 if (Attr *A = getDLLAttr(FD)) {
13329 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13330 NewAttr->setInherited(true);
13331 VD->addAttr(NewAttr);
13332 } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13333 auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13334 NewAttr->setInherited(true);
13335 VD->addAttr(NewAttr);
13336
13337 // Export this function to enforce exporting this static variable even
13338 // if it is not used in this compilation unit.
13339 if (!FD->hasAttr<DLLExportAttr>())
13340 FD->addAttr(NewAttr);
13341
13342 } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13343 auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13344 NewAttr->setInherited(true);
13345 VD->addAttr(NewAttr);
13346 }
13347}
13348
13349/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13350/// any semantic actions necessary after any initializer has been attached.
13351void Sema::FinalizeDeclaration(Decl *ThisDecl) {
13352 // Note that we are no longer parsing the initializer for this declaration.
13353 ParsingInitForAutoVars.erase(ThisDecl);
13354
13355 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13356 if (!VD)
13357 return;
13358
13359 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13360 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13361 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13362 if (PragmaClangBSSSection.Valid)
13363 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13364 Context, PragmaClangBSSSection.SectionName,
13365 PragmaClangBSSSection.PragmaLocation,
13366 AttributeCommonInfo::AS_Pragma));
13367 if (PragmaClangDataSection.Valid)
13368 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13369 Context, PragmaClangDataSection.SectionName,
13370 PragmaClangDataSection.PragmaLocation,
13371 AttributeCommonInfo::AS_Pragma));
13372 if (PragmaClangRodataSection.Valid)
13373 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13374 Context, PragmaClangRodataSection.SectionName,
13375 PragmaClangRodataSection.PragmaLocation,
13376 AttributeCommonInfo::AS_Pragma));
13377 if (PragmaClangRelroSection.Valid)
13378 VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13379 Context, PragmaClangRelroSection.SectionName,
13380 PragmaClangRelroSection.PragmaLocation,
13381 AttributeCommonInfo::AS_Pragma));
13382 }
13383
13384 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13385 for (auto *BD : DD->bindings()) {
13386 FinalizeDeclaration(BD);
13387 }
13388 }
13389
13390 checkAttributesAfterMerging(*this, *VD);
13391
13392 // Perform TLS alignment check here after attributes attached to the variable
13393 // which may affect the alignment have been processed. Only perform the check
13394 // if the target has a maximum TLS alignment (zero means no constraints).
13395 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13396 // Protect the check so that it's not performed on dependent types and
13397 // dependent alignments (we can't determine the alignment in that case).
13398 if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13399 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13400 if (Context.getDeclAlign(VD) > MaxAlignChars) {
13401 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13402 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13403 << (unsigned)MaxAlignChars.getQuantity();
13404 }
13405 }
13406 }
13407
13408 if (VD->isStaticLocal())
13409 CheckStaticLocalForDllExport(VD);
13410
13411 // Perform check for initializers of device-side global variables.
13412 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13413 // 7.5). We must also apply the same checks to all __shared__
13414 // variables whether they are local or not. CUDA also allows
13415 // constant initializers for __constant__ and __device__ variables.
13416 if (getLangOpts().CUDA)
13417 checkAllowedCUDAInitializer(VD);
13418
13419 // Grab the dllimport or dllexport attribute off of the VarDecl.
13420 const InheritableAttr *DLLAttr = getDLLAttr(VD);
13421
13422 // Imported static data members cannot be defined out-of-line.
13423 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13424 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13425 VD->isThisDeclarationADefinition()) {
13426 // We allow definitions of dllimport class template static data members
13427 // with a warning.
13428 CXXRecordDecl *Context =
13429 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13430 bool IsClassTemplateMember =
13431 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13432 Context->getDescribedClassTemplate();
13433
13434 Diag(VD->getLocation(),
13435 IsClassTemplateMember
13436 ? diag::warn_attribute_dllimport_static_field_definition
13437 : diag::err_attribute_dllimport_static_field_definition);
13438 Diag(IA->getLocation(), diag::note_attribute);
13439 if (!IsClassTemplateMember)
13440 VD->setInvalidDecl();
13441 }
13442 }
13443
13444 // dllimport/dllexport variables cannot be thread local, their TLS index
13445 // isn't exported with the variable.
13446 if (DLLAttr && VD->getTLSKind()) {
13447 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13448 if (F && getDLLAttr(F)) {
13449 assert(VD->isStaticLocal())((void)0);
13450 // But if this is a static local in a dlimport/dllexport function, the
13451 // function will never be inlined, which means the var would never be
13452 // imported, so having it marked import/export is safe.
13453 } else {
13454 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13455 << DLLAttr;
13456 VD->setInvalidDecl();
13457 }
13458 }
13459
13460 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13461 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13462 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13463 << Attr;
13464 VD->dropAttr<UsedAttr>();
13465 }
13466 }
13467 if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13468 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13469 Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13470 << Attr;
13471 VD->dropAttr<RetainAttr>();
13472 }
13473 }
13474
13475 const DeclContext *DC = VD->getDeclContext();
13476 // If there's a #pragma GCC visibility in scope, and this isn't a class
13477 // member, set the visibility of this variable.
13478 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13479 AddPushedVisibilityAttribute(VD);
13480
13481 // FIXME: Warn on unused var template partial specializations.
13482 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13483 MarkUnusedFileScopedDecl(VD);
13484
13485 // Now we have parsed the initializer and can update the table of magic
13486 // tag values.
13487 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13488 !VD->getType()->isIntegralOrEnumerationType())
13489 return;
13490
13491 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13492 const Expr *MagicValueExpr = VD->getInit();
13493 if (!MagicValueExpr) {
13494 continue;
13495 }
13496 Optional<llvm::APSInt> MagicValueInt;
13497 if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13498 Diag(I->getRange().getBegin(),
13499 diag::err_type_tag_for_datatype_not_ice)
13500 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13501 continue;
13502 }
13503 if (MagicValueInt->getActiveBits() > 64) {
13504 Diag(I->getRange().getBegin(),
13505 diag::err_type_tag_for_datatype_too_large)
13506 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13507 continue;
13508 }
13509 uint64_t MagicValue = MagicValueInt->getZExtValue();
13510 RegisterTypeTagForDatatype(I->getArgumentKind(),
13511 MagicValue,
13512 I->getMatchingCType(),
13513 I->getLayoutCompatible(),
13514 I->getMustBeNull());
13515 }
13516}
13517
13518static bool hasDeducedAuto(DeclaratorDecl *DD) {
13519 auto *VD = dyn_cast<VarDecl>(DD);
13520 return VD && !VD->getType()->hasAutoForTrailingReturnType();
13521}
13522
13523Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
13524 ArrayRef<Decl *> Group) {
13525 SmallVector<Decl*, 8> Decls;
13526
13527 if (DS.isTypeSpecOwned())
13528 Decls.push_back(DS.getRepAsDecl());
13529
13530 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13531 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13532 bool DiagnosedMultipleDecomps = false;
13533 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13534 bool DiagnosedNonDeducedAuto = false;
13535
13536 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13537 if (Decl *D = Group[i]) {
13538 // For declarators, there are some additional syntactic-ish checks we need
13539 // to perform.
13540 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13541 if (!FirstDeclaratorInGroup)
13542 FirstDeclaratorInGroup = DD;
13543 if (!FirstDecompDeclaratorInGroup)
13544 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13545 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13546 !hasDeducedAuto(DD))
13547 FirstNonDeducedAutoInGroup = DD;
13548
13549 if (FirstDeclaratorInGroup != DD) {
13550 // A decomposition declaration cannot be combined with any other
13551 // declaration in the same group.
13552 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13553 Diag(FirstDecompDeclaratorInGroup->getLocation(),
13554 diag::err_decomp_decl_not_alone)
13555 << FirstDeclaratorInGroup->getSourceRange()
13556 << DD->getSourceRange();
13557 DiagnosedMultipleDecomps = true;
13558 }
13559
13560 // A declarator that uses 'auto' in any way other than to declare a
13561 // variable with a deduced type cannot be combined with any other
13562 // declarator in the same group.
13563 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13564 Diag(FirstNonDeducedAutoInGroup->getLocation(),
13565 diag::err_auto_non_deduced_not_alone)
13566 << FirstNonDeducedAutoInGroup->getType()
13567 ->hasAutoForTrailingReturnType()
13568 << FirstDeclaratorInGroup->getSourceRange()
13569 << DD->getSourceRange();
13570 DiagnosedNonDeducedAuto = true;
13571 }
13572 }
13573 }
13574
13575 Decls.push_back(D);
13576 }
13577 }
13578
13579 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
13580 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13581 handleTagNumbering(Tag, S);
13582 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13583 getLangOpts().CPlusPlus)
13584 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13585 }
13586 }
13587
13588 return BuildDeclaratorGroup(Decls);
13589}
13590
13591/// BuildDeclaratorGroup - convert a list of declarations into a declaration
13592/// group, performing any necessary semantic checking.
13593Sema::DeclGroupPtrTy
13594Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
13595 // C++14 [dcl.spec.auto]p7: (DR1347)
13596 // If the type that replaces the placeholder type is not the same in each
13597 // deduction, the program is ill-formed.
13598 if (Group.size() > 1) {
13599 QualType Deduced;
13600 VarDecl *DeducedDecl = nullptr;
13601 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13602 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13603 if (!D || D->isInvalidDecl())
13604 break;
13605 DeducedType *DT = D->getType()->getContainedDeducedType();
13606 if (!DT || DT->getDeducedType().isNull())
13607 continue;
13608 if (Deduced.isNull()) {
13609 Deduced = DT->getDeducedType();
13610 DeducedDecl = D;
13611 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13612 auto *AT = dyn_cast<AutoType>(DT);
13613 auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13614 diag::err_auto_different_deductions)
13615 << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13616 << DeducedDecl->getDeclName() << DT->getDeducedType()
13617 << D->getDeclName();
13618 if (DeducedDecl->hasInit())
13619 Dia << DeducedDecl->getInit()->getSourceRange();
13620 if (D->getInit())
13621 Dia << D->getInit()->getSourceRange();
13622 D->setInvalidDecl();
13623 break;
13624 }
13625 }
13626 }
13627
13628 ActOnDocumentableDecls(Group);
13629
13630 return DeclGroupPtrTy::make(
13631 DeclGroupRef::Create(Context, Group.data(), Group.size()));
13632}
13633
13634void Sema::ActOnDocumentableDecl(Decl *D) {
13635 ActOnDocumentableDecls(D);
13636}
13637
13638void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
13639 // Don't parse the comment if Doxygen diagnostics are ignored.
13640 if (Group.empty() || !Group[0])
13641 return;
13642
13643 if (Diags.isIgnored(diag::warn_doc_param_not_found,
13644 Group[0]->getLocation()) &&
13645 Diags.isIgnored(diag::warn_unknown_comment_command_name,
13646 Group[0]->getLocation()))
13647 return;
13648
13649 if (Group.size() >= 2) {
13650 // This is a decl group. Normally it will contain only declarations
13651 // produced from declarator list. But in case we have any definitions or
13652 // additional declaration references:
13653 // 'typedef struct S {} S;'
13654 // 'typedef struct S *S;'
13655 // 'struct S *pS;'
13656 // FinalizeDeclaratorGroup adds these as separate declarations.
13657 Decl *MaybeTagDecl = Group[0];
13658 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13659 Group = Group.slice(1);
13660 }
13661 }
13662
13663 // FIMXE: We assume every Decl in the group is in the same file.
13664 // This is false when preprocessor constructs the group from decls in
13665 // different files (e. g. macros or #include).
13666 Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13667}
13668
13669/// Common checks for a parameter-declaration that should apply to both function
13670/// parameters and non-type template parameters.
13671void Sema::CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D) {
13672 // Check that there are no default arguments inside the type of this
13673 // parameter.
13674 if (getLangOpts().CPlusPlus)
13675 CheckExtraCXXDefaultArguments(D);
13676
13677 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13678 if (D.getCXXScopeSpec().isSet()) {
13679 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13680 << D.getCXXScopeSpec().getRange();
13681 }
13682
13683 // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13684 // simple identifier except [...irrelevant cases...].
13685 switch (D.getName().getKind()) {
13686 case UnqualifiedIdKind::IK_Identifier:
13687 break;
13688
13689 case UnqualifiedIdKind::IK_OperatorFunctionId:
13690 case UnqualifiedIdKind::IK_ConversionFunctionId:
13691 case UnqualifiedIdKind::IK_LiteralOperatorId:
13692 case UnqualifiedIdKind::IK_ConstructorName:
13693 case UnqualifiedIdKind::IK_DestructorName:
13694 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13695 case UnqualifiedIdKind::IK_DeductionGuideName:
13696 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13697 << GetNameForDeclarator(D).getName();
13698 break;
13699
13700 case UnqualifiedIdKind::IK_TemplateId:
13701 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13702 // GetNameForDeclarator would not produce a useful name in this case.
13703 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13704 break;
13705 }
13706}
13707
13708/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13709/// to introduce parameters into function prototype scope.
13710Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
13711 const DeclSpec &DS = D.getDeclSpec();
13712
13713 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13714
13715 // C++03 [dcl.stc]p2 also permits 'auto'.
13716 StorageClass SC = SC_None;
13717 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
13718 SC = SC_Register;
13719 // In C++11, the 'register' storage class specifier is deprecated.
13720 // In C++17, it is not allowed, but we tolerate it as an extension.
13721 if (getLangOpts().CPlusPlus11) {
13722 Diag(DS.getStorageClassSpecLoc(),
13723 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13724 : diag::warn_deprecated_register)
13725 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
13726 }
13727 } else if (getLangOpts().CPlusPlus &&
13728 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
13729 SC = SC_Auto;
13730 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13731 Diag(DS.getStorageClassSpecLoc(),
13732 diag::err_invalid_storage_class_in_func_decl);
13733 D.getMutableDeclSpec().ClearStorageClassSpecs();
13734 }
13735
13736 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13737 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13738 << DeclSpec::getSpecifierName(TSCS);
13739 if (DS.isInlineSpecified())
13740 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13741 << getLangOpts().CPlusPlus17;
13742 if (DS.hasConstexprSpecifier())
13743 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13744 << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13745
13746 DiagnoseFunctionSpecifiers(DS);
13747
13748 CheckFunctionOrTemplateParamDeclarator(S, D);
13749
13750 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13751 QualType parmDeclType = TInfo->getType();
13752
13753 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13754 IdentifierInfo *II = D.getIdentifier();
13755 if (II) {
13756 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13757 ForVisibleRedeclaration);
13758 LookupName(R, S);
13759 if (R.isSingleResult()) {
13760 NamedDecl *PrevDecl = R.getFoundDecl();
13761 if (PrevDecl->isTemplateParameter()) {
13762 // Maybe we will complain about the shadowed template parameter.
13763 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13764 // Just pretend that we didn't see the previous declaration.
13765 PrevDecl = nullptr;
13766 } else if (S->isDeclScope(PrevDecl)) {
13767 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
13768 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13769
13770 // Recover by removing the name
13771 II = nullptr;
13772 D.SetIdentifier(nullptr, D.getIdentifierLoc());
13773 D.setInvalidType(true);
13774 }
13775 }
13776 }
13777
13778 // Temporarily put parameter variables in the translation unit, not
13779 // the enclosing context. This prevents them from accidentally
13780 // looking like class members in C++.
13781 ParmVarDecl *New =
13782 CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
13783 D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
13784
13785 if (D.isInvalidType())
13786 New->setInvalidDecl();
13787
13788 assert(S->isFunctionPrototypeScope())((void)0);
13789 assert(S->getFunctionPrototypeDepth() >= 1)((void)0);
13790 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
13791 S->getNextFunctionPrototypeIndex());
13792
13793 // Add the parameter declaration into this scope.
13794 S->AddDecl(New);
13795 if (II)
13796 IdResolver.AddDecl(New);
13797
13798 ProcessDeclAttributes(S, New, D);
13799
13800 if (D.getDeclSpec().isModulePrivateSpecified())
13801 Diag(New->getLocation(), diag::err_module_private_local)
13802 << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13803 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13804
13805 if (New->hasAttr<BlocksAttr>()) {
13806 Diag(New->getLocation(), diag::err_block_on_nonlocal);
13807 }
13808
13809 if (getLangOpts().OpenCL)
13810 deduceOpenCLAddressSpace(New);
13811
13812 return New;
13813}
13814
13815/// Synthesizes a variable for a parameter arising from a
13816/// typedef.
13817ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
13818 SourceLocation Loc,
13819 QualType T) {
13820 /* FIXME: setting StartLoc == Loc.
13821 Would it be worth to modify callers so as to provide proper source
13822 location for the unnamed parameters, embedding the parameter's type? */
13823 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
13824 T, Context.getTrivialTypeSourceInfo(T, Loc),
13825 SC_None, nullptr);
13826 Param->setImplicit();
13827 return Param;
13828}
13829
13830void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
13831 // Don't diagnose unused-parameter errors in template instantiations; we
13832 // will already have done so in the template itself.
13833 if (inTemplateInstantiation())
13834 return;
13835
13836 for (const ParmVarDecl *Parameter : Parameters) {
13837 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
13838 !Parameter->hasAttr<UnusedAttr>()) {
13839 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
13840 << Parameter->getDeclName();
13841 }
13842 }
13843}
13844
13845void Sema::DiagnoseSizeOfParametersAndReturnValue(
13846 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
13847 if (LangOpts.NumLargeByValueCopy == 0) // No check.
13848 return;
13849
13850 // Warn if the return value is pass-by-value and larger than the specified
13851 // threshold.
13852 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
13853 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
13854 if (Size > LangOpts.NumLargeByValueCopy)
13855 Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
13856 }
13857
13858 // Warn if any parameter is pass-by-value and larger than the specified
13859 // threshold.
13860 for (const ParmVarDecl *Parameter : Parameters) {
13861 QualType T = Parameter->getType();
13862 if (T->isDependentType() || !T.isPODType(Context))
13863 continue;
13864 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
13865 if (Size > LangOpts.NumLargeByValueCopy)
13866 Diag(Parameter->getLocation(), diag::warn_parameter_size)
13867 << Parameter << Size;
13868 }
13869}
13870
13871ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
13872 SourceLocation NameLoc, IdentifierInfo *Name,
13873 QualType T, TypeSourceInfo *TSInfo,
13874 StorageClass SC) {
13875 // In ARC, infer a lifetime qualifier for appropriate parameter types.
13876 if (getLangOpts().ObjCAutoRefCount &&
13877 T.getObjCLifetime() == Qualifiers::OCL_None &&
13878 T->isObjCLifetimeType()) {
13879
13880 Qualifiers::ObjCLifetime lifetime;
13881
13882 // Special cases for arrays:
13883 // - if it's const, use __unsafe_unretained
13884 // - otherwise, it's an error
13885 if (T->isArrayType()) {
13886 if (!T.isConstQualified()) {
13887 if (DelayedDiagnostics.shouldDelayDiagnostics())
13888 DelayedDiagnostics.add(
13889 sema::DelayedDiagnostic::makeForbiddenType(
13890 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
13891 else
13892 Diag(NameLoc, diag::err_arc_array_param_no_ownership)
13893 << TSInfo->getTypeLoc().getSourceRange();
13894 }
13895 lifetime = Qualifiers::OCL_ExplicitNone;
13896 } else {
13897 lifetime = T->getObjCARCImplicitLifetime();
13898 }
13899 T = Context.getLifetimeQualifiedType(T, lifetime);
13900 }
13901
13902 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
13903 Context.getAdjustedParameterType(T),
13904 TSInfo, SC, nullptr);
13905
13906 // Make a note if we created a new pack in the scope of a lambda, so that
13907 // we know that references to that pack must also be expanded within the
13908 // lambda scope.
13909 if (New->isParameterPack())
13910 if (auto *LSI = getEnclosingLambda())
13911 LSI->LocalPacks.push_back(New);
13912
13913 if (New->getType().hasNonTrivialToPrimitiveDestructCUnion() ||
13914 New->getType().hasNonTrivialToPrimitiveCopyCUnion())
13915 checkNonTrivialCUnion(New->getType(), New->getLocation(),
13916 NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
13917
13918 // Parameters can not be abstract class types.
13919 // For record types, this is done by the AbstractClassUsageDiagnoser once
13920 // the class has been completely parsed.
13921 if (!CurContext->isRecord() &&
13922 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
13923 AbstractParamType))
13924 New->setInvalidDecl();
13925
13926 // Parameter declarators cannot be interface types. All ObjC objects are
13927 // passed by reference.
13928 if (T->isObjCObjectType()) {
13929 SourceLocation TypeEndLoc =
13930 getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
13931 Diag(NameLoc,
13932 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
13933 << FixItHint::CreateInsertion(TypeEndLoc, "*");
13934 T = Context.getObjCObjectPointerType(T);
13935 New->setType(T);
13936 }
13937
13938 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
13939 // duration shall not be qualified by an address-space qualifier."
13940 // Since all parameters have automatic store duration, they can not have
13941 // an address space.
13942 if (T.getAddressSpace() != LangAS::Default &&
13943 // OpenCL allows function arguments declared to be an array of a type
13944 // to be qualified with an address space.
13945 !(getLangOpts().OpenCL &&
13946 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
13947 Diag(NameLoc, diag::err_arg_with_address_space);
13948 New->setInvalidDecl();
13949 }
13950
13951 // PPC MMA non-pointer types are not allowed as function argument types.
13952 if (Context.getTargetInfo().getTriple().isPPC64() &&
13953 CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
13954 New->setInvalidDecl();
13955 }
13956
13957 return New;
13958}
13959
13960void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
13961 SourceLocation LocAfterDecls) {
13962 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
13963
13964 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
13965 // for a K&R function.
13966 if (!FTI.hasPrototype) {
13967 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
13968 --i;
13969 if (FTI.Params[i].Param == nullptr) {
13970 SmallString<256> Code;
13971 llvm::raw_svector_ostream(Code)
13972 << " int " << FTI.Params[i].Ident->getName() << ";\n";
13973 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
13974 << FTI.Params[i].Ident
13975 << FixItHint::CreateInsertion(LocAfterDecls, Code);
13976
13977 // Implicitly declare the argument as type 'int' for lack of a better
13978 // type.
13979 AttributeFactory attrs;
13980 DeclSpec DS(attrs);
13981 const char* PrevSpec; // unused
13982 unsigned DiagID; // unused
13983 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
13984 DiagID, Context.getPrintingPolicy());
13985 // Use the identifier location for the type source range.
13986 DS.SetRangeStart(FTI.Params[i].IdentLoc);
13987 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
13988 Declarator ParamD(DS, DeclaratorContext::KNRTypeList);
13989 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
13990 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
13991 }
13992 }
13993 }
13994}
13995
13996Decl *
13997Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
13998 MultiTemplateParamsArg TemplateParameterLists,
13999 SkipBodyInfo *SkipBody) {
14000 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")((void)0);
14001 assert(D.isFunctionDeclarator() && "Not a function declarator!")((void)0);
14002 Scope *ParentScope = FnBodyScope->getParent();
14003
14004 // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14005 // we define a non-templated function definition, we will create a declaration
14006 // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14007 // The base function declaration will have the equivalent of an `omp declare
14008 // variant` annotation which specifies the mangled definition as a
14009 // specialization function under the OpenMP context defined as part of the
14010 // `omp begin declare variant`.
14011 SmallVector<FunctionDecl *, 4> Bases;
14012 if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14013 ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14014 ParentScope, D, TemplateParameterLists, Bases);
14015
14016 D.setFunctionDefinitionKind(FunctionDefinitionKind::Definition);
14017 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14018 Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14019
14020 if (!Bases.empty())
14021 ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14022
14023 return Dcl;
14024}
14025
14026void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
14027 Consumer.HandleInlineFunctionDefinition(D);
14028}
14029
14030static bool
14031ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
14032 const FunctionDecl *&PossiblePrototype) {
14033 // Don't warn about invalid declarations.
14034 if (FD->isInvalidDecl())
14035 return false;
14036
14037 // Or declarations that aren't global.
14038 if (!FD->isGlobal())
14039 return false;
14040
14041 // Don't warn about C++ member functions.
14042 if (isa<CXXMethodDecl>(FD))
14043 return false;
14044
14045 // Don't warn about 'main'.
14046 if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14047 if (IdentifierInfo *II = FD->getIdentifier())
14048 if (II->isStr("main") || II->isStr("efi_main"))
14049 return false;
14050
14051 // Don't warn about inline functions.
14052 if (FD->isInlined())
14053 return false;
14054
14055 // Don't warn about function templates.
14056 if (FD->getDescribedFunctionTemplate())
14057 return false;
14058
14059 // Don't warn about function template specializations.
14060 if (FD->isFunctionTemplateSpecialization())
14061 return false;
14062
14063 // Don't warn for OpenCL kernels.
14064 if (FD->hasAttr<OpenCLKernelAttr>())
14065 return false;
14066
14067 // Don't warn on explicitly deleted functions.
14068 if (FD->isDeleted())
14069 return false;
14070
14071 for (const FunctionDecl *Prev = FD->getPreviousDecl();
14072 Prev; Prev = Prev->getPreviousDecl()) {
14073 // Ignore any declarations that occur in function or method
14074 // scope, because they aren't visible from the header.
14075 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14076 continue;
14077
14078 PossiblePrototype = Prev;
14079 return Prev->getType()->isFunctionNoProtoType();
14080 }
14081
14082 return true;
14083}
14084
14085void
14086Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
14087 const FunctionDecl *EffectiveDefinition,
14088 SkipBodyInfo *SkipBody) {
14089 const FunctionDecl *Definition = EffectiveDefinition;
14090 if (!Definition &&
14091 !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14092 return;
14093
14094 if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14095 if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14096 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14097 // A merged copy of the same function, instantiated as a member of
14098 // the same class, is OK.
14099 if (declaresSameEntity(OrigFD, OrigDef) &&
14100 declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14101 cast<Decl>(FD->getLexicalDeclContext())))
14102 return;
14103 }
14104 }
14105 }
14106
14107 if (canRedefineFunction(Definition, getLangOpts()))
14108 return;
14109
14110 // Don't emit an error when this is redefinition of a typo-corrected
14111 // definition.
14112 if (TypoCorrectedFunctionDefinitions.count(Definition))
14113 return;
14114
14115 // If we don't have a visible definition of the function, and it's inline or
14116 // a template, skip the new definition.
14117 if (SkipBody && !hasVisibleDefinition(Definition) &&
14118 (Definition->getFormalLinkage() == InternalLinkage ||
14119 Definition->isInlined() ||
14120 Definition->getDescribedFunctionTemplate() ||
14121 Definition->getNumTemplateParameterLists())) {
14122 SkipBody->ShouldSkip = true;
14123 SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14124 if (auto *TD = Definition->getDescribedFunctionTemplate())
14125 makeMergedDefinitionVisible(TD);
14126 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14127 return;
14128 }
14129
14130 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14131 Definition->getStorageClass() == SC_Extern)
14132 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14133 << FD << getLangOpts().CPlusPlus;
14134 else
14135 Diag(FD->getLocation(), diag::err_redefinition) << FD;
14136
14137 Diag(Definition->getLocation(), diag::note_previous_definition);
14138 FD->setInvalidDecl();
14139}
14140
14141static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14142 Sema &S) {
14143 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14144
14145 LambdaScopeInfo *LSI = S.PushLambdaScope();
14146 LSI->CallOperator = CallOperator;
14147 LSI->Lambda = LambdaClass;
14148 LSI->ReturnType = CallOperator->getReturnType();
14149 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14150
14151 if (LCD == LCD_None)
14152 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
14153 else if (LCD == LCD_ByCopy)
14154 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
14155 else if (LCD == LCD_ByRef)
14156 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
14157 DeclarationNameInfo DNI = CallOperator->getNameInfo();
14158
14159 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
14160 LSI->Mutable = !CallOperator->isConst();
14161
14162 // Add the captures to the LSI so they can be noted as already
14163 // captured within tryCaptureVar.
14164 auto I = LambdaClass->field_begin();
14165 for (const auto &C : LambdaClass->captures()) {
14166 if (C.capturesVariable()) {
14167 VarDecl *VD = C.getCapturedVar();
14168 if (VD->isInitCapture())
14169 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
14170 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14171 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14172 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14173 /*EllipsisLoc*/C.isPackExpansion()
14174 ? C.getEllipsisLoc() : SourceLocation(),
14175 I->getType(), /*Invalid*/false);
14176
14177 } else if (C.capturesThis()) {
14178 LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14179 C.getCaptureKind() == LCK_StarThis);
14180 } else {
14181 LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14182 I->getType());
14183 }
14184 ++I;
14185 }
14186}
14187
14188Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
14189 SkipBodyInfo *SkipBody) {
14190 if (!D) {
14191 // Parsing the function declaration failed in some way. Push on a fake scope
14192 // anyway so we can try to parse the function body.
14193 PushFunctionScope();
14194 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14195 return D;
14196 }
14197
14198 FunctionDecl *FD = nullptr;
14199
14200 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14201 FD = FunTmpl->getTemplatedDecl();
14202 else
14203 FD = cast<FunctionDecl>(D);
14204
14205 // Do not push if it is a lambda because one is already pushed when building
14206 // the lambda in ActOnStartOfLambdaDefinition().
14207 if (!isLambdaCallOperator(FD))
14208 PushExpressionEvaluationContext(
14209 FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14210 : ExprEvalContexts.back().Context);
14211
14212 // Check for defining attributes before the check for redefinition.
14213 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14214 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14215 FD->dropAttr<AliasAttr>();
14216 FD->setInvalidDecl();
14217 }
14218 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14219 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14220 FD->dropAttr<IFuncAttr>();
14221 FD->setInvalidDecl();
14222 }
14223
14224 if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14225 if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14226 Ctor->isDefaultConstructor() &&
14227 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14228 // If this is an MS ABI dllexport default constructor, instantiate any
14229 // default arguments.
14230 InstantiateDefaultCtorDefaultArgs(Ctor);
14231 }
14232 }
14233
14234 // See if this is a redefinition. If 'will have body' (or similar) is already
14235 // set, then these checks were already performed when it was set.
14236 if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14237 !FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
14238 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14239
14240 // If we're skipping the body, we're done. Don't enter the scope.
14241 if (SkipBody && SkipBody->ShouldSkip)
14242 return D;
14243 }
14244
14245 // Mark this function as "will have a body eventually". This lets users to
14246 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14247 // this function.
14248 FD->setWillHaveBody();
14249
14250 // If we are instantiating a generic lambda call operator, push
14251 // a LambdaScopeInfo onto the function stack. But use the information
14252 // that's already been calculated (ActOnLambdaExpr) to prime the current
14253 // LambdaScopeInfo.
14254 // When the template operator is being specialized, the LambdaScopeInfo,
14255 // has to be properly restored so that tryCaptureVariable doesn't try
14256 // and capture any new variables. In addition when calculating potential
14257 // captures during transformation of nested lambdas, it is necessary to
14258 // have the LSI properly restored.
14259 if (isGenericLambdaCallOperatorSpecialization(FD)) {
14260 assert(inTemplateInstantiation() &&((void)0)
14261 "There should be an active template instantiation on the stack "((void)0)
14262 "when instantiating a generic lambda!")((void)0);
14263 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14264 } else {
14265 // Enter a new function scope
14266 PushFunctionScope();
14267 }
14268
14269 // Builtin functions cannot be defined.
14270 if (unsigned BuiltinID = FD->getBuiltinID()) {
14271 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14272 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14273 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14274 FD->setInvalidDecl();
14275 }
14276 }
14277
14278 // The return type of a function definition must be complete
14279 // (C99 6.9.1p3, C++ [dcl.fct]p6).
14280 QualType ResultType = FD->getReturnType();
14281 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14282 !FD->isInvalidDecl() &&
14283 RequireCompleteType(FD->getLocation(), ResultType,
14284 diag::err_func_def_incomplete_result))
14285 FD->setInvalidDecl();
14286
14287 if (FnBodyScope)
14288 PushDeclContext(FnBodyScope, FD);
14289
14290 // Check the validity of our function parameters
14291 CheckParmsForFunctionDef(FD->parameters(),
14292 /*CheckParameterNames=*/true);
14293
14294 // Add non-parameter declarations already in the function to the current
14295 // scope.
14296 if (FnBodyScope) {
14297 for (Decl *NPD : FD->decls()) {
14298 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14299 if (!NonParmDecl)
14300 continue;
14301 assert(!isa<ParmVarDecl>(NonParmDecl) &&((void)0)
14302 "parameters should not be in newly created FD yet")((void)0);
14303
14304 // If the decl has a name, make it accessible in the current scope.
14305 if (NonParmDecl->getDeclName())
14306 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14307
14308 // Similarly, dive into enums and fish their constants out, making them
14309 // accessible in this scope.
14310 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14311 for (auto *EI : ED->enumerators())
14312 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14313 }
14314 }
14315 }
14316
14317 // Introduce our parameters into the function scope
14318 for (auto Param : FD->parameters()) {
14319 Param->setOwningFunction(FD);
14320
14321 // If this has an identifier, add it to the scope stack.
14322 if (Param->getIdentifier() && FnBodyScope) {
14323 CheckShadow(FnBodyScope, Param);
14324
14325 PushOnScopeChains(Param, FnBodyScope);
14326 }
14327 }
14328
14329 // Ensure that the function's exception specification is instantiated.
14330 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14331 ResolveExceptionSpec(D->getLocation(), FPT);
14332
14333 // dllimport cannot be applied to non-inline function definitions.
14334 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14335 !FD->isTemplateInstantiation()) {
14336 assert(!FD->hasAttr<DLLExportAttr>())((void)0);
14337 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14338 FD->setInvalidDecl();
14339 return D;
14340 }
14341 // We want to attach documentation to original Decl (which might be
14342 // a function template).
14343 ActOnDocumentableDecl(D);
14344 if (getCurLexicalContext()->isObjCContainer() &&
14345 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14346 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14347 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14348
14349 return D;
14350}
14351
14352/// Given the set of return statements within a function body,
14353/// compute the variables that are subject to the named return value
14354/// optimization.
14355///
14356/// Each of the variables that is subject to the named return value
14357/// optimization will be marked as NRVO variables in the AST, and any
14358/// return statement that has a marked NRVO variable as its NRVO candidate can
14359/// use the named return value optimization.
14360///
14361/// This function applies a very simplistic algorithm for NRVO: if every return
14362/// statement in the scope of a variable has the same NRVO candidate, that
14363/// candidate is an NRVO variable.
14364void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
14365 ReturnStmt **Returns = Scope->Returns.data();
14366
14367 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14368 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14369 if (!NRVOCandidate->isNRVOVariable())
14370 Returns[I]->setNRVOCandidate(nullptr);
14371 }
14372 }
14373}
14374
14375bool Sema::canDelayFunctionBody(const Declarator &D) {
14376 // We can't delay parsing the body of a constexpr function template (yet).
14377 if (D.getDeclSpec().hasConstexprSpecifier())
14378 return false;
14379
14380 // We can't delay parsing the body of a function template with a deduced
14381 // return type (yet).
14382 if (D.getDeclSpec().hasAutoTypeSpec()) {
14383 // If the placeholder introduces a non-deduced trailing return type,
14384 // we can still delay parsing it.
14385 if (D.getNumTypeObjects()) {
14386 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14387 if (Outer.Kind == DeclaratorChunk::Function &&
14388 Outer.Fun.hasTrailingReturnType()) {
14389 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14390 return Ty.isNull() || !Ty->isUndeducedType();
14391 }
14392 }
14393 return false;
14394 }
14395
14396 return true;
14397}
14398
14399bool Sema::canSkipFunctionBody(Decl *D) {
14400 // We cannot skip the body of a function (or function template) which is
14401 // constexpr, since we may need to evaluate its body in order to parse the
14402 // rest of the file.
14403 // We cannot skip the body of a function with an undeduced return type,
14404 // because any callers of that function need to know the type.
14405 if (const FunctionDecl *FD = D->getAsFunction()) {
14406 if (FD->isConstexpr())
14407 return false;
14408 // We can't simply call Type::isUndeducedType here, because inside template
14409 // auto can be deduced to a dependent type, which is not considered
14410 // "undeduced".
14411 if (FD->getReturnType()->getContainedDeducedType())
14412 return false;
14413 }
14414 return Consumer.shouldSkipFunctionBody(D);
14415}
14416
14417Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
14418 if (!Decl)
14419 return nullptr;
14420 if (FunctionDecl *FD = Decl->getAsFunction())
14421 FD->setHasSkippedBody();
14422 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14423 MD->setHasSkippedBody();
14424 return Decl;
14425}
14426
14427Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
14428 return ActOnFinishFunctionBody(D, BodyArg, false);
14429}
14430
14431/// RAII object that pops an ExpressionEvaluationContext when exiting a function
14432/// body.
14433class ExitFunctionBodyRAII {
14434public:
14435 ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14436 ~ExitFunctionBodyRAII() {
14437 if (!IsLambda)
14438 S.PopExpressionEvaluationContext();
14439 }
14440
14441private:
14442 Sema &S;
14443 bool IsLambda = false;
14444};
14445
14446static void diagnoseImplicitlyRetainedSelf(Sema &S) {
14447 llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14448
14449 auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14450 if (EscapeInfo.count(BD))
14451 return EscapeInfo[BD];
14452
14453 bool R = false;
14454 const BlockDecl *CurBD = BD;
14455
14456 do {
14457 R = !CurBD->doesNotEscape();
14458 if (R)
14459 break;
14460 CurBD = CurBD->getParent()->getInnermostBlockDecl();
14461 } while (CurBD);
14462
14463 return EscapeInfo[BD] = R;
14464 };
14465
14466 // If the location where 'self' is implicitly retained is inside a escaping
14467 // block, emit a diagnostic.
14468 for (const std::pair<SourceLocation, const BlockDecl *> &P :
14469 S.ImplicitlyRetainedSelfLocs)
14470 if (IsOrNestedInEscapingBlock(P.second))
14471 S.Diag(P.first, diag::warn_implicitly_retains_self)
14472 << FixItHint::CreateInsertion(P.first, "self->");
14473}
14474
14475Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
14476 bool IsInstantiation) {
14477 FunctionScopeInfo *FSI = getCurFunction();
14478 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14479
14480 if (FSI->UsesFPIntrin && !FD->hasAttr<StrictFPAttr>())
14481 FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14482
14483 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14484 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14485
14486 if (getLangOpts().Coroutines && FSI->isCoroutine())
14487 CheckCompletedCoroutineBody(FD, Body);
14488
14489 // Do not call PopExpressionEvaluationContext() if it is a lambda because one
14490 // is already popped when finishing the lambda in BuildLambdaExpr(). This is
14491 // meant to pop the context added in ActOnStartOfFunctionDef().
14492 ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14493
14494 if (FD) {
14495 FD->setBody(Body);
14496 FD->setWillHaveBody(false);
14497
14498 if (getLangOpts().CPlusPlus14) {
14499 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14500 FD->getReturnType()->isUndeducedType()) {
14501 // If the function has a deduced result type but contains no 'return'
14502 // statements, the result type as written must be exactly 'auto', and
14503 // the deduced result type is 'void'.
14504 if (!FD->getReturnType()->getAs<AutoType>()) {
14505 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14506 << FD->getReturnType();
14507 FD->setInvalidDecl();
14508 } else {
14509 // Substitute 'void' for the 'auto' in the type.
14510 TypeLoc ResultType = getReturnTypeLoc(FD);
14511 Context.adjustDeducedFunctionResultType(
14512 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
14513 }
14514 }
14515 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14516 // In C++11, we don't use 'auto' deduction rules for lambda call
14517 // operators because we don't support return type deduction.
14518 auto *LSI = getCurLambda();
14519 if (LSI->HasImplicitReturnType) {
14520 deduceClosureReturnType(*LSI);
14521
14522 // C++11 [expr.prim.lambda]p4:
14523 // [...] if there are no return statements in the compound-statement
14524 // [the deduced type is] the type void
14525 QualType RetType =
14526 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14527
14528 // Update the return type to the deduced type.
14529 const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14530 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14531 Proto->getExtProtoInfo()));
14532 }
14533 }
14534
14535 // If the function implicitly returns zero (like 'main') or is naked,
14536 // don't complain about missing return statements.
14537 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14538 WP.disableCheckFallThrough();
14539
14540 // MSVC permits the use of pure specifier (=0) on function definition,
14541 // defined at class scope, warn about this non-standard construct.
14542 if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14543 Diag(FD->getLocation(), diag::ext_pure_function_definition);
14544
14545 if (!FD->isInvalidDecl()) {
14546 // Don't diagnose unused parameters of defaulted or deleted functions.
14547 if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
14548 DiagnoseUnusedParameters(FD->parameters());
14549 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14550 FD->getReturnType(), FD);
14551
14552 // If this is a structor, we need a vtable.
14553 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14554 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14555 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
14556 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14557
14558 // Try to apply the named return value optimization. We have to check
14559 // if we can do this here because lambdas keep return statements around
14560 // to deduce an implicit return type.
14561 if (FD->getReturnType()->isRecordType() &&
14562 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14563 computeNRVO(Body, FSI);
14564 }
14565
14566 // GNU warning -Wmissing-prototypes:
14567 // Warn if a global function is defined without a previous
14568 // prototype declaration. This warning is issued even if the
14569 // definition itself provides a prototype. The aim is to detect
14570 // global functions that fail to be declared in header files.
14571 const FunctionDecl *PossiblePrototype = nullptr;
14572 if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14573 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14574
14575 if (PossiblePrototype) {
14576 // We found a declaration that is not a prototype,
14577 // but that could be a zero-parameter prototype
14578 if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14579 TypeLoc TL = TI->getTypeLoc();
14580 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
14581 Diag(PossiblePrototype->getLocation(),
14582 diag::note_declaration_not_a_prototype)
14583 << (FD->getNumParams() != 0)
14584 << (FD->getNumParams() == 0
14585 ? FixItHint::CreateInsertion(FTL.getRParenLoc(), "void")
14586 : FixItHint{});
14587 }
14588 } else {
14589 // Returns true if the token beginning at this Loc is `const`.
14590 auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14591 const LangOptions &LangOpts) {
14592 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14593 if (LocInfo.first.isInvalid())
14594 return false;
14595
14596 bool Invalid = false;
14597 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14598 if (Invalid)
14599 return false;
14600
14601 if (LocInfo.second > Buffer.size())
14602 return false;
14603
14604 const char *LexStart = Buffer.data() + LocInfo.second;
14605 StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14606
14607 return StartTok.consume_front("const") &&
14608 (StartTok.empty() || isWhitespace(StartTok[0]) ||
14609 StartTok.startswith("/*") || StartTok.startswith("//"));
14610 };
14611
14612 auto findBeginLoc = [&]() {
14613 // If the return type has `const` qualifier, we want to insert
14614 // `static` before `const` (and not before the typename).
14615 if ((FD->getReturnType()->isAnyPointerType() &&
14616 FD->getReturnType()->getPointeeType().isConstQualified()) ||
14617 FD->getReturnType().isConstQualified()) {
14618 // But only do this if we can determine where the `const` is.
14619
14620 if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14621 getLangOpts()))
14622
14623 return FD->getBeginLoc();
14624 }
14625 return FD->getTypeSpecStartLoc();
14626 };
14627 Diag(FD->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
14628 << /* function */ 1
14629 << (FD->getStorageClass() == SC_None
14630 ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14631 : FixItHint{});
14632 }
14633
14634 // GNU warning -Wstrict-prototypes
14635 // Warn if K&R function is defined without a previous declaration.
14636 // This warning is issued only if the definition itself does not provide
14637 // a prototype. Only K&R definitions do not provide a prototype.
14638 if (!FD->hasWrittenPrototype()) {
14639 TypeSourceInfo *TI = FD->getTypeSourceInfo();
14640 TypeLoc TL = TI->getTypeLoc();
14641 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
14642 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14643 }
14644 }
14645
14646 // Warn on CPUDispatch with an actual body.
14647 if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14648 if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14649 if (!CmpndBody->body_empty())
14650 Diag(CmpndBody->body_front()->getBeginLoc(),
14651 diag::warn_dispatch_body_ignored);
14652
14653 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14654 const CXXMethodDecl *KeyFunction;
14655 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14656 MD->isVirtual() &&
14657 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14658 MD == KeyFunction->getCanonicalDecl()) {
14659 // Update the key-function state if necessary for this ABI.
14660 if (FD->isInlined() &&
14661 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
14662 Context.setNonKeyFunction(MD);
14663
14664 // If the newly-chosen key function is already defined, then we
14665 // need to mark the vtable as used retroactively.
14666 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14667 const FunctionDecl *Definition;
14668 if (KeyFunction && KeyFunction->isDefined(Definition))
14669 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14670 } else {
14671 // We just defined they key function; mark the vtable as used.
14672 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14673 }
14674 }
14675 }
14676
14677 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&((void)0)
14678 "Function parsing confused")((void)0);
14679 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14680 assert(MD == getCurMethodDecl() && "Method parsing confused")((void)0);
14681 MD->setBody(Body);
14682 if (!MD->isInvalidDecl()) {
14683 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14684 MD->getReturnType(), MD);
14685
14686 if (Body)
14687 computeNRVO(Body, FSI);
14688 }
14689 if (FSI->ObjCShouldCallSuper) {
14690 Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14691 << MD->getSelector().getAsString();
14692 FSI->ObjCShouldCallSuper = false;
14693 }
14694 if (FSI->ObjCWarnForNoDesignatedInitChain) {
14695 const ObjCMethodDecl *InitMethod = nullptr;
14696 bool isDesignated =
14697 MD->isDesignatedInitializerForTheInterface(&InitMethod);
14698 assert(isDesignated && InitMethod)((void)0);
14699 (void)isDesignated;
14700
14701 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14702 auto IFace = MD->getClassInterface();
14703 if (!IFace)
14704 return false;
14705 auto SuperD = IFace->getSuperClass();
14706 if (!SuperD)
14707 return false;
14708 return SuperD->getIdentifier() ==
14709 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14710 };
14711 // Don't issue this warning for unavailable inits or direct subclasses
14712 // of NSObject.
14713 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14714 Diag(MD->getLocation(),
14715 diag::warn_objc_designated_init_missing_super_call);
14716 Diag(InitMethod->getLocation(),
14717 diag::note_objc_designated_init_marked_here);
14718 }
14719 FSI->ObjCWarnForNoDesignatedInitChain = false;
14720 }
14721 if (FSI->ObjCWarnForNoInitDelegation) {
14722 // Don't issue this warning for unavaialable inits.
14723 if (!MD->isUnavailable())
14724 Diag(MD->getLocation(),
14725 diag::warn_objc_secondary_init_missing_init_call);
14726 FSI->ObjCWarnForNoInitDelegation = false;
14727 }
14728
14729 diagnoseImplicitlyRetainedSelf(*this);
14730 } else {
14731 // Parsing the function declaration failed in some way. Pop the fake scope
14732 // we pushed on.
14733 PopFunctionScopeInfo(ActivePolicy, dcl);
14734 return nullptr;
14735 }
14736
14737 if (Body && FSI->HasPotentialAvailabilityViolations)
14738 DiagnoseUnguardedAvailabilityViolations(dcl);
14739
14740 assert(!FSI->ObjCShouldCallSuper &&((void)0)
14741 "This should only be set for ObjC methods, which should have been "((void)0)
14742 "handled in the block above.")((void)0);
14743
14744 // Verify and clean out per-function state.
14745 if (Body && (!FD || !FD->isDefaulted())) {
14746 // C++ constructors that have function-try-blocks can't have return
14747 // statements in the handlers of that block. (C++ [except.handle]p14)
14748 // Verify this.
14749 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
14750 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
14751
14752 // Verify that gotos and switch cases don't jump into scopes illegally.
14753 if (FSI->NeedsScopeChecking() &&
14754 !PP.isCodeCompletionEnabled())
14755 DiagnoseInvalidJumps(Body);
14756
14757 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
14758 if (!Destructor->getParent()->isDependentType())
14759 CheckDestructor(Destructor);
14760
14761 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
14762 Destructor->getParent());
14763 }
14764
14765 // If any errors have occurred, clear out any temporaries that may have
14766 // been leftover. This ensures that these temporaries won't be picked up for
14767 // deletion in some later function.
14768 if (hasUncompilableErrorOccurred() ||
14769 getDiagnostics().getSuppressAllDiagnostics()) {
14770 DiscardCleanupsInEvaluationContext();
14771 }
14772 if (!hasUncompilableErrorOccurred() &&
14773 !isa<FunctionTemplateDecl>(dcl)) {
14774 // Since the body is valid, issue any analysis-based warnings that are
14775 // enabled.
14776 ActivePolicy = &WP;
14777 }
14778
14779 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
14780 !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
14781 FD->setInvalidDecl();
14782
14783 if (FD && FD->hasAttr<NakedAttr>()) {
14784 for (const Stmt *S : Body->children()) {
14785 // Allow local register variables without initializer as they don't
14786 // require prologue.
14787 bool RegisterVariables = false;
14788 if (auto *DS = dyn_cast<DeclStmt>(S)) {
14789 for (const auto *Decl : DS->decls()) {
14790 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
14791 RegisterVariables =
14792 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
14793 if (!RegisterVariables)
14794 break;
14795 }
14796 }
14797 }
14798 if (RegisterVariables)
14799 continue;
14800 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
14801 Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
14802 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
14803 FD->setInvalidDecl();
14804 break;
14805 }
14806 }
14807 }
14808
14809 assert(ExprCleanupObjects.size() ==((void)0)
14810 ExprEvalContexts.back().NumCleanupObjects &&((void)0)
14811 "Leftover temporaries in function")((void)0);
14812 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")((void)0);
14813 assert(MaybeODRUseExprs.empty() &&((void)0)
14814 "Leftover expressions for odr-use checking")((void)0);
14815 }
14816
14817 if (!IsInstantiation)
14818 PopDeclContext();
14819
14820 PopFunctionScopeInfo(ActivePolicy, dcl);
14821 // If any errors have occurred, clear out any temporaries that may have
14822 // been leftover. This ensures that these temporaries won't be picked up for
14823 // deletion in some later function.
14824 if (hasUncompilableErrorOccurred()) {
14825 DiscardCleanupsInEvaluationContext();
14826 }
14827
14828 if (FD && (LangOpts.OpenMP || LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
14829 auto ES = getEmissionStatus(FD);
14830 if (ES == Sema::FunctionEmissionStatus::Emitted ||
14831 ES == Sema::FunctionEmissionStatus::Unknown)
14832 DeclsToCheckForDeferredDiags.insert(FD);
14833 }
14834
14835 return dcl;
14836}
14837
14838/// When we finish delayed parsing of an attribute, we must attach it to the
14839/// relevant Decl.
14840void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
14841 ParsedAttributes &Attrs) {
14842 // Always attach attributes to the underlying decl.
14843 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
14844 D = TD->getTemplatedDecl();
14845 ProcessDeclAttributeList(S, D, Attrs);
14846
14847 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
14848 if (Method->isStatic())
14849 checkThisInStaticMemberFunctionAttributes(Method);
14850}
14851
14852/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
14853/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
14854NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
14855 IdentifierInfo &II, Scope *S) {
14856 // Find the scope in which the identifier is injected and the corresponding
14857 // DeclContext.
14858 // FIXME: C89 does not say what happens if there is no enclosing block scope.
14859 // In that case, we inject the declaration into the translation unit scope
14860 // instead.
14861 Scope *BlockScope = S;
14862 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
14863 BlockScope = BlockScope->getParent();
14864
14865 Scope *ContextScope = BlockScope;
14866 while (!ContextScope->getEntity())
14867 ContextScope = ContextScope->getParent();
14868 ContextRAII SavedContext(*this, ContextScope->getEntity());
14869
14870 // Before we produce a declaration for an implicitly defined
14871 // function, see whether there was a locally-scoped declaration of
14872 // this name as a function or variable. If so, use that
14873 // (non-visible) declaration, and complain about it.
14874 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
14875 if (ExternCPrev) {
14876 // We still need to inject the function into the enclosing block scope so
14877 // that later (non-call) uses can see it.
14878 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
14879
14880 // C89 footnote 38:
14881 // If in fact it is not defined as having type "function returning int",
14882 // the behavior is undefined.
14883 if (!isa<FunctionDecl>(ExternCPrev) ||
14884 !Context.typesAreCompatible(
14885 cast<FunctionDecl>(ExternCPrev)->getType(),
14886 Context.getFunctionNoProtoType(Context.IntTy))) {
14887 Diag(Loc, diag::ext_use_out_of_scope_declaration)
14888 << ExternCPrev << !getLangOpts().C99;
14889 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
14890 return ExternCPrev;
14891 }
14892 }
14893
14894 // Extension in C99. Legal in C90, but warn about it.
14895 unsigned diag_id;
14896 if (II.getName().startswith("__builtin_"))
14897 diag_id = diag::warn_builtin_unknown;
14898 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
14899 else if (getLangOpts().OpenCL)
14900 diag_id = diag::err_opencl_implicit_function_decl;
14901 else if (getLangOpts().C99)
14902 diag_id = diag::ext_implicit_function_decl;
14903 else
14904 diag_id = diag::warn_implicit_function_decl;
14905 Diag(Loc, diag_id) << &II;
14906
14907 // If we found a prior declaration of this function, don't bother building
14908 // another one. We've already pushed that one into scope, so there's nothing
14909 // more to do.
14910 if (ExternCPrev)
14911 return ExternCPrev;
14912
14913 // Because typo correction is expensive, only do it if the implicit
14914 // function declaration is going to be treated as an error.
14915 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
14916 TypoCorrection Corrected;
14917 DeclFilterCCC<FunctionDecl> CCC{};
14918 if (S && (Corrected =
14919 CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
14920 S, nullptr, CCC, CTK_NonError)))
14921 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
14922 /*ErrorRecovery*/false);
14923 }
14924
14925 // Set a Declarator for the implicit definition: int foo();
14926 const char *Dummy;
14927 AttributeFactory attrFactory;
14928 DeclSpec DS(attrFactory);
14929 unsigned DiagID;
14930 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
14931 Context.getPrintingPolicy());
14932 (void)Error; // Silence warning.
14933 assert(!Error && "Error setting up implicit decl!")((void)0);
14934 SourceLocation NoLoc;
14935 Declarator D(DS, DeclaratorContext::Block);
14936 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
14937 /*IsAmbiguous=*/false,
14938 /*LParenLoc=*/NoLoc,
14939 /*Params=*/nullptr,
14940 /*NumParams=*/0,
14941 /*EllipsisLoc=*/NoLoc,
14942 /*RParenLoc=*/NoLoc,
14943 /*RefQualifierIsLvalueRef=*/true,
14944 /*RefQualifierLoc=*/NoLoc,
14945 /*MutableLoc=*/NoLoc, EST_None,
14946 /*ESpecRange=*/SourceRange(),
14947 /*Exceptions=*/nullptr,
14948 /*ExceptionRanges=*/nullptr,
14949 /*NumExceptions=*/0,
14950 /*NoexceptExpr=*/nullptr,
14951 /*ExceptionSpecTokens=*/nullptr,
14952 /*DeclsInPrototype=*/None, Loc,
14953 Loc, D),
14954 std::move(DS.getAttributes()), SourceLocation());
14955 D.SetIdentifier(&II, Loc);
14956
14957 // Insert this function into the enclosing block scope.
14958 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
14959 FD->setImplicit();
14960
14961 AddKnownFunctionAttributes(FD);
14962
14963 return FD;
14964}
14965
14966/// If this function is a C++ replaceable global allocation function
14967/// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
14968/// adds any function attributes that we know a priori based on the standard.
14969///
14970/// We need to check for duplicate attributes both here and where user-written
14971/// attributes are applied to declarations.
14972void Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(
14973 FunctionDecl *FD) {
14974 if (FD->isInvalidDecl())
14975 return;
14976
14977 if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
14978 FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
14979 return;
14980
14981 Optional<unsigned> AlignmentParam;
14982 bool IsNothrow = false;
14983 if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
14984 return;
14985
14986 // C++2a [basic.stc.dynamic.allocation]p4:
14987 // An allocation function that has a non-throwing exception specification
14988 // indicates failure by returning a null pointer value. Any other allocation
14989 // function never returns a null pointer value and indicates failure only by
14990 // throwing an exception [...]
14991 if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
14992 FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
14993
14994 // C++2a [basic.stc.dynamic.allocation]p2:
14995 // An allocation function attempts to allocate the requested amount of
14996 // storage. [...] If the request succeeds, the value returned by a
14997 // replaceable allocation function is a [...] pointer value p0 different
14998 // from any previously returned value p1 [...]
14999 //
15000 // However, this particular information is being added in codegen,
15001 // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15002
15003 // C++2a [basic.stc.dynamic.allocation]p2:
15004 // An allocation function attempts to allocate the requested amount of
15005 // storage. If it is successful, it returns the address of the start of a
15006 // block of storage whose length in bytes is at least as large as the
15007 // requested size.
15008 if (!FD->hasAttr<AllocSizeAttr>()) {
15009 FD->addAttr(AllocSizeAttr::CreateImplicit(
15010 Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15011 /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15012 }
15013
15014 // C++2a [basic.stc.dynamic.allocation]p3:
15015 // For an allocation function [...], the pointer returned on a successful
15016 // call shall represent the address of storage that is aligned as follows:
15017 // (3.1) If the allocation function takes an argument of type
15018 // std​::​align_­val_­t, the storage will have the alignment
15019 // specified by the value of this argument.
15020 if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15021 FD->addAttr(AllocAlignAttr::CreateImplicit(
15022 Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15023 }
15024
15025 // FIXME:
15026 // C++2a [basic.stc.dynamic.allocation]p3:
15027 // For an allocation function [...], the pointer returned on a successful
15028 // call shall represent the address of storage that is aligned as follows:
15029 // (3.2) Otherwise, if the allocation function is named operator new[],
15030 // the storage is aligned for any object that does not have
15031 // new-extended alignment ([basic.align]) and is no larger than the
15032 // requested size.
15033 // (3.3) Otherwise, the storage is aligned for any object that does not
15034 // have new-extended alignment and is of the requested size.
15035}
15036
15037/// Adds any function attributes that we know a priori based on
15038/// the declaration of this function.
15039///
15040/// These attributes can apply both to implicitly-declared builtins
15041/// (like __builtin___printf_chk) or to library-declared functions
15042/// like NSLog or printf.
15043///
15044/// We need to check for duplicate attributes both here and where user-written
15045/// attributes are applied to declarations.
15046void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
15047 if (FD->isInvalidDecl())
15048 return;
15049
15050 // If this is a built-in function, map its builtin attributes to
15051 // actual attributes.
15052 if (unsigned BuiltinID = FD->getBuiltinID()) {
15053 // Handle printf-formatting attributes.
15054 unsigned FormatIdx;
15055 bool HasVAListArg;
15056 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15057 if (!FD->hasAttr<FormatAttr>()) {
15058 const char *fmt = "printf";
15059 unsigned int NumParams = FD->getNumParams();
15060 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15061 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15062 fmt = "NSString";
15063 FD->addAttr(FormatAttr::CreateImplicit(Context,
15064 &Context.Idents.get(fmt),
15065 FormatIdx+1,
15066 HasVAListArg ? 0 : FormatIdx+2,
15067 FD->getLocation()));
15068 }
15069 }
15070 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15071 HasVAListArg)) {
15072 if (!FD->hasAttr<FormatAttr>())
15073 FD->addAttr(FormatAttr::CreateImplicit(Context,
15074 &Context.Idents.get("scanf"),
15075 FormatIdx+1,
15076 HasVAListArg ? 0 : FormatIdx+2,
15077 FD->getLocation()));
15078 }
15079
15080 // Handle automatically recognized callbacks.
15081 SmallVector<int, 4> Encoding;
15082 if (!FD->hasAttr<CallbackAttr>() &&
15083 Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15084 FD->addAttr(CallbackAttr::CreateImplicit(
15085 Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15086
15087 // Mark const if we don't care about errno and that is the only thing
15088 // preventing the function from being const. This allows IRgen to use LLVM
15089 // intrinsics for such functions.
15090 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15091 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15092 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15093
15094 // We make "fma" on some platforms const because we know it does not set
15095 // errno in those environments even though it could set errno based on the
15096 // C standard.
15097 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15098 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
15099 !FD->hasAttr<ConstAttr>()) {
15100 switch (BuiltinID) {
15101 case Builtin::BI__builtin_fma:
15102 case Builtin::BI__builtin_fmaf:
15103 case Builtin::BI__builtin_fmal:
15104 case Builtin::BIfma:
15105 case Builtin::BIfmaf:
15106 case Builtin::BIfmal:
15107 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15108 break;
15109 default:
15110 break;
15111 }
15112 }
15113
15114 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15115 !FD->hasAttr<ReturnsTwiceAttr>())
15116 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15117 FD->getLocation()));
15118 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15119 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15120 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15121 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15122 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15123 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15124 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15125 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15126 // Add the appropriate attribute, depending on the CUDA compilation mode
15127 // and which target the builtin belongs to. For example, during host
15128 // compilation, aux builtins are __device__, while the rest are __host__.
15129 if (getLangOpts().CUDAIsDevice !=
15130 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15131 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15132 else
15133 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15134 }
15135 }
15136
15137 AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15138
15139 // If C++ exceptions are enabled but we are told extern "C" functions cannot
15140 // throw, add an implicit nothrow attribute to any extern "C" function we come
15141 // across.
15142 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15143 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15144 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15145 if (!FPT || FPT->getExceptionSpecType() == EST_None)
15146 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15147 }
15148
15149 IdentifierInfo *Name = FD->getIdentifier();
15150 if (!Name)
15151 return;
15152 if ((!getLangOpts().CPlusPlus &&
15153 FD->getDeclContext()->isTranslationUnit()) ||
15154 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15155 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15156 LinkageSpecDecl::lang_c)) {
15157 // Okay: this could be a libc/libm/Objective-C function we know
15158 // about.
15159 } else
15160 return;
15161
15162 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15163 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15164 // target-specific builtins, perhaps?
15165 if (!FD->hasAttr<FormatAttr>())
15166 FD->addAttr(FormatAttr::CreateImplicit(Context,
15167 &Context.Idents.get("printf"), 2,
15168 Name->isStr("vasprintf") ? 0 : 3,
15169 FD->getLocation()));
15170 }
15171
15172 if (Name->isStr("__CFStringMakeConstantString")) {
15173 // We already have a __builtin___CFStringMakeConstantString,
15174 // but builds that use -fno-constant-cfstrings don't go through that.
15175 if (!FD->hasAttr<FormatArgAttr>())
15176 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15177 FD->getLocation()));
15178 }
15179}
15180
15181TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
15182 TypeSourceInfo *TInfo) {
15183 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")((void)0);
15184 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")((void)0);
15185
15186 if (!TInfo) {
15187 assert(D.isInvalidType() && "no declarator info for valid type")((void)0);
15188 TInfo = Context.getTrivialTypeSourceInfo(T);
15189 }
15190
15191 // Scope manipulation handled by caller.
15192 TypedefDecl *NewTD =
15193 TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15194 D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15195
15196 // Bail out immediately if we have an invalid declaration.
15197 if (D.isInvalidType()) {
15198 NewTD->setInvalidDecl();
15199 return NewTD;
15200 }
15201
15202 if (D.getDeclSpec().isModulePrivateSpecified()) {
15203 if (CurContext->isFunctionOrMethod())
15204 Diag(NewTD->getLocation(), diag::err_module_private_local)
15205 << 2 << NewTD
15206 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
15207 << FixItHint::CreateRemoval(
15208 D.getDeclSpec().getModulePrivateSpecLoc());
15209 else
15210 NewTD->setModulePrivate();
15211 }
15212
15213 // C++ [dcl.typedef]p8:
15214 // If the typedef declaration defines an unnamed class (or
15215 // enum), the first typedef-name declared by the declaration
15216 // to be that class type (or enum type) is used to denote the
15217 // class type (or enum type) for linkage purposes only.
15218 // We need to check whether the type was declared in the declaration.
15219 switch (D.getDeclSpec().getTypeSpecType()) {
15220 case TST_enum:
15221 case TST_struct:
15222 case TST_interface:
15223 case TST_union:
15224 case TST_class: {
15225 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15226 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15227 break;
15228 }
15229
15230 default:
15231 break;
15232 }
15233
15234 return NewTD;
15235}
15236
15237/// Check that this is a valid underlying type for an enum declaration.
15238bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
15239 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15240 QualType T = TI->getType();
15241
15242 if (T->isDependentType())
15243 return false;
15244
15245 // This doesn't use 'isIntegralType' despite the error message mentioning
15246 // integral type because isIntegralType would also allow enum types in C.
15247 if (const BuiltinType *BT = T->getAs<BuiltinType>())
15248 if (BT->isInteger())
15249 return false;
15250
15251 if (T->isExtIntType())
15252 return false;
15253
15254 return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15255}
15256
15257/// Check whether this is a valid redeclaration of a previous enumeration.
15258/// \return true if the redeclaration was invalid.
15259bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15260 QualType EnumUnderlyingTy, bool IsFixed,
15261 const EnumDecl *Prev) {
15262 if (IsScoped != Prev->isScoped()) {
15263 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15264 << Prev->isScoped();
15265 Diag(Prev->getLocation(), diag::note_previous_declaration);
15266 return true;
15267 }
15268
15269 if (IsFixed && Prev->isFixed()) {
15270 if (!EnumUnderlyingTy->isDependentType() &&
15271 !Prev->getIntegerType()->isDependentType() &&
15272 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15273 Prev->getIntegerType())) {
15274 // TODO: Highlight the underlying type of the redeclaration.
15275 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15276 << EnumUnderlyingTy << Prev->getIntegerType();
15277 Diag(Prev->getLocation(), diag::note_previous_declaration)
15278 << Prev->getIntegerTypeRange();
15279 return true;
15280 }
15281 } else if (IsFixed != Prev->isFixed()) {
15282 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15283 << Prev->isFixed();
15284 Diag(Prev->getLocation(), diag::note_previous_declaration);
15285 return true;
15286 }
15287
15288 return false;
15289}
15290
15291/// Get diagnostic %select index for tag kind for
15292/// redeclaration diagnostic message.
15293/// WARNING: Indexes apply to particular diagnostics only!
15294///
15295/// \returns diagnostic %select index.
15296static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
15297 switch (Tag) {
15298 case TTK_Struct: return 0;
15299 case TTK_Interface: return 1;
15300 case TTK_Class: return 2;
15301 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")__builtin_unreachable();
15302 }
15303}
15304
15305/// Determine if tag kind is a class-key compatible with
15306/// class for redeclaration (class, struct, or __interface).
15307///
15308/// \returns true iff the tag kind is compatible.
15309static bool isClassCompatTagKind(TagTypeKind Tag)
15310{
15311 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15312}
15313
15314Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
15315 TagTypeKind TTK) {
15316 if (isa<TypedefDecl>(PrevDecl))
15317 return NTK_Typedef;
15318 else if (isa<TypeAliasDecl>(PrevDecl))
15319 return NTK_TypeAlias;
15320 else if (isa<ClassTemplateDecl>(PrevDecl))
15321 return NTK_Template;
15322 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15323 return NTK_TypeAliasTemplate;
15324 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15325 return NTK_TemplateTemplateArgument;
15326 switch (TTK) {
15327 case TTK_Struct:
15328 case TTK_Interface:
15329 case TTK_Class:
15330 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15331 case TTK_Union:
15332 return NTK_NonUnion;
15333 case TTK_Enum:
15334 return NTK_NonEnum;
15335 }
15336 llvm_unreachable("invalid TTK")__builtin_unreachable();
15337}
15338
15339/// Determine whether a tag with a given kind is acceptable
15340/// as a redeclaration of the given tag declaration.
15341///
15342/// \returns true if the new tag kind is acceptable, false otherwise.
15343bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
15344 TagTypeKind NewTag, bool isDefinition,
15345 SourceLocation NewTagLoc,
15346 const IdentifierInfo *Name) {
15347 // C++ [dcl.type.elab]p3:
15348 // The class-key or enum keyword present in the
15349 // elaborated-type-specifier shall agree in kind with the
15350 // declaration to which the name in the elaborated-type-specifier
15351 // refers. This rule also applies to the form of
15352 // elaborated-type-specifier that declares a class-name or
15353 // friend class since it can be construed as referring to the
15354 // definition of the class. Thus, in any
15355 // elaborated-type-specifier, the enum keyword shall be used to
15356 // refer to an enumeration (7.2), the union class-key shall be
15357 // used to refer to a union (clause 9), and either the class or
15358 // struct class-key shall be used to refer to a class (clause 9)
15359 // declared using the class or struct class-key.
15360 TagTypeKind OldTag = Previous->getTagKind();
15361 if (OldTag != NewTag &&
15362 !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15363 return false;
15364
15365 // Tags are compatible, but we might still want to warn on mismatched tags.
15366 // Non-class tags can't be mismatched at this point.
15367 if (!isClassCompatTagKind(NewTag))
15368 return true;
15369
15370 // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15371 // by our warning analysis. We don't want to warn about mismatches with (eg)
15372 // declarations in system headers that are designed to be specialized, but if
15373 // a user asks us to warn, we should warn if their code contains mismatched
15374 // declarations.
15375 auto IsIgnoredLoc = [&](SourceLocation Loc) {
15376 return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15377 Loc);
15378 };
15379 if (IsIgnoredLoc(NewTagLoc))
15380 return true;
15381
15382 auto IsIgnored = [&](const TagDecl *Tag) {
15383 return IsIgnoredLoc(Tag->getLocation());
15384 };
15385 while (IsIgnored(Previous)) {
15386 Previous = Previous->getPreviousDecl();
15387 if (!Previous)
15388 return true;
15389 OldTag = Previous->getTagKind();
15390 }
15391
15392 bool isTemplate = false;
15393 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15394 isTemplate = Record->getDescribedClassTemplate();
15395
15396 if (inTemplateInstantiation()) {
15397 if (OldTag != NewTag) {
15398 // In a template instantiation, do not offer fix-its for tag mismatches
15399 // since they usually mess up the template instead of fixing the problem.
15400 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15401 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15402 << getRedeclDiagFromTagKind(OldTag);
15403 // FIXME: Note previous location?
15404 }
15405 return true;
15406 }
15407
15408 if (isDefinition) {
15409 // On definitions, check all previous tags and issue a fix-it for each
15410 // one that doesn't match the current tag.
15411 if (Previous->getDefinition()) {
15412 // Don't suggest fix-its for redefinitions.
15413 return true;
15414 }
15415
15416 bool previousMismatch = false;
15417 for (const TagDecl *I : Previous->redecls()) {
15418 if (I->getTagKind() != NewTag) {
15419 // Ignore previous declarations for which the warning was disabled.
15420 if (IsIgnored(I))
15421 continue;
15422
15423 if (!previousMismatch) {
15424 previousMismatch = true;
15425 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15426 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15427 << getRedeclDiagFromTagKind(I->getTagKind());
15428 }
15429 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15430 << getRedeclDiagFromTagKind(NewTag)
15431 << FixItHint::CreateReplacement(I->getInnerLocStart(),
15432 TypeWithKeyword::getTagTypeKindName(NewTag));
15433 }
15434 }
15435 return true;
15436 }
15437
15438 // Identify the prevailing tag kind: this is the kind of the definition (if
15439 // there is a non-ignored definition), or otherwise the kind of the prior
15440 // (non-ignored) declaration.
15441 const TagDecl *PrevDef = Previous->getDefinition();
15442 if (PrevDef && IsIgnored(PrevDef))
15443 PrevDef = nullptr;
15444 const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15445 if (Redecl->getTagKind() != NewTag) {
15446 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15447 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15448 << getRedeclDiagFromTagKind(OldTag);
15449 Diag(Redecl->getLocation(), diag::note_previous_use);
15450
15451 // If there is a previous definition, suggest a fix-it.
15452 if (PrevDef) {
15453 Diag(NewTagLoc, diag::note_struct_class_suggestion)
15454 << getRedeclDiagFromTagKind(Redecl->getTagKind())
15455 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
15456 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
15457 }
15458 }
15459
15460 return true;
15461}
15462
15463/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15464/// from an outer enclosing namespace or file scope inside a friend declaration.
15465/// This should provide the commented out code in the following snippet:
15466/// namespace N {
15467/// struct X;
15468/// namespace M {
15469/// struct Y { friend struct /*N::*/ X; };
15470/// }
15471/// }
15472static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
15473 SourceLocation NameLoc) {
15474 // While the decl is in a namespace, do repeated lookup of that name and see
15475 // if we get the same namespace back. If we do not, continue until
15476 // translation unit scope, at which point we have a fully qualified NNS.
15477 SmallVector<IdentifierInfo *, 4> Namespaces;
15478 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15479 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15480 // This tag should be declared in a namespace, which can only be enclosed by
15481 // other namespaces. Bail if there's an anonymous namespace in the chain.
15482 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15483 if (!Namespace || Namespace->isAnonymousNamespace())
15484 return FixItHint();
15485 IdentifierInfo *II = Namespace->getIdentifier();
15486 Namespaces.push_back(II);
15487 NamedDecl *Lookup = SemaRef.LookupSingleName(
15488 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15489 if (Lookup == Namespace)
15490 break;
15491 }
15492
15493 // Once we have all the namespaces, reverse them to go outermost first, and
15494 // build an NNS.
15495 SmallString<64> Insertion;
15496 llvm::raw_svector_ostream OS(Insertion);
15497 if (DC->isTranslationUnit())
15498 OS << "::";
15499 std::reverse(Namespaces.begin(), Namespaces.end());
15500 for (auto *II : Namespaces)
15501 OS << II->getName() << "::";
15502 return FixItHint::CreateInsertion(NameLoc, Insertion);
15503}
15504
15505/// Determine whether a tag originally declared in context \p OldDC can
15506/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15507/// found a declaration in \p OldDC as a previous decl, perhaps through a
15508/// using-declaration).
15509static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
15510 DeclContext *NewDC) {
15511 OldDC = OldDC->getRedeclContext();
15512 NewDC = NewDC->getRedeclContext();
15513
15514 if (OldDC->Equals(NewDC))
15515 return true;
15516
15517 // In MSVC mode, we allow a redeclaration if the contexts are related (either
15518 // encloses the other).
15519 if (S.getLangOpts().MSVCCompat &&
15520 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15521 return true;
15522
15523 return false;
15524}
15525
15526/// This is invoked when we see 'struct foo' or 'struct {'. In the
15527/// former case, Name will be non-null. In the later case, Name will be null.
15528/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15529/// reference/declaration/definition of a tag.
15530///
15531/// \param IsTypeSpecifier \c true if this is a type-specifier (or
15532/// trailing-type-specifier) other than one in an alias-declaration.
15533///
15534/// \param SkipBody If non-null, will be set to indicate if the caller should
15535/// skip the definition of this tag and treat it as if it were a declaration.
15536Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15537 SourceLocation KWLoc, CXXScopeSpec &SS,
15538 IdentifierInfo *Name, SourceLocation NameLoc,
15539 const ParsedAttributesView &Attrs, AccessSpecifier AS,
15540 SourceLocation ModulePrivateLoc,
15541 MultiTemplateParamsArg TemplateParameterLists,
15542 bool &OwnedDecl, bool &IsDependent,
15543 SourceLocation ScopedEnumKWLoc,
15544 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15545 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15546 SkipBodyInfo *SkipBody) {
15547 // If this is not a definition, it must have a name.
15548 IdentifierInfo *OrigName = Name;
15549 assert((Name != nullptr || TUK == TUK_Definition) &&((void)0)
15550 "Nameless record must be a definition!")((void)0);
15551 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)((void)0);
15552
15553 OwnedDecl = false;
15554 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
15555 bool ScopedEnum = ScopedEnumKWLoc.isValid();
15556
15557 // FIXME: Check member specializations more carefully.
15558 bool isMemberSpecialization = false;
15559 bool Invalid = false;
15560
15561 // We only need to do this matching if we have template parameters
15562 // or a scope specifier, which also conveniently avoids this work
15563 // for non-C++ cases.
15564 if (TemplateParameterLists.size() > 0 ||
15565 (SS.isNotEmpty() && TUK != TUK_Reference)) {
15566 if (TemplateParameterList *TemplateParams =
15567 MatchTemplateParametersToScopeSpecifier(
15568 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15569 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15570 if (Kind == TTK_Enum) {
15571 Diag(KWLoc, diag::err_enum_template);
15572 return nullptr;
15573 }
15574
15575 if (TemplateParams->size() > 0) {
15576 // This is a declaration or definition of a class template (which may
15577 // be a member of another template).
15578
15579 if (Invalid)
15580 return nullptr;
15581
15582 OwnedDecl = false;
15583 DeclResult Result = CheckClassTemplate(
15584 S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15585 AS, ModulePrivateLoc,
15586 /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15587 TemplateParameterLists.data(), SkipBody);
15588 return Result.get();
15589 } else {
15590 // The "template<>" header is extraneous.
15591 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15592 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
15593 isMemberSpecialization = true;
15594 }
15595 }
15596
15597 if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15598 CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15599 return nullptr;
15600 }
15601
15602 // Figure out the underlying type if this a enum declaration. We need to do
15603 // this early, because it's needed to detect if this is an incompatible
15604 // redeclaration.
15605 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15606 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15607
15608 if (Kind == TTK_Enum) {
15609 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15610 // No underlying type explicitly specified, or we failed to parse the
15611 // type, default to int.
15612 EnumUnderlying = Context.IntTy.getTypePtr();
15613 } else if (UnderlyingType.get()) {
15614 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15615 // integral type; any cv-qualification is ignored.
15616 TypeSourceInfo *TI = nullptr;
15617 GetTypeFromParser(UnderlyingType.get(), &TI);
15618 EnumUnderlying = TI;
15619
15620 if (CheckEnumUnderlyingType(TI))
15621 // Recover by falling back to int.
15622 EnumUnderlying = Context.IntTy.getTypePtr();
15623
15624 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15625 UPPC_FixedUnderlyingType))
15626 EnumUnderlying = Context.IntTy.getTypePtr();
15627
15628 } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15629 // For MSVC ABI compatibility, unfixed enums must use an underlying type
15630 // of 'int'. However, if this is an unfixed forward declaration, don't set
15631 // the underlying type unless the user enables -fms-compatibility. This
15632 // makes unfixed forward declared enums incomplete and is more conforming.
15633 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15634 EnumUnderlying = Context.IntTy.getTypePtr();
15635 }
15636 }
15637
15638 DeclContext *SearchDC = CurContext;
15639 DeclContext *DC = CurContext;
15640 bool isStdBadAlloc = false;
15641 bool isStdAlignValT = false;
15642
15643 RedeclarationKind Redecl = forRedeclarationInCurContext();
15644 if (TUK == TUK_Friend || TUK == TUK_Reference)
15645 Redecl = NotForRedeclaration;
15646
15647 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15648 /// implemented asks for structural equivalence checking, the returned decl
15649 /// here is passed back to the parser, allowing the tag body to be parsed.
15650 auto createTagFromNewDecl = [&]() -> TagDecl * {
15651 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")((void)0);
15652 // If there is an identifier, use the location of the identifier as the
15653 // location of the decl, otherwise use the location of the struct/union
15654 // keyword.
15655 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15656 TagDecl *New = nullptr;
15657
15658 if (Kind == TTK_Enum) {
15659 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15660 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15661 // If this is an undefined enum, bail.
15662 if (TUK != TUK_Definition && !Invalid)
15663 return nullptr;
15664 if (EnumUnderlying) {
15665 EnumDecl *ED = cast<EnumDecl>(New);
15666 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15667 ED->setIntegerTypeSourceInfo(TI);
15668 else
15669 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15670 ED->setPromotionType(ED->getIntegerType());
15671 }
15672 } else { // struct/union
15673 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15674 nullptr);
15675 }
15676
15677 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15678 // Add alignment attributes if necessary; these attributes are checked
15679 // when the ASTContext lays out the structure.
15680 //
15681 // It is important for implementing the correct semantics that this
15682 // happen here (in ActOnTag). The #pragma pack stack is
15683 // maintained as a result of parser callbacks which can occur at
15684 // many points during the parsing of a struct declaration (because
15685 // the #pragma tokens are effectively skipped over during the
15686 // parsing of the struct).
15687 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15688 AddAlignmentAttributesForRecord(RD);
15689 AddMsStructLayoutForRecord(RD);
15690 }
15691 }
15692 New->setLexicalDeclContext(CurContext);
15693 return New;
15694 };
15695
15696 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15697 if (Name && SS.isNotEmpty()) {
15698 // We have a nested-name tag ('struct foo::bar').
15699
15700 // Check for invalid 'foo::'.
15701 if (SS.isInvalid()) {
15702 Name = nullptr;
15703 goto CreateNewDecl;
15704 }
15705
15706 // If this is a friend or a reference to a class in a dependent
15707 // context, don't try to make a decl for it.
15708 if (TUK == TUK_Friend || TUK == TUK_Reference) {
15709 DC = computeDeclContext(SS, false);
15710 if (!DC) {
15711 IsDependent = true;
15712 return nullptr;
15713 }
15714 } else {
15715 DC = computeDeclContext(SS, true);
15716 if (!DC) {
15717 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
15718 << SS.getRange();
15719 return nullptr;
15720 }
15721 }
15722
15723 if (RequireCompleteDeclContext(SS, DC))
15724 return nullptr;
15725
15726 SearchDC = DC;
15727 // Look-up name inside 'foo::'.
15728 LookupQualifiedName(Previous, DC);
15729
15730 if (Previous.isAmbiguous())
15731 return nullptr;
15732
15733 if (Previous.empty()) {
15734 // Name lookup did not find anything. However, if the
15735 // nested-name-specifier refers to the current instantiation,
15736 // and that current instantiation has any dependent base
15737 // classes, we might find something at instantiation time: treat
15738 // this as a dependent elaborated-type-specifier.
15739 // But this only makes any sense for reference-like lookups.
15740 if (Previous.wasNotFoundInCurrentInstantiation() &&
15741 (TUK == TUK_Reference || TUK == TUK_Friend)) {
15742 IsDependent = true;
15743 return nullptr;
15744 }
15745
15746 // A tag 'foo::bar' must already exist.
15747 Diag(NameLoc, diag::err_not_tag_in_scope)
15748 << Kind << Name << DC << SS.getRange();
15749 Name = nullptr;
15750 Invalid = true;
15751 goto CreateNewDecl;
15752 }
15753 } else if (Name) {
15754 // C++14 [class.mem]p14:
15755 // If T is the name of a class, then each of the following shall have a
15756 // name different from T:
15757 // -- every member of class T that is itself a type
15758 if (TUK != TUK_Reference && TUK != TUK_Friend &&
15759 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
15760 return nullptr;
15761
15762 // If this is a named struct, check to see if there was a previous forward
15763 // declaration or definition.
15764 // FIXME: We're looking into outer scopes here, even when we
15765 // shouldn't be. Doing so can result in ambiguities that we
15766 // shouldn't be diagnosing.
15767 LookupName(Previous, S);
15768
15769 // When declaring or defining a tag, ignore ambiguities introduced
15770 // by types using'ed into this scope.
15771 if (Previous.isAmbiguous() &&
15772 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
15773 LookupResult::Filter F = Previous.makeFilter();
15774 while (F.hasNext()) {
15775 NamedDecl *ND = F.next();
15776 if (!ND->getDeclContext()->getRedeclContext()->Equals(
15777 SearchDC->getRedeclContext()))
15778 F.erase();
15779 }
15780 F.done();
15781 }
15782
15783 // C++11 [namespace.memdef]p3:
15784 // If the name in a friend declaration is neither qualified nor
15785 // a template-id and the declaration is a function or an
15786 // elaborated-type-specifier, the lookup to determine whether
15787 // the entity has been previously declared shall not consider
15788 // any scopes outside the innermost enclosing namespace.
15789 //
15790 // MSVC doesn't implement the above rule for types, so a friend tag
15791 // declaration may be a redeclaration of a type declared in an enclosing
15792 // scope. They do implement this rule for friend functions.
15793 //
15794 // Does it matter that this should be by scope instead of by
15795 // semantic context?
15796 if (!Previous.empty() && TUK == TUK_Friend) {
15797 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
15798 LookupResult::Filter F = Previous.makeFilter();
15799 bool FriendSawTagOutsideEnclosingNamespace = false;
15800 while (F.hasNext()) {
15801 NamedDecl *ND = F.next();
15802 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
15803 if (DC->isFileContext() &&
15804 !EnclosingNS->Encloses(ND->getDeclContext())) {
15805 if (getLangOpts().MSVCCompat)
15806 FriendSawTagOutsideEnclosingNamespace = true;
15807 else
15808 F.erase();
15809 }
15810 }
15811 F.done();
15812
15813 // Diagnose this MSVC extension in the easy case where lookup would have
15814 // unambiguously found something outside the enclosing namespace.
15815 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
15816 NamedDecl *ND = Previous.getFoundDecl();
15817 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
15818 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
15819 }
15820 }
15821
15822 // Note: there used to be some attempt at recovery here.
15823 if (Previous.isAmbiguous())
15824 return nullptr;
15825
15826 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
15827 // FIXME: This makes sure that we ignore the contexts associated
15828 // with C structs, unions, and enums when looking for a matching
15829 // tag declaration or definition. See the similar lookup tweak
15830 // in Sema::LookupName; is there a better way to deal with this?
15831 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
15832 SearchDC = SearchDC->getParent();
15833 }
15834 }
15835
15836 if (Previous.isSingleResult() &&
15837 Previous.getFoundDecl()->isTemplateParameter()) {
15838 // Maybe we will complain about the shadowed template parameter.
15839 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
15840 // Just pretend that we didn't see the previous declaration.
15841 Previous.clear();
15842 }
15843
15844 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
15845 DC->Equals(getStdNamespace())) {
15846 if (Name->isStr("bad_alloc")) {
15847 // This is a declaration of or a reference to "std::bad_alloc".
15848 isStdBadAlloc = true;
15849
15850 // If std::bad_alloc has been implicitly declared (but made invisible to
15851 // name lookup), fill in this implicit declaration as the previous
15852 // declaration, so that the declarations get chained appropriately.
15853 if (Previous.empty() && StdBadAlloc)
15854 Previous.addDecl(getStdBadAlloc());
15855 } else if (Name->isStr("align_val_t")) {
15856 isStdAlignValT = true;
15857 if (Previous.empty() && StdAlignValT)
15858 Previous.addDecl(getStdAlignValT());
15859 }
15860 }
15861
15862 // If we didn't find a previous declaration, and this is a reference
15863 // (or friend reference), move to the correct scope. In C++, we
15864 // also need to do a redeclaration lookup there, just in case
15865 // there's a shadow friend decl.
15866 if (Name && Previous.empty() &&
15867 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
15868 if (Invalid) goto CreateNewDecl;
15869 assert(SS.isEmpty())((void)0);
15870
15871 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
15872 // C++ [basic.scope.pdecl]p5:
15873 // -- for an elaborated-type-specifier of the form
15874 //
15875 // class-key identifier
15876 //
15877 // if the elaborated-type-specifier is used in the
15878 // decl-specifier-seq or parameter-declaration-clause of a
15879 // function defined in namespace scope, the identifier is
15880 // declared as a class-name in the namespace that contains
15881 // the declaration; otherwise, except as a friend
15882 // declaration, the identifier is declared in the smallest
15883 // non-class, non-function-prototype scope that contains the
15884 // declaration.
15885 //
15886 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
15887 // C structs and unions.
15888 //
15889 // It is an error in C++ to declare (rather than define) an enum
15890 // type, including via an elaborated type specifier. We'll
15891 // diagnose that later; for now, declare the enum in the same
15892 // scope as we would have picked for any other tag type.
15893 //
15894 // GNU C also supports this behavior as part of its incomplete
15895 // enum types extension, while GNU C++ does not.
15896 //
15897 // Find the context where we'll be declaring the tag.
15898 // FIXME: We would like to maintain the current DeclContext as the
15899 // lexical context,
15900 SearchDC = getTagInjectionContext(SearchDC);
15901
15902 // Find the scope where we'll be declaring the tag.
15903 S = getTagInjectionScope(S, getLangOpts());
15904 } else {
15905 assert(TUK == TUK_Friend)((void)0);
15906 // C++ [namespace.memdef]p3:
15907 // If a friend declaration in a non-local class first declares a
15908 // class or function, the friend class or function is a member of
15909 // the innermost enclosing namespace.
15910 SearchDC = SearchDC->getEnclosingNamespaceContext();
15911 }
15912
15913 // In C++, we need to do a redeclaration lookup to properly
15914 // diagnose some problems.
15915 // FIXME: redeclaration lookup is also used (with and without C++) to find a
15916 // hidden declaration so that we don't get ambiguity errors when using a
15917 // type declared by an elaborated-type-specifier. In C that is not correct
15918 // and we should instead merge compatible types found by lookup.
15919 if (getLangOpts().CPlusPlus) {
15920 // FIXME: This can perform qualified lookups into function contexts,
15921 // which are meaningless.
15922 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15923 LookupQualifiedName(Previous, SearchDC);
15924 } else {
15925 Previous.setRedeclarationKind(forRedeclarationInCurContext());
15926 LookupName(Previous, S);
15927 }
15928 }
15929
15930 // If we have a known previous declaration to use, then use it.
15931 if (Previous.empty() && SkipBody && SkipBody->Previous)
15932 Previous.addDecl(SkipBody->Previous);
15933
15934 if (!Previous.empty()) {
15935 NamedDecl *PrevDecl = Previous.getFoundDecl();
15936 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
15937
15938 // It's okay to have a tag decl in the same scope as a typedef
15939 // which hides a tag decl in the same scope. Finding this
15940 // insanity with a redeclaration lookup can only actually happen
15941 // in C++.
15942 //
15943 // This is also okay for elaborated-type-specifiers, which is
15944 // technically forbidden by the current standard but which is
15945 // okay according to the likely resolution of an open issue;
15946 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
15947 if (getLangOpts().CPlusPlus) {
15948 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
15949 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
15950 TagDecl *Tag = TT->getDecl();
15951 if (Tag->getDeclName() == Name &&
15952 Tag->getDeclContext()->getRedeclContext()
15953 ->Equals(TD->getDeclContext()->getRedeclContext())) {
15954 PrevDecl = Tag;
15955 Previous.clear();
15956 Previous.addDecl(Tag);
15957 Previous.resolveKind();
15958 }
15959 }
15960 }
15961 }
15962
15963 // If this is a redeclaration of a using shadow declaration, it must
15964 // declare a tag in the same context. In MSVC mode, we allow a
15965 // redefinition if either context is within the other.
15966 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
15967 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
15968 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
15969 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
15970 !(OldTag && isAcceptableTagRedeclContext(
15971 *this, OldTag->getDeclContext(), SearchDC))) {
15972 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
15973 Diag(Shadow->getTargetDecl()->getLocation(),
15974 diag::note_using_decl_target);
15975 Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
15976 << 0;
15977 // Recover by ignoring the old declaration.
15978 Previous.clear();
15979 goto CreateNewDecl;
15980 }
15981 }
15982
15983 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
15984 // If this is a use of a previous tag, or if the tag is already declared
15985 // in the same scope (so that the definition/declaration completes or
15986 // rementions the tag), reuse the decl.
15987 if (TUK == TUK_Reference || TUK == TUK_Friend ||
15988 isDeclInScope(DirectPrevDecl, SearchDC, S,
15989 SS.isNotEmpty() || isMemberSpecialization)) {
15990 // Make sure that this wasn't declared as an enum and now used as a
15991 // struct or something similar.
15992 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
15993 TUK == TUK_Definition, KWLoc,
15994 Name)) {
15995 bool SafeToContinue
15996 = (PrevTagDecl->getTagKind() != TTK_Enum &&
15997 Kind != TTK_Enum);
15998 if (SafeToContinue)
15999 Diag(KWLoc, diag::err_use_with_wrong_tag)
16000 << Name
16001 << FixItHint::CreateReplacement(SourceRange(KWLoc),
16002 PrevTagDecl->getKindName());
16003 else
16004 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16005 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16006
16007 if (SafeToContinue)
16008 Kind = PrevTagDecl->getTagKind();
16009 else {
16010 // Recover by making this an anonymous redefinition.
16011 Name = nullptr;
16012 Previous.clear();
16013 Invalid = true;
16014 }
16015 }
16016
16017 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16018 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16019 if (TUK == TUK_Reference || TUK == TUK_Friend)
16020 return PrevTagDecl;
16021
16022 QualType EnumUnderlyingTy;
16023 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16024 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16025 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16026 EnumUnderlyingTy = QualType(T, 0);
16027
16028 // All conflicts with previous declarations are recovered by
16029 // returning the previous declaration, unless this is a definition,
16030 // in which case we want the caller to bail out.
16031 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16032 ScopedEnum, EnumUnderlyingTy,
16033 IsFixed, PrevEnum))
16034 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16035 }
16036
16037 // C++11 [class.mem]p1:
16038 // A member shall not be declared twice in the member-specification,
16039 // except that a nested class or member class template can be declared
16040 // and then later defined.
16041 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16042 S->isDeclScope(PrevDecl)) {
16043 Diag(NameLoc, diag::ext_member_redeclared);
16044 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16045 }
16046
16047 if (!Invalid) {
16048 // If this is a use, just return the declaration we found, unless
16049 // we have attributes.
16050 if (TUK == TUK_Reference || TUK == TUK_Friend) {
16051 if (!Attrs.empty()) {
16052 // FIXME: Diagnose these attributes. For now, we create a new
16053 // declaration to hold them.
16054 } else if (TUK == TUK_Reference &&
16055 (PrevTagDecl->getFriendObjectKind() ==
16056 Decl::FOK_Undeclared ||
16057 PrevDecl->getOwningModule() != getCurrentModule()) &&
16058 SS.isEmpty()) {
16059 // This declaration is a reference to an existing entity, but
16060 // has different visibility from that entity: it either makes
16061 // a friend visible or it makes a type visible in a new module.
16062 // In either case, create a new declaration. We only do this if
16063 // the declaration would have meant the same thing if no prior
16064 // declaration were found, that is, if it was found in the same
16065 // scope where we would have injected a declaration.
16066 if (!getTagInjectionContext(CurContext)->getRedeclContext()
16067 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16068 return PrevTagDecl;
16069 // This is in the injected scope, create a new declaration in
16070 // that scope.
16071 S = getTagInjectionScope(S, getLangOpts());
16072 } else {
16073 return PrevTagDecl;
16074 }
16075 }
16076
16077 // Diagnose attempts to redefine a tag.
16078 if (TUK == TUK_Definition) {
16079 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16080 // If we're defining a specialization and the previous definition
16081 // is from an implicit instantiation, don't emit an error
16082 // here; we'll catch this in the general case below.
16083 bool IsExplicitSpecializationAfterInstantiation = false;
16084 if (isMemberSpecialization) {
16085 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16086 IsExplicitSpecializationAfterInstantiation =
16087 RD->getTemplateSpecializationKind() !=
16088 TSK_ExplicitSpecialization;
16089 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16090 IsExplicitSpecializationAfterInstantiation =
16091 ED->getTemplateSpecializationKind() !=
16092 TSK_ExplicitSpecialization;
16093 }
16094
16095 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16096 // not keep more that one definition around (merge them). However,
16097 // ensure the decl passes the structural compatibility check in
16098 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16099 NamedDecl *Hidden = nullptr;
16100 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16101 // There is a definition of this tag, but it is not visible. We
16102 // explicitly make use of C++'s one definition rule here, and
16103 // assume that this definition is identical to the hidden one
16104 // we already have. Make the existing definition visible and
16105 // use it in place of this one.
16106 if (!getLangOpts().CPlusPlus) {
16107 // Postpone making the old definition visible until after we
16108 // complete parsing the new one and do the structural
16109 // comparison.
16110 SkipBody->CheckSameAsPrevious = true;
16111 SkipBody->New = createTagFromNewDecl();
16112 SkipBody->Previous = Def;
16113 return Def;
16114 } else {
16115 SkipBody->ShouldSkip = true;
16116 SkipBody->Previous = Def;
16117 makeMergedDefinitionVisible(Hidden);
16118 // Carry on and handle it like a normal definition. We'll
16119 // skip starting the definitiion later.
16120 }
16121 } else if (!IsExplicitSpecializationAfterInstantiation) {
16122 // A redeclaration in function prototype scope in C isn't
16123 // visible elsewhere, so merely issue a warning.
16124 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16125 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16126 else
16127 Diag(NameLoc, diag::err_redefinition) << Name;
16128 notePreviousDefinition(Def,
16129 NameLoc.isValid() ? NameLoc : KWLoc);
16130 // If this is a redefinition, recover by making this
16131 // struct be anonymous, which will make any later
16132 // references get the previous definition.
16133 Name = nullptr;
16134 Previous.clear();
16135 Invalid = true;
16136 }
16137 } else {
16138 // If the type is currently being defined, complain
16139 // about a nested redefinition.
16140 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16141 if (TD->isBeingDefined()) {
16142 Diag(NameLoc, diag::err_nested_redefinition) << Name;
16143 Diag(PrevTagDecl->getLocation(),
16144 diag::note_previous_definition);
16145 Name = nullptr;
16146 Previous.clear();
16147 Invalid = true;
16148 }
16149 }
16150
16151 // Okay, this is definition of a previously declared or referenced
16152 // tag. We're going to create a new Decl for it.
16153 }
16154
16155 // Okay, we're going to make a redeclaration. If this is some kind
16156 // of reference, make sure we build the redeclaration in the same DC
16157 // as the original, and ignore the current access specifier.
16158 if (TUK == TUK_Friend || TUK == TUK_Reference) {
16159 SearchDC = PrevTagDecl->getDeclContext();
16160 AS = AS_none;
16161 }
16162 }
16163 // If we get here we have (another) forward declaration or we
16164 // have a definition. Just create a new decl.
16165
16166 } else {
16167 // If we get here, this is a definition of a new tag type in a nested
16168 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16169 // new decl/type. We set PrevDecl to NULL so that the entities
16170 // have distinct types.
16171 Previous.clear();
16172 }
16173 // If we get here, we're going to create a new Decl. If PrevDecl
16174 // is non-NULL, it's a definition of the tag declared by
16175 // PrevDecl. If it's NULL, we have a new definition.
16176
16177 // Otherwise, PrevDecl is not a tag, but was found with tag
16178 // lookup. This is only actually possible in C++, where a few
16179 // things like templates still live in the tag namespace.
16180 } else {
16181 // Use a better diagnostic if an elaborated-type-specifier
16182 // found the wrong kind of type on the first
16183 // (non-redeclaration) lookup.
16184 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16185 !Previous.isForRedeclaration()) {
16186 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16187 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16188 << Kind;
16189 Diag(PrevDecl->getLocation(), diag::note_declared_at);
16190 Invalid = true;
16191
16192 // Otherwise, only diagnose if the declaration is in scope.
16193 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16194 SS.isNotEmpty() || isMemberSpecialization)) {
16195 // do nothing
16196
16197 // Diagnose implicit declarations introduced by elaborated types.
16198 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16199 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16200 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16201 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16202 Invalid = true;
16203
16204 // Otherwise it's a declaration. Call out a particularly common
16205 // case here.
16206 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16207 unsigned Kind = 0;
16208 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16209 Diag(NameLoc, diag::err_tag_definition_of_typedef)
16210 << Name << Kind << TND->getUnderlyingType();
16211 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16212 Invalid = true;
16213
16214 // Otherwise, diagnose.
16215 } else {
16216 // The tag name clashes with something else in the target scope,
16217 // issue an error and recover by making this tag be anonymous.
16218 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16219 notePreviousDefinition(PrevDecl, NameLoc);
16220 Name = nullptr;
16221 Invalid = true;
16222 }
16223
16224 // The existing declaration isn't relevant to us; we're in a
16225 // new scope, so clear out the previous declaration.
16226 Previous.clear();
16227 }
16228 }
16229
16230CreateNewDecl:
16231
16232 TagDecl *PrevDecl = nullptr;
16233 if (Previous.isSingleResult())
16234 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16235
16236 // If there is an identifier, use the location of the identifier as the
16237 // location of the decl, otherwise use the location of the struct/union
16238 // keyword.
16239 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16240
16241 // Otherwise, create a new declaration. If there is a previous
16242 // declaration of the same entity, the two will be linked via
16243 // PrevDecl.
16244 TagDecl *New;
16245
16246 if (Kind == TTK_Enum) {
16247 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16248 // enum X { A, B, C } D; D should chain to X.
16249 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16250 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16251 ScopedEnumUsesClassTag, IsFixed);
16252
16253 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16254 StdAlignValT = cast<EnumDecl>(New);
16255
16256 // If this is an undefined enum, warn.
16257 if (TUK != TUK_Definition && !Invalid) {
16258 TagDecl *Def;
16259 if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16260 // C++0x: 7.2p2: opaque-enum-declaration.
16261 // Conflicts are diagnosed above. Do nothing.
16262 }
16263 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16264 Diag(Loc, diag::ext_forward_ref_enum_def)
16265 << New;
16266 Diag(Def->getLocation(), diag::note_previous_definition);
16267 } else {
16268 unsigned DiagID = diag::ext_forward_ref_enum;
16269 if (getLangOpts().MSVCCompat)
16270 DiagID = diag::ext_ms_forward_ref_enum;
16271 else if (getLangOpts().CPlusPlus)
16272 DiagID = diag::err_forward_ref_enum;
16273 Diag(Loc, DiagID);
16274 }
16275 }
16276
16277 if (EnumUnderlying) {
16278 EnumDecl *ED = cast<EnumDecl>(New);
16279 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16280 ED->setIntegerTypeSourceInfo(TI);
16281 else
16282 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16283 ED->setPromotionType(ED->getIntegerType());
16284 assert(ED->isComplete() && "enum with type should be complete")((void)0);
16285 }
16286 } else {
16287 // struct/union/class
16288
16289 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16290 // struct X { int A; } D; D should chain to X.
16291 if (getLangOpts().CPlusPlus) {
16292 // FIXME: Look for a way to use RecordDecl for simple structs.
16293 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16294 cast_or_null<CXXRecordDecl>(PrevDecl));
16295
16296 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16297 StdBadAlloc = cast<CXXRecordDecl>(New);
16298 } else
16299 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16300 cast_or_null<RecordDecl>(PrevDecl));
16301 }
16302
16303 // C++11 [dcl.type]p3:
16304 // A type-specifier-seq shall not define a class or enumeration [...].
16305 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16306 TUK == TUK_Definition) {
16307 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16308 << Context.getTagDeclType(New);
16309 Invalid = true;
16310 }
16311
16312 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16313 DC->getDeclKind() == Decl::Enum) {
16314 Diag(New->getLocation(), diag::err_type_defined_in_enum)
16315 << Context.getTagDeclType(New);
16316 Invalid = true;
16317 }
16318
16319 // Maybe add qualifier info.
16320 if (SS.isNotEmpty()) {
16321 if (SS.isSet()) {
16322 // If this is either a declaration or a definition, check the
16323 // nested-name-specifier against the current context.
16324 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16325 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16326 isMemberSpecialization))
16327 Invalid = true;
16328
16329 New->setQualifierInfo(SS.getWithLocInContext(Context));
16330 if (TemplateParameterLists.size() > 0) {
16331 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16332 }
16333 }
16334 else
16335 Invalid = true;
16336 }
16337
16338 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16339 // Add alignment attributes if necessary; these attributes are checked when
16340 // the ASTContext lays out the structure.
16341 //
16342 // It is important for implementing the correct semantics that this
16343 // happen here (in ActOnTag). The #pragma pack stack is
16344 // maintained as a result of parser callbacks which can occur at
16345 // many points during the parsing of a struct declaration (because
16346 // the #pragma tokens are effectively skipped over during the
16347 // parsing of the struct).
16348 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16349 AddAlignmentAttributesForRecord(RD);
16350 AddMsStructLayoutForRecord(RD);
16351 }
16352 }
16353
16354 if (ModulePrivateLoc.isValid()) {
16355 if (isMemberSpecialization)
16356 Diag(New->getLocation(), diag::err_module_private_specialization)
16357 << 2
16358 << FixItHint::CreateRemoval(ModulePrivateLoc);
16359 // __module_private__ does not apply to local classes. However, we only
16360 // diagnose this as an error when the declaration specifiers are
16361 // freestanding. Here, we just ignore the __module_private__.
16362 else if (!SearchDC->isFunctionOrMethod())
16363 New->setModulePrivate();
16364 }
16365
16366 // If this is a specialization of a member class (of a class template),
16367 // check the specialization.
16368 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16369 Invalid = true;
16370
16371 // If we're declaring or defining a tag in function prototype scope in C,
16372 // note that this type can only be used within the function and add it to
16373 // the list of decls to inject into the function definition scope.
16374 if ((Name || Kind == TTK_Enum) &&
16375 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16376 if (getLangOpts().CPlusPlus) {
16377 // C++ [dcl.fct]p6:
16378 // Types shall not be defined in return or parameter types.
16379 if (TUK == TUK_Definition && !IsTypeSpecifier) {
16380 Diag(Loc, diag::err_type_defined_in_param_type)
16381 << Name;
16382 Invalid = true;
16383 }
16384 } else if (!PrevDecl) {
16385 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16386 }
16387 }
16388
16389 if (Invalid)
16390 New->setInvalidDecl();
16391
16392 // Set the lexical context. If the tag has a C++ scope specifier, the
16393 // lexical context will be different from the semantic context.
16394 New->setLexicalDeclContext(CurContext);
16395
16396 // Mark this as a friend decl if applicable.
16397 // In Microsoft mode, a friend declaration also acts as a forward
16398 // declaration so we always pass true to setObjectOfFriendDecl to make
16399 // the tag name visible.
16400 if (TUK == TUK_Friend)
16401 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16402
16403 // Set the access specifier.
16404 if (!Invalid && SearchDC->isRecord())
16405 SetMemberAccessSpecifier(New, PrevDecl, AS);
16406
16407 if (PrevDecl)
16408 CheckRedeclarationModuleOwnership(New, PrevDecl);
16409
16410 if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16411 New->startDefinition();
16412
16413 ProcessDeclAttributeList(S, New, Attrs);
16414 AddPragmaAttributes(S, New);
16415
16416 // If this has an identifier, add it to the scope stack.
16417 if (TUK == TUK_Friend) {
16418 // We might be replacing an existing declaration in the lookup tables;
16419 // if so, borrow its access specifier.
16420 if (PrevDecl)
16421 New->setAccess(PrevDecl->getAccess());
16422
16423 DeclContext *DC = New->getDeclContext()->getRedeclContext();
16424 DC->makeDeclVisibleInContext(New);
16425 if (Name) // can be null along some error paths
16426 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16427 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16428 } else if (Name) {
16429 S = getNonFieldDeclScope(S);
16430 PushOnScopeChains(New, S, true);
16431 } else {
16432 CurContext->addDecl(New);
16433 }
16434
16435 // If this is the C FILE type, notify the AST context.
16436 if (IdentifierInfo *II = New->getIdentifier())
16437 if (!New->isInvalidDecl() &&
16438 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
16439 II->isStr("FILE"))
16440 Context.setFILEDecl(New);
16441
16442 if (PrevDecl)
16443 mergeDeclAttributes(New, PrevDecl);
16444
16445 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16446 inferGslOwnerPointerAttribute(CXXRD);
16447
16448 // If there's a #pragma GCC visibility in scope, set the visibility of this
16449 // record.
16450 AddPushedVisibilityAttribute(New);
16451
16452 if (isMemberSpecialization && !New->isInvalidDecl())
16453 CompleteMemberSpecialization(New, Previous);
16454
16455 OwnedDecl = true;
16456 // In C++, don't return an invalid declaration. We can't recover well from
16457 // the cases where we make the type anonymous.
16458 if (Invalid && getLangOpts().CPlusPlus) {
16459 if (New->isBeingDefined())
16460 if (auto RD = dyn_cast<RecordDecl>(New))
16461 RD->completeDefinition();
16462 return nullptr;
16463 } else if (SkipBody && SkipBody->ShouldSkip) {
16464 return SkipBody->Previous;
16465 } else {
16466 return New;
16467 }
16468}
16469
16470void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
16471 AdjustDeclIfTemplate(TagD);
16472 TagDecl *Tag = cast<TagDecl>(TagD);
16473
16474 // Enter the tag context.
16475 PushDeclContext(S, Tag);
16476
16477 ActOnDocumentableDecl(TagD);
16478
16479 // If there's a #pragma GCC visibility in scope, set the visibility of this
16480 // record.
16481 AddPushedVisibilityAttribute(Tag);
16482}
16483
16484bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
16485 SkipBodyInfo &SkipBody) {
16486 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16487 return false;
16488
16489 // Make the previous decl visible.
16490 makeMergedDefinitionVisible(SkipBody.Previous);
16491 return true;
16492}
16493
16494Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
16495 assert(isa<ObjCContainerDecl>(IDecl) &&((void)0)
16496 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")((void)0);
16497 DeclContext *OCD = cast<DeclContext>(IDecl);
16498 assert(OCD->getLexicalParent() == CurContext &&((void)0)
16499 "The next DeclContext should be lexically contained in the current one.")((void)0);
16500 CurContext = OCD;
16501 return IDecl;
16502}
16503
16504void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
16505 SourceLocation FinalLoc,
16506 bool IsFinalSpelledSealed,
16507 bool IsAbstract,
16508 SourceLocation LBraceLoc) {
16509 AdjustDeclIfTemplate(TagD);
16510 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16511
16512 FieldCollector->StartClass();
16513
16514 if (!Record->getIdentifier())
16515 return;
16516
16517 if (IsAbstract)
16518 Record->markAbstract();
16519
16520 if (FinalLoc.isValid()) {
16521 Record->addAttr(FinalAttr::Create(
16522 Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16523 static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16524 }
16525 // C++ [class]p2:
16526 // [...] The class-name is also inserted into the scope of the
16527 // class itself; this is known as the injected-class-name. For
16528 // purposes of access checking, the injected-class-name is treated
16529 // as if it were a public member name.
16530 CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16531 Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16532 Record->getLocation(), Record->getIdentifier(),
16533 /*PrevDecl=*/nullptr,
16534 /*DelayTypeCreation=*/true);
16535 Context.getTypeDeclType(InjectedClassName, Record);
16536 InjectedClassName->setImplicit();
16537 InjectedClassName->setAccess(AS_public);
16538 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16539 InjectedClassName->setDescribedClassTemplate(Template);
16540 PushOnScopeChains(InjectedClassName, S);
16541 assert(InjectedClassName->isInjectedClassName() &&((void)0)
16542 "Broken injected-class-name")((void)0);
16543}
16544
16545void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
16546 SourceRange BraceRange) {
16547 AdjustDeclIfTemplate(TagD);
16548 TagDecl *Tag = cast<TagDecl>(TagD);
16549 Tag->setBraceRange(BraceRange);
16550
16551 // Make sure we "complete" the definition even it is invalid.
16552 if (Tag->isBeingDefined()) {
16553 assert(Tag->isInvalidDecl() && "We should already have completed it")((void)0);
16554 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16555 RD->completeDefinition();
16556 }
16557
16558 if (isa<CXXRecordDecl>(Tag)) {
16559 FieldCollector->FinishClass();
16560 }
16561
16562 // Exit this scope of this tag's definition.
16563 PopDeclContext();
16564
16565 if (getCurLexicalContext()->isObjCContainer() &&
16566 Tag->getDeclContext()->isFileContext())
16567 Tag->setTopLevelDeclInObjCContainer();
16568
16569 // Notify the consumer that we've defined a tag.
16570 if (!Tag->isInvalidDecl())
16571 Consumer.HandleTagDeclDefinition(Tag);
16572}
16573
16574void Sema::ActOnObjCContainerFinishDefinition() {
16575 // Exit this scope of this interface definition.
16576 PopDeclContext();
16577}
16578
16579void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
16580 assert(DC == CurContext && "Mismatch of container contexts")((void)0);
16581 OriginalLexicalContext = DC;
16582 ActOnObjCContainerFinishDefinition();
16583}
16584
16585void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
16586 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16587 OriginalLexicalContext = nullptr;
16588}
16589
16590void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
16591 AdjustDeclIfTemplate(TagD);
16592 TagDecl *Tag = cast<TagDecl>(TagD);
16593 Tag->setInvalidDecl();
16594
16595 // Make sure we "complete" the definition even it is invalid.
16596 if (Tag->isBeingDefined()) {
16597 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16598 RD->completeDefinition();
16599 }
16600
16601 // We're undoing ActOnTagStartDefinition here, not
16602 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16603 // the FieldCollector.
16604
16605 PopDeclContext();
16606}
16607
16608// Note that FieldName may be null for anonymous bitfields.
16609ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
16610 IdentifierInfo *FieldName,
16611 QualType FieldTy, bool IsMsStruct,
16612 Expr *BitWidth, bool *ZeroWidth) {
16613 assert(BitWidth)((void)0);
16614 if (BitWidth->containsErrors())
16615 return ExprError();
16616
16617 // Default to true; that shouldn't confuse checks for emptiness
16618 if (ZeroWidth)
16619 *ZeroWidth = true;
16620
16621 // C99 6.7.2.1p4 - verify the field type.
16622 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16623 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16624 // Handle incomplete and sizeless types with a specific error.
16625 if (RequireCompleteSizedType(FieldLoc, FieldTy,
16626 diag::err_field_incomplete_or_sizeless))
16627 return ExprError();
16628 if (FieldName)
16629 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16630 << FieldName << FieldTy << BitWidth->getSourceRange();
16631 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16632 << FieldTy << BitWidth->getSourceRange();
16633 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16634 UPPC_BitFieldWidth))
16635 return ExprError();
16636
16637 // If the bit-width is type- or value-dependent, don't try to check
16638 // it now.
16639 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16640 return BitWidth;
16641
16642 llvm::APSInt Value;
16643 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16644 if (ICE.isInvalid())
16645 return ICE;
16646 BitWidth = ICE.get();
16647
16648 if (Value != 0 && ZeroWidth)
16649 *ZeroWidth = false;
16650
16651 // Zero-width bitfield is ok for anonymous field.
16652 if (Value == 0 && FieldName)
16653 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16654
16655 if (Value.isSigned() && Value.isNegative()) {
16656 if (FieldName)
16657 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16658 << FieldName << toString(Value, 10);
16659 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16660 << toString(Value, 10);
16661 }
16662
16663 // The size of the bit-field must not exceed our maximum permitted object
16664 // size.
16665 if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16666 return Diag(FieldLoc, diag::err_bitfield_too_wide)
16667 << !FieldName << FieldName << toString(Value, 10);
16668 }
16669
16670 if (!FieldTy->isDependentType()) {
16671 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
16672 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
16673 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
16674
16675 // Over-wide bitfields are an error in C or when using the MSVC bitfield
16676 // ABI.
16677 bool CStdConstraintViolation =
16678 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
16679 bool MSBitfieldViolation =
16680 Value.ugt(TypeStorageSize) &&
16681 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
16682 if (CStdConstraintViolation || MSBitfieldViolation) {
16683 unsigned DiagWidth =
16684 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
16685 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
16686 << (bool)FieldName << FieldName << toString(Value, 10)
16687 << !CStdConstraintViolation << DiagWidth;
16688 }
16689
16690 // Warn on types where the user might conceivably expect to get all
16691 // specified bits as value bits: that's all integral types other than
16692 // 'bool'.
16693 if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
16694 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
16695 << FieldName << toString(Value, 10)
16696 << (unsigned)TypeWidth;
16697 }
16698 }
16699
16700 return BitWidth;
16701}
16702
16703/// ActOnField - Each field of a C struct/union is passed into this in order
16704/// to create a FieldDecl object for it.
16705Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
16706 Declarator &D, Expr *BitfieldWidth) {
16707 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
16708 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
16709 /*InitStyle=*/ICIS_NoInit, AS_public);
16710 return Res;
16711}
16712
16713/// HandleField - Analyze a field of a C struct or a C++ data member.
16714///
16715FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
16716 SourceLocation DeclStart,
16717 Declarator &D, Expr *BitWidth,
16718 InClassInitStyle InitStyle,
16719 AccessSpecifier AS) {
16720 if (D.isDecompositionDeclarator()) {
16721 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
16722 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
16723 << Decomp.getSourceRange();
16724 return nullptr;
16725 }
16726
16727 IdentifierInfo *II = D.getIdentifier();
16728 SourceLocation Loc = DeclStart;
16729 if (II) Loc = D.getIdentifierLoc();
16730
16731 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16732 QualType T = TInfo->getType();
16733 if (getLangOpts().CPlusPlus) {
16734 CheckExtraCXXDefaultArguments(D);
16735
16736 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16737 UPPC_DataMemberType)) {
16738 D.setInvalidType();
16739 T = Context.IntTy;
16740 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
16741 }
16742 }
16743
16744 DiagnoseFunctionSpecifiers(D.getDeclSpec());
16745
16746 if (D.getDeclSpec().isInlineSpecified())
16747 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
16748 << getLangOpts().CPlusPlus17;
16749 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
16750 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
16751 diag::err_invalid_thread)
16752 << DeclSpec::getSpecifierName(TSCS);
16753
16754 // Check to see if this name was declared as a member previously
16755 NamedDecl *PrevDecl = nullptr;
16756 LookupResult Previous(*this, II, Loc, LookupMemberName,
16757 ForVisibleRedeclaration);
16758 LookupName(Previous, S);
16759 switch (Previous.getResultKind()) {
16760 case LookupResult::Found:
16761 case LookupResult::FoundUnresolvedValue:
16762 PrevDecl = Previous.getAsSingle<NamedDecl>();
16763 break;
16764
16765 case LookupResult::FoundOverloaded:
16766 PrevDecl = Previous.getRepresentativeDecl();
16767 break;
16768
16769 case LookupResult::NotFound:
16770 case LookupResult::NotFoundInCurrentInstantiation:
16771 case LookupResult::Ambiguous:
16772 break;
16773 }
16774 Previous.suppressDiagnostics();
16775
16776 if (PrevDecl && PrevDecl->isTemplateParameter()) {
16777 // Maybe we will complain about the shadowed template parameter.
16778 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16779 // Just pretend that we didn't see the previous declaration.
16780 PrevDecl = nullptr;
16781 }
16782
16783 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
16784 PrevDecl = nullptr;
16785
16786 bool Mutable
16787 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
16788 SourceLocation TSSL = D.getBeginLoc();
16789 FieldDecl *NewFD
16790 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
16791 TSSL, AS, PrevDecl, &D);
16792
16793 if (NewFD->isInvalidDecl())
16794 Record->setInvalidDecl();
16795
16796 if (D.getDeclSpec().isModulePrivateSpecified())
16797 NewFD->setModulePrivate();
16798
16799 if (NewFD->isInvalidDecl() && PrevDecl) {
16800 // Don't introduce NewFD into scope; there's already something
16801 // with the same name in the same scope.
16802 } else if (II) {
16803 PushOnScopeChains(NewFD, S);
16804 } else
16805 Record->addDecl(NewFD);
16806
16807 return NewFD;
16808}
16809
16810/// Build a new FieldDecl and check its well-formedness.
16811///
16812/// This routine builds a new FieldDecl given the fields name, type,
16813/// record, etc. \p PrevDecl should refer to any previous declaration
16814/// with the same name and in the same scope as the field to be
16815/// created.
16816///
16817/// \returns a new FieldDecl.
16818///
16819/// \todo The Declarator argument is a hack. It will be removed once
16820FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
16821 TypeSourceInfo *TInfo,
16822 RecordDecl *Record, SourceLocation Loc,
16823 bool Mutable, Expr *BitWidth,
16824 InClassInitStyle InitStyle,
16825 SourceLocation TSSL,
16826 AccessSpecifier AS, NamedDecl *PrevDecl,
16827 Declarator *D) {
16828 IdentifierInfo *II = Name.getAsIdentifierInfo();
16829 bool InvalidDecl = false;
16830 if (D) InvalidDecl = D->isInvalidType();
16831
16832 // If we receive a broken type, recover by assuming 'int' and
16833 // marking this declaration as invalid.
16834 if (T.isNull() || T->containsErrors()) {
16835 InvalidDecl = true;
16836 T = Context.IntTy;
16837 }
16838
16839 QualType EltTy = Context.getBaseElementType(T);
16840 if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
16841 if (RequireCompleteSizedType(Loc, EltTy,
16842 diag::err_field_incomplete_or_sizeless)) {
16843 // Fields of incomplete type force their record to be invalid.
16844 Record->setInvalidDecl();
16845 InvalidDecl = true;
16846 } else {
16847 NamedDecl *Def;
16848 EltTy->isIncompleteType(&Def);
16849 if (Def && Def->isInvalidDecl()) {
16850 Record->setInvalidDecl();
16851 InvalidDecl = true;
16852 }
16853 }
16854 }
16855
16856 // TR 18037 does not allow fields to be declared with address space
16857 if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
16858 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
16859 Diag(Loc, diag::err_field_with_address_space);
16860 Record->setInvalidDecl();
16861 InvalidDecl = true;
16862 }
16863
16864 if (LangOpts.OpenCL) {
16865 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
16866 // used as structure or union field: image, sampler, event or block types.
16867 if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
16868 T->isBlockPointerType()) {
16869 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
16870 Record->setInvalidDecl();
16871 InvalidDecl = true;
16872 }
16873 // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
16874 // is enabled.
16875 if (BitWidth && !getOpenCLOptions().isAvailableOption(
16876 "__cl_clang_bitfields", LangOpts)) {
16877 Diag(Loc, diag::err_opencl_bitfields);
16878 InvalidDecl = true;
16879 }
16880 }
16881
16882 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
16883 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
16884 T.hasQualifiers()) {
16885 InvalidDecl = true;
16886 Diag(Loc, diag::err_anon_bitfield_qualifiers);
16887 }
16888
16889 // C99 6.7.2.1p8: A member of a structure or union may have any type other
16890 // than a variably modified type.
16891 if (!InvalidDecl && T->isVariablyModifiedType()) {
16892 if (!tryToFixVariablyModifiedVarType(
16893 TInfo, T, Loc, diag::err_typecheck_field_variable_size))
16894 InvalidDecl = true;
16895 }
16896
16897 // Fields can not have abstract class types
16898 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
16899 diag::err_abstract_type_in_decl,
16900 AbstractFieldType))
16901 InvalidDecl = true;
16902
16903 bool ZeroWidth = false;
16904 if (InvalidDecl)
16905 BitWidth = nullptr;
16906 // If this is declared as a bit-field, check the bit-field.
16907 if (BitWidth) {
16908 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
16909 &ZeroWidth).get();
16910 if (!BitWidth) {
16911 InvalidDecl = true;
16912 BitWidth = nullptr;
16913 ZeroWidth = false;
16914 }
16915 }
16916
16917 // Check that 'mutable' is consistent with the type of the declaration.
16918 if (!InvalidDecl && Mutable) {
16919 unsigned DiagID = 0;
16920 if (T->isReferenceType())
16921 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
16922 : diag::err_mutable_reference;
16923 else if (T.isConstQualified())
16924 DiagID = diag::err_mutable_const;
16925
16926 if (DiagID) {
16927 SourceLocation ErrLoc = Loc;
16928 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
16929 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
16930 Diag(ErrLoc, DiagID);
16931 if (DiagID != diag::ext_mutable_reference) {
16932 Mutable = false;
16933 InvalidDecl = true;
16934 }
16935 }
16936 }
16937
16938 // C++11 [class.union]p8 (DR1460):
16939 // At most one variant member of a union may have a
16940 // brace-or-equal-initializer.
16941 if (InitStyle != ICIS_NoInit)
16942 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
16943
16944 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
16945 BitWidth, Mutable, InitStyle);
16946 if (InvalidDecl)
16947 NewFD->setInvalidDecl();
16948
16949 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
16950 Diag(Loc, diag::err_duplicate_member) << II;
16951 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
16952 NewFD->setInvalidDecl();
16953 }
16954
16955 if (!InvalidDecl && getLangOpts().CPlusPlus) {
16956 if (Record->isUnion()) {
16957 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
16958 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
16959 if (RDecl->getDefinition()) {
16960 // C++ [class.union]p1: An object of a class with a non-trivial
16961 // constructor, a non-trivial copy constructor, a non-trivial
16962 // destructor, or a non-trivial copy assignment operator
16963 // cannot be a member of a union, nor can an array of such
16964 // objects.
16965 if (CheckNontrivialField(NewFD))
16966 NewFD->setInvalidDecl();
16967 }
16968 }
16969
16970 // C++ [class.union]p1: If a union contains a member of reference type,
16971 // the program is ill-formed, except when compiling with MSVC extensions
16972 // enabled.
16973 if (EltTy->isReferenceType()) {
16974 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
16975 diag::ext_union_member_of_reference_type :
16976 diag::err_union_member_of_reference_type)
16977 << NewFD->getDeclName() << EltTy;
16978 if (!getLangOpts().MicrosoftExt)
16979 NewFD->setInvalidDecl();
16980 }
16981 }
16982 }
16983
16984 // FIXME: We need to pass in the attributes given an AST
16985 // representation, not a parser representation.
16986 if (D) {
16987 // FIXME: The current scope is almost... but not entirely... correct here.
16988 ProcessDeclAttributes(getCurScope(), NewFD, *D);
16989
16990 if (NewFD->hasAttrs())
16991 CheckAlignasUnderalignment(NewFD);
16992 }
16993
16994 // In auto-retain/release, infer strong retension for fields of
16995 // retainable type.
16996 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
16997 NewFD->setInvalidDecl();
16998
16999 if (T.isObjCGCWeak())
17000 Diag(Loc, diag::warn_attribute_weak_on_field);
17001
17002 // PPC MMA non-pointer types are not allowed as field types.
17003 if (Context.getTargetInfo().getTriple().isPPC64() &&
17004 CheckPPCMMAType(T, NewFD->getLocation()))
17005 NewFD->setInvalidDecl();
17006
17007 NewFD->setAccess(AS);
17008 return NewFD;
17009}
17010
17011bool Sema::CheckNontrivialField(FieldDecl *FD) {
17012 assert(FD)((void)0);
17013 assert(getLangOpts().CPlusPlus && "valid check only for C++")((void)0);
17014
17015 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17016 return false;
17017
17018 QualType EltTy = Context.getBaseElementType(FD->getType());
17019 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17020 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17021 if (RDecl->getDefinition()) {
17022 // We check for copy constructors before constructors
17023 // because otherwise we'll never get complaints about
17024 // copy constructors.
17025
17026 CXXSpecialMember member = CXXInvalid;
17027 // We're required to check for any non-trivial constructors. Since the
17028 // implicit default constructor is suppressed if there are any
17029 // user-declared constructors, we just need to check that there is a
17030 // trivial default constructor and a trivial copy constructor. (We don't
17031 // worry about move constructors here, since this is a C++98 check.)
17032 if (RDecl->hasNonTrivialCopyConstructor())
17033 member = CXXCopyConstructor;
17034 else if (!RDecl->hasTrivialDefaultConstructor())
17035 member = CXXDefaultConstructor;
17036 else if (RDecl->hasNonTrivialCopyAssignment())
17037 member = CXXCopyAssignment;
17038 else if (RDecl->hasNonTrivialDestructor())
17039 member = CXXDestructor;
17040
17041 if (member != CXXInvalid) {
17042 if (!getLangOpts().CPlusPlus11 &&
17043 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17044 // Objective-C++ ARC: it is an error to have a non-trivial field of
17045 // a union. However, system headers in Objective-C programs
17046 // occasionally have Objective-C lifetime objects within unions,
17047 // and rather than cause the program to fail, we make those
17048 // members unavailable.
17049 SourceLocation Loc = FD->getLocation();
17050 if (getSourceManager().isInSystemHeader(Loc)) {
17051 if (!FD->hasAttr<UnavailableAttr>())
17052 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17053 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17054 return false;
17055 }
17056 }
17057
17058 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17059 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17060 diag::err_illegal_union_or_anon_struct_member)
17061 << FD->getParent()->isUnion() << FD->getDeclName() << member;
17062 DiagnoseNontrivial(RDecl, member);
17063 return !getLangOpts().CPlusPlus11;
17064 }
17065 }
17066 }
17067
17068 return false;
17069}
17070
17071/// TranslateIvarVisibility - Translate visibility from a token ID to an
17072/// AST enum value.
17073static ObjCIvarDecl::AccessControl
17074TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
17075 switch (ivarVisibility) {
17076 default: llvm_unreachable("Unknown visitibility kind")__builtin_unreachable();
17077 case tok::objc_private: return ObjCIvarDecl::Private;
17078 case tok::objc_public: return ObjCIvarDecl::Public;
17079 case tok::objc_protected: return ObjCIvarDecl::Protected;
17080 case tok::objc_package: return ObjCIvarDecl::Package;
17081 }
17082}
17083
17084/// ActOnIvar - Each ivar field of an objective-c class is passed into this
17085/// in order to create an IvarDecl object for it.
17086Decl *Sema::ActOnIvar(Scope *S,
17087 SourceLocation DeclStart,
17088 Declarator &D, Expr *BitfieldWidth,
17089 tok::ObjCKeywordKind Visibility) {
17090
17091 IdentifierInfo *II = D.getIdentifier();
17092 Expr *BitWidth = (Expr*)BitfieldWidth;
17093 SourceLocation Loc = DeclStart;
17094 if (II) Loc = D.getIdentifierLoc();
17095
17096 // FIXME: Unnamed fields can be handled in various different ways, for
17097 // example, unnamed unions inject all members into the struct namespace!
17098
17099 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17100 QualType T = TInfo->getType();
17101
17102 if (BitWidth) {
17103 // 6.7.2.1p3, 6.7.2.1p4
17104 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17105 if (!BitWidth)
17106 D.setInvalidType();
17107 } else {
17108 // Not a bitfield.
17109
17110 // validate II.
17111
17112 }
17113 if (T->isReferenceType()) {
17114 Diag(Loc, diag::err_ivar_reference_type);
17115 D.setInvalidType();
17116 }
17117 // C99 6.7.2.1p8: A member of a structure or union may have any type other
17118 // than a variably modified type.
17119 else if (T->isVariablyModifiedType()) {
17120 if (!tryToFixVariablyModifiedVarType(
17121 TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17122 D.setInvalidType();
17123 }
17124
17125 // Get the visibility (access control) for this ivar.
17126 ObjCIvarDecl::AccessControl ac =
17127 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17128 : ObjCIvarDecl::None;
17129 // Must set ivar's DeclContext to its enclosing interface.
17130 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17131 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17132 return nullptr;
17133 ObjCContainerDecl *EnclosingContext;
17134 if (ObjCImplementationDecl *IMPDecl =
17135 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17136 if (LangOpts.ObjCRuntime.isFragile()) {
17137 // Case of ivar declared in an implementation. Context is that of its class.
17138 EnclosingContext = IMPDecl->getClassInterface();
17139 assert(EnclosingContext && "Implementation has no class interface!")((void)0);
17140 }
17141 else
17142 EnclosingContext = EnclosingDecl;
17143 } else {
17144 if (ObjCCategoryDecl *CDecl =
17145 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17146 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17147 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17148 return nullptr;
17149 }
17150 }
17151 EnclosingContext = EnclosingDecl;
17152 }
17153
17154 // Construct the decl.
17155 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17156 DeclStart, Loc, II, T,
17157 TInfo, ac, (Expr *)BitfieldWidth);
17158
17159 if (II) {
17160 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17161 ForVisibleRedeclaration);
17162 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17163 && !isa<TagDecl>(PrevDecl)) {
17164 Diag(Loc, diag::err_duplicate_member) << II;
17165 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17166 NewID->setInvalidDecl();
17167 }
17168 }
17169
17170 // Process attributes attached to the ivar.
17171 ProcessDeclAttributes(S, NewID, D);
17172
17173 if (D.isInvalidType())
17174 NewID->setInvalidDecl();
17175
17176 // In ARC, infer 'retaining' for ivars of retainable type.
17177 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17178 NewID->setInvalidDecl();
17179
17180 if (D.getDeclSpec().isModulePrivateSpecified())
17181 NewID->setModulePrivate();
17182
17183 if (II) {
17184 // FIXME: When interfaces are DeclContexts, we'll need to add
17185 // these to the interface.
17186 S->AddDecl(NewID);
17187 IdResolver.AddDecl(NewID);
17188 }
17189
17190 if (LangOpts.ObjCRuntime.isNonFragile() &&
17191 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17192 Diag(Loc, diag::warn_ivars_in_interface);
17193
17194 return NewID;
17195}
17196
17197/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17198/// class and class extensions. For every class \@interface and class
17199/// extension \@interface, if the last ivar is a bitfield of any type,
17200/// then add an implicit `char :0` ivar to the end of that interface.
17201void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
17202 SmallVectorImpl<Decl *> &AllIvarDecls) {
17203 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17204 return;
17205
17206 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17207 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17208
17209 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17210 return;
17211 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17212 if (!ID) {
17213 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17214 if (!CD->IsClassExtension())
17215 return;
17216 }
17217 // No need to add this to end of @implementation.
17218 else
17219 return;
17220 }
17221 // All conditions are met. Add a new bitfield to the tail end of ivars.
17222 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17223 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17224
17225 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17226 DeclLoc, DeclLoc, nullptr,
17227 Context.CharTy,
17228 Context.getTrivialTypeSourceInfo(Context.CharTy,
17229 DeclLoc),
17230 ObjCIvarDecl::Private, BW,
17231 true);
17232 AllIvarDecls.push_back(Ivar);
17233}
17234
17235void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17236 ArrayRef<Decl *> Fields, SourceLocation LBrac,
17237 SourceLocation RBrac,
17238 const ParsedAttributesView &Attrs) {
17239 assert(EnclosingDecl && "missing record or interface decl")((void)0);
17240
17241 // If this is an Objective-C @implementation or category and we have
17242 // new fields here we should reset the layout of the interface since
17243 // it will now change.
17244 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17245 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17246 switch (DC->getKind()) {
17247 default: break;
17248 case Decl::ObjCCategory:
17249 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17250 break;
17251 case Decl::ObjCImplementation:
17252 Context.
17253 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17254 break;
17255 }
17256 }
17257
17258 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17259 CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17260
17261 // Start counting up the number of named members; make sure to include
17262 // members of anonymous structs and unions in the total.
17263 unsigned NumNamedMembers = 0;
17264 if (Record) {
17265 for (const auto *I : Record->decls()) {
17266 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17267 if (IFD->getDeclName())
17268 ++NumNamedMembers;
17269 }
17270 }
17271
17272 // Verify that all the fields are okay.
17273 SmallVector<FieldDecl*, 32> RecFields;
17274
17275 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17276 i != end; ++i) {
17277 FieldDecl *FD = cast<FieldDecl>(*i);
17278
17279 // Get the type for the field.
17280 const Type *FDTy = FD->getType().getTypePtr();
17281
17282 if (!FD->isAnonymousStructOrUnion()) {
17283 // Remember all fields written by the user.
17284 RecFields.push_back(FD);
17285 }
17286
17287 // If the field is already invalid for some reason, don't emit more
17288 // diagnostics about it.
17289 if (FD->isInvalidDecl()) {
17290 EnclosingDecl->setInvalidDecl();
17291 continue;
17292 }
17293
17294 // C99 6.7.2.1p2:
17295 // A structure or union shall not contain a member with
17296 // incomplete or function type (hence, a structure shall not
17297 // contain an instance of itself, but may contain a pointer to
17298 // an instance of itself), except that the last member of a
17299 // structure with more than one named member may have incomplete
17300 // array type; such a structure (and any union containing,
17301 // possibly recursively, a member that is such a structure)
17302 // shall not be a member of a structure or an element of an
17303 // array.
17304 bool IsLastField = (i + 1 == Fields.end());
17305 if (FDTy->isFunctionType()) {
17306 // Field declared as a function.
17307 Diag(FD->getLocation(), diag::err_field_declared_as_function)
17308 << FD->getDeclName();
17309 FD->setInvalidDecl();
17310 EnclosingDecl->setInvalidDecl();
17311 continue;
17312 } else if (FDTy->isIncompleteArrayType() &&
17313 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17314 if (Record) {
17315 // Flexible array member.
17316 // Microsoft and g++ is more permissive regarding flexible array.
17317 // It will accept flexible array in union and also
17318 // as the sole element of a struct/class.
17319 unsigned DiagID = 0;
17320 if (!Record->isUnion() && !IsLastField) {
17321 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17322 << FD->getDeclName() << FD->getType() << Record->getTagKind();
17323 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17324 FD->setInvalidDecl();
17325 EnclosingDecl->setInvalidDecl();
17326 continue;
17327 } else if (Record->isUnion())
17328 DiagID = getLangOpts().MicrosoftExt
17329 ? diag::ext_flexible_array_union_ms
17330 : getLangOpts().CPlusPlus
17331 ? diag::ext_flexible_array_union_gnu
17332 : diag::err_flexible_array_union;
17333 else if (NumNamedMembers < 1)
17334 DiagID = getLangOpts().MicrosoftExt
17335 ? diag::ext_flexible_array_empty_aggregate_ms
17336 : getLangOpts().CPlusPlus
17337 ? diag::ext_flexible_array_empty_aggregate_gnu
17338 : diag::err_flexible_array_empty_aggregate;
17339
17340 if (DiagID)
17341 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17342 << Record->getTagKind();
17343 // While the layout of types that contain virtual bases is not specified
17344 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17345 // virtual bases after the derived members. This would make a flexible
17346 // array member declared at the end of an object not adjacent to the end
17347 // of the type.
17348 if (CXXRecord && CXXRecord->getNumVBases() != 0)
17349 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17350 << FD->getDeclName() << Record->getTagKind();
17351 if (!getLangOpts().C99)
17352 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17353 << FD->getDeclName() << Record->getTagKind();
17354
17355 // If the element type has a non-trivial destructor, we would not
17356 // implicitly destroy the elements, so disallow it for now.
17357 //
17358 // FIXME: GCC allows this. We should probably either implicitly delete
17359 // the destructor of the containing class, or just allow this.
17360 QualType BaseElem = Context.getBaseElementType(FD->getType());
17361 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17362 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17363 << FD->getDeclName() << FD->getType();
17364 FD->setInvalidDecl();
17365 EnclosingDecl->setInvalidDecl();
17366 continue;
17367 }
17368 // Okay, we have a legal flexible array member at the end of the struct.
17369 Record->setHasFlexibleArrayMember(true);
17370 } else {
17371 // In ObjCContainerDecl ivars with incomplete array type are accepted,
17372 // unless they are followed by another ivar. That check is done
17373 // elsewhere, after synthesized ivars are known.
17374 }
17375 } else if (!FDTy->isDependentType() &&
17376 RequireCompleteSizedType(
17377 FD->getLocation(), FD->getType(),
17378 diag::err_field_incomplete_or_sizeless)) {
17379 // Incomplete type
17380 FD->setInvalidDecl();
17381 EnclosingDecl->setInvalidDecl();
17382 continue;
17383 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17384 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17385 // A type which contains a flexible array member is considered to be a
17386 // flexible array member.
17387 Record->setHasFlexibleArrayMember(true);
17388 if (!Record->isUnion()) {
17389 // If this is a struct/class and this is not the last element, reject
17390 // it. Note that GCC supports variable sized arrays in the middle of
17391 // structures.
17392 if (!IsLastField)
17393 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17394 << FD->getDeclName() << FD->getType();
17395 else {
17396 // We support flexible arrays at the end of structs in
17397 // other structs as an extension.
17398 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17399 << FD->getDeclName();
17400 }
17401 }
17402 }
17403 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17404 RequireNonAbstractType(FD->getLocation(), FD->getType(),
17405 diag::err_abstract_type_in_decl,
17406 AbstractIvarType)) {
17407 // Ivars can not have abstract class types
17408 FD->setInvalidDecl();
17409 }
17410 if (Record && FDTTy->getDecl()->hasObjectMember())
17411 Record->setHasObjectMember(true);
17412 if (Record && FDTTy->getDecl()->hasVolatileMember())
17413 Record->setHasVolatileMember(true);
17414 } else if (FDTy->isObjCObjectType()) {
17415 /// A field cannot be an Objective-c object
17416 Diag(FD->getLocation(), diag::err_statically_allocated_object)
17417 << FixItHint::CreateInsertion(FD->getLocation(), "*");
17418 QualType T = Context.getObjCObjectPointerType(FD->getType());
17419 FD->setType(T);
17420 } else if (Record && Record->isUnion() &&
17421 FD->getType().hasNonTrivialObjCLifetime() &&
17422 getSourceManager().isInSystemHeader(FD->getLocation()) &&
17423 !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17424 (FD->getType().getObjCLifetime() != Qualifiers::OCL_Strong ||
17425 !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17426 // For backward compatibility, fields of C unions declared in system
17427 // headers that have non-trivial ObjC ownership qualifications are marked
17428 // as unavailable unless the qualifier is explicit and __strong. This can
17429 // break ABI compatibility between programs compiled with ARC and MRR, but
17430 // is a better option than rejecting programs using those unions under
17431 // ARC.
17432 FD->addAttr(UnavailableAttr::CreateImplicit(
17433 Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17434 FD->getLocation()));
17435 } else if (getLangOpts().ObjC &&
17436 getLangOpts().getGC() != LangOptions::NonGC && Record &&
17437 !Record->hasObjectMember()) {
17438 if (FD->getType()->isObjCObjectPointerType() ||
17439 FD->getType().isObjCGCStrong())
17440 Record->setHasObjectMember(true);
17441 else if (Context.getAsArrayType(FD->getType())) {
17442 QualType BaseType = Context.getBaseElementType(FD->getType());
17443 if (BaseType->isRecordType() &&
17444 BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17445 Record->setHasObjectMember(true);
17446 else if (BaseType->isObjCObjectPointerType() ||
17447 BaseType.isObjCGCStrong())
17448 Record->setHasObjectMember(true);
17449 }
17450 }
17451
17452 if (Record && !getLangOpts().CPlusPlus &&
17453 !shouldIgnoreForRecordTriviality(FD)) {
17454 QualType FT = FD->getType();
17455 if (FT.isNonTrivialToPrimitiveDefaultInitialize()) {
17456 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
17457 if (FT.hasNonTrivialToPrimitiveDefaultInitializeCUnion() ||
17458 Record->isUnion())
17459 Record->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(true);
17460 }
17461 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
17462 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial) {
17463 Record->setNonTrivialToPrimitiveCopy(true);
17464 if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17465 Record->setHasNonTrivialToPrimitiveCopyCUnion(true);
17466 }
17467 if (FT.isDestructedType()) {
17468 Record->setNonTrivialToPrimitiveDestroy(true);
17469 Record->setParamDestroyedInCallee(true);
17470 if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17471 Record->setHasNonTrivialToPrimitiveDestructCUnion(true);
17472 }
17473
17474 if (const auto *RT = FT->getAs<RecordType>()) {
17475 if (RT->getDecl()->getArgPassingRestrictions() ==
17476 RecordDecl::APK_CanNeverPassInRegs)
17477 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17478 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17479 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
17480 }
17481
17482 if (Record && FD->getType().isVolatileQualified())
17483 Record->setHasVolatileMember(true);
17484 // Keep track of the number of named members.
17485 if (FD->getIdentifier())
17486 ++NumNamedMembers;
17487 }
17488
17489 // Okay, we successfully defined 'Record'.
17490 if (Record) {
17491 bool Completed = false;
17492 if (CXXRecord) {
17493 if (!CXXRecord->isInvalidDecl()) {
17494 // Set access bits correctly on the directly-declared conversions.
17495 for (CXXRecordDecl::conversion_iterator
17496 I = CXXRecord->conversion_begin(),
17497 E = CXXRecord->conversion_end(); I != E; ++I)
17498 I.setAccess((*I)->getAccess());
17499 }
17500
17501 // Add any implicitly-declared members to this class.
17502 AddImplicitlyDeclaredMembersToClass(CXXRecord);
17503
17504 if (!CXXRecord->isDependentType()) {
17505 if (!CXXRecord->isInvalidDecl()) {
17506 // If we have virtual base classes, we may end up finding multiple
17507 // final overriders for a given virtual function. Check for this
17508 // problem now.
17509 if (CXXRecord->getNumVBases()) {
17510 CXXFinalOverriderMap FinalOverriders;
17511 CXXRecord->getFinalOverriders(FinalOverriders);
17512
17513 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17514 MEnd = FinalOverriders.end();
17515 M != MEnd; ++M) {
17516 for (OverridingMethods::iterator SO = M->second.begin(),
17517 SOEnd = M->second.end();
17518 SO != SOEnd; ++SO) {
17519 assert(SO->second.size() > 0 &&((void)0)
17520 "Virtual function without overriding functions?")((void)0);
17521 if (SO->second.size() == 1)
17522 continue;
17523
17524 // C++ [class.virtual]p2:
17525 // In a derived class, if a virtual member function of a base
17526 // class subobject has more than one final overrider the
17527 // program is ill-formed.
17528 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17529 << (const NamedDecl *)M->first << Record;
17530 Diag(M->first->getLocation(),
17531 diag::note_overridden_virtual_function);
17532 for (OverridingMethods::overriding_iterator
17533 OM = SO->second.begin(),
17534 OMEnd = SO->second.end();
17535 OM != OMEnd; ++OM)
17536 Diag(OM->Method->getLocation(), diag::note_final_overrider)
17537 << (const NamedDecl *)M->first << OM->Method->getParent();
17538
17539 Record->setInvalidDecl();
17540 }
17541 }
17542 CXXRecord->completeDefinition(&FinalOverriders);
17543 Completed = true;
17544 }
17545 }
17546 }
17547 }
17548
17549 if (!Completed)
17550 Record->completeDefinition();
17551
17552 // Handle attributes before checking the layout.
17553 ProcessDeclAttributeList(S, Record, Attrs);
17554
17555 // We may have deferred checking for a deleted destructor. Check now.
17556 if (CXXRecord) {
17557 auto *Dtor = CXXRecord->getDestructor();
17558 if (Dtor && Dtor->isImplicit() &&
17559 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17560 CXXRecord->setImplicitDestructorIsDeleted();
17561 SetDeclDeleted(Dtor, CXXRecord->getLocation());
17562 }
17563 }
17564
17565 if (Record->hasAttrs()) {
17566 CheckAlignasUnderalignment(Record);
17567
17568 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17569 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17570 IA->getRange(), IA->getBestCase(),
17571 IA->getInheritanceModel());
17572 }
17573
17574 // Check if the structure/union declaration is a type that can have zero
17575 // size in C. For C this is a language extension, for C++ it may cause
17576 // compatibility problems.
17577 bool CheckForZeroSize;
17578 if (!getLangOpts().CPlusPlus) {
17579 CheckForZeroSize = true;
17580 } else {
17581 // For C++ filter out types that cannot be referenced in C code.
17582 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17583 CheckForZeroSize =
17584 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17585 !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17586 CXXRecord->isCLike();
17587 }
17588 if (CheckForZeroSize) {
17589 bool ZeroSize = true;
17590 bool IsEmpty = true;
17591 unsigned NonBitFields = 0;
17592 for (RecordDecl::field_iterator I = Record->field_begin(),
17593 E = Record->field_end();
17594 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17595 IsEmpty = false;
17596 if (I->isUnnamedBitfield()) {
17597 if (!I->isZeroLengthBitField(Context))
17598 ZeroSize = false;
17599 } else {
17600 ++NonBitFields;
17601 QualType FieldType = I->getType();
17602 if (FieldType->isIncompleteType() ||
17603 !Context.getTypeSizeInChars(FieldType).isZero())
17604 ZeroSize = false;
17605 }
17606 }
17607
17608 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17609 // allowed in C++, but warn if its declaration is inside
17610 // extern "C" block.
17611 if (ZeroSize) {
17612 Diag(RecLoc, getLangOpts().CPlusPlus ?
17613 diag::warn_zero_size_struct_union_in_extern_c :
17614 diag::warn_zero_size_struct_union_compat)
17615 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17616 }
17617
17618 // Structs without named members are extension in C (C99 6.7.2.1p7),
17619 // but are accepted by GCC.
17620 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17621 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17622 diag::ext_no_named_members_in_struct_union)
17623 << Record->isUnion();
17624 }
17625 }
17626 } else {
17627 ObjCIvarDecl **ClsFields =
17628 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17629 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17630 ID->setEndOfDefinitionLoc(RBrac);
17631 // Add ivar's to class's DeclContext.
17632 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17633 ClsFields[i]->setLexicalDeclContext(ID);
17634 ID->addDecl(ClsFields[i]);
17635 }
17636 // Must enforce the rule that ivars in the base classes may not be
17637 // duplicates.
17638 if (ID->getSuperClass())
17639 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17640 } else if (ObjCImplementationDecl *IMPDecl =
17641 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17642 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")((void)0);
17643 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17644 // Ivar declared in @implementation never belongs to the implementation.
17645 // Only it is in implementation's lexical context.
17646 ClsFields[I]->setLexicalDeclContext(IMPDecl);
17647 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17648 IMPDecl->setIvarLBraceLoc(LBrac);
17649 IMPDecl->setIvarRBraceLoc(RBrac);
17650 } else if (ObjCCategoryDecl *CDecl =
17651 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17652 // case of ivars in class extension; all other cases have been
17653 // reported as errors elsewhere.
17654 // FIXME. Class extension does not have a LocEnd field.
17655 // CDecl->setLocEnd(RBrac);
17656 // Add ivar's to class extension's DeclContext.
17657 // Diagnose redeclaration of private ivars.
17658 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17659 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17660 if (IDecl) {
17661 if (const ObjCIvarDecl *ClsIvar =
17662 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17663 Diag(ClsFields[i]->getLocation(),
17664 diag::err_duplicate_ivar_declaration);
17665 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17666 continue;
17667 }
17668 for (const auto *Ext : IDecl->known_extensions()) {
17669 if (const ObjCIvarDecl *ClsExtIvar
17670 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
17671 Diag(ClsFields[i]->getLocation(),
17672 diag::err_duplicate_ivar_declaration);
17673 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
17674 continue;
17675 }
17676 }
17677 }
17678 ClsFields[i]->setLexicalDeclContext(CDecl);
17679 CDecl->addDecl(ClsFields[i]);
17680 }
17681 CDecl->setIvarLBraceLoc(LBrac);
17682 CDecl->setIvarRBraceLoc(RBrac);
17683 }
17684 }
17685}
17686
17687/// Determine whether the given integral value is representable within
17688/// the given type T.
17689static bool isRepresentableIntegerValue(ASTContext &Context,
17690 llvm::APSInt &Value,
17691 QualType T) {
17692 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&((void)0)
17693 "Integral type required!")((void)0);
17694 unsigned BitWidth = Context.getIntWidth(T);
17695
17696 if (Value.isUnsigned() || Value.isNonNegative()) {
17697 if (T->isSignedIntegerOrEnumerationType())
17698 --BitWidth;
17699 return Value.getActiveBits() <= BitWidth;
17700 }
17701 return Value.getMinSignedBits() <= BitWidth;
17702}
17703
17704// Given an integral type, return the next larger integral type
17705// (or a NULL type of no such type exists).
17706static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
17707 // FIXME: Int128/UInt128 support, which also needs to be introduced into
17708 // enum checking below.
17709 assert((T->isIntegralType(Context) ||((void)0)
17710 T->isEnumeralType()) && "Integral type required!")((void)0);
17711 const unsigned NumTypes = 4;
17712 QualType SignedIntegralTypes[NumTypes] = {
17713 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
17714 };
17715 QualType UnsignedIntegralTypes[NumTypes] = {
17716 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
17717 Context.UnsignedLongLongTy
17718 };
17719
17720 unsigned BitWidth = Context.getTypeSize(T);
17721 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
17722 : UnsignedIntegralTypes;
17723 for (unsigned I = 0; I != NumTypes; ++I)
17724 if (Context.getTypeSize(Types[I]) > BitWidth)
17725 return Types[I];
17726
17727 return QualType();
17728}
17729
17730EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
17731 EnumConstantDecl *LastEnumConst,
17732 SourceLocation IdLoc,
17733 IdentifierInfo *Id,
17734 Expr *Val) {
17735 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
17736 llvm::APSInt EnumVal(IntWidth);
17737 QualType EltTy;
17738
17739 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
17740 Val = nullptr;
17741
17742 if (Val)
17743 Val = DefaultLvalueConversion(Val).get();
17744
17745 if (Val) {
17746 if (Enum->isDependentType() || Val->isTypeDependent())
17747 EltTy = Context.DependentTy;
17748 else {
17749 // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
17750 // underlying type, but do allow it in all other contexts.
17751 if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
17752 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
17753 // constant-expression in the enumerator-definition shall be a converted
17754 // constant expression of the underlying type.
17755 EltTy = Enum->getIntegerType();
17756 ExprResult Converted =
17757 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
17758 CCEK_Enumerator);
17759 if (Converted.isInvalid())
17760 Val = nullptr;
17761 else
17762 Val = Converted.get();
17763 } else if (!Val->isValueDependent() &&
17764 !(Val =
17765 VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
17766 .get())) {
17767 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
17768 } else {
17769 if (Enum->isComplete()) {
17770 EltTy = Enum->getIntegerType();
17771
17772 // In Obj-C and Microsoft mode, require the enumeration value to be
17773 // representable in the underlying type of the enumeration. In C++11,
17774 // we perform a non-narrowing conversion as part of converted constant
17775 // expression checking.
17776 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17777 if (Context.getTargetInfo()
17778 .getTriple()
17779 .isWindowsMSVCEnvironment()) {
17780 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
17781 } else {
17782 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
17783 }
17784 }
17785
17786 // Cast to the underlying type.
17787 Val = ImpCastExprToType(Val, EltTy,
17788 EltTy->isBooleanType() ? CK_IntegralToBoolean
17789 : CK_IntegralCast)
17790 .get();
17791 } else if (getLangOpts().CPlusPlus) {
17792 // C++11 [dcl.enum]p5:
17793 // If the underlying type is not fixed, the type of each enumerator
17794 // is the type of its initializing value:
17795 // - If an initializer is specified for an enumerator, the
17796 // initializing value has the same type as the expression.
17797 EltTy = Val->getType();
17798 } else {
17799 // C99 6.7.2.2p2:
17800 // The expression that defines the value of an enumeration constant
17801 // shall be an integer constant expression that has a value
17802 // representable as an int.
17803
17804 // Complain if the value is not representable in an int.
17805 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
17806 Diag(IdLoc, diag::ext_enum_value_not_int)
17807 << toString(EnumVal, 10) << Val->getSourceRange()
17808 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
17809 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
17810 // Force the type of the expression to 'int'.
17811 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
17812 }
17813 EltTy = Val->getType();
17814 }
17815 }
17816 }
17817 }
17818
17819 if (!Val) {
17820 if (Enum->isDependentType())
17821 EltTy = Context.DependentTy;
17822 else if (!LastEnumConst) {
17823 // C++0x [dcl.enum]p5:
17824 // If the underlying type is not fixed, the type of each enumerator
17825 // is the type of its initializing value:
17826 // - If no initializer is specified for the first enumerator, the
17827 // initializing value has an unspecified integral type.
17828 //
17829 // GCC uses 'int' for its unspecified integral type, as does
17830 // C99 6.7.2.2p3.
17831 if (Enum->isFixed()) {
17832 EltTy = Enum->getIntegerType();
17833 }
17834 else {
17835 EltTy = Context.IntTy;
17836 }
17837 } else {
17838 // Assign the last value + 1.
17839 EnumVal = LastEnumConst->getInitVal();
17840 ++EnumVal;
17841 EltTy = LastEnumConst->getType();
17842
17843 // Check for overflow on increment.
17844 if (EnumVal < LastEnumConst->getInitVal()) {
17845 // C++0x [dcl.enum]p5:
17846 // If the underlying type is not fixed, the type of each enumerator
17847 // is the type of its initializing value:
17848 //
17849 // - Otherwise the type of the initializing value is the same as
17850 // the type of the initializing value of the preceding enumerator
17851 // unless the incremented value is not representable in that type,
17852 // in which case the type is an unspecified integral type
17853 // sufficient to contain the incremented value. If no such type
17854 // exists, the program is ill-formed.
17855 QualType T = getNextLargerIntegralType(Context, EltTy);
17856 if (T.isNull() || Enum->isFixed()) {
17857 // There is no integral type larger enough to represent this
17858 // value. Complain, then allow the value to wrap around.
17859 EnumVal = LastEnumConst->getInitVal();
17860 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
17861 ++EnumVal;
17862 if (Enum->isFixed())
17863 // When the underlying type is fixed, this is ill-formed.
17864 Diag(IdLoc, diag::err_enumerator_wrapped)
17865 << toString(EnumVal, 10)
17866 << EltTy;
17867 else
17868 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
17869 << toString(EnumVal, 10);
17870 } else {
17871 EltTy = T;
17872 }
17873
17874 // Retrieve the last enumerator's value, extent that type to the
17875 // type that is supposed to be large enough to represent the incremented
17876 // value, then increment.
17877 EnumVal = LastEnumConst->getInitVal();
17878 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17879 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
17880 ++EnumVal;
17881
17882 // If we're not in C++, diagnose the overflow of enumerator values,
17883 // which in C99 means that the enumerator value is not representable in
17884 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
17885 // permits enumerator values that are representable in some larger
17886 // integral type.
17887 if (!getLangOpts().CPlusPlus && !T.isNull())
17888 Diag(IdLoc, diag::warn_enum_value_overflow);
17889 } else if (!getLangOpts().CPlusPlus &&
17890 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
17891 // Enforce C99 6.7.2.2p2 even when we compute the next value.
17892 Diag(IdLoc, diag::ext_enum_value_not_int)
17893 << toString(EnumVal, 10) << 1;
17894 }
17895 }
17896 }
17897
17898 if (!EltTy->isDependentType()) {
17899 // Make the enumerator value match the signedness and size of the
17900 // enumerator's type.
17901 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
17902 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
17903 }
17904
17905 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
17906 Val, EnumVal);
17907}
17908
17909Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
17910 SourceLocation IILoc) {
17911 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
17912 !getLangOpts().CPlusPlus)
17913 return SkipBodyInfo();
17914
17915 // We have an anonymous enum definition. Look up the first enumerator to
17916 // determine if we should merge the definition with an existing one and
17917 // skip the body.
17918 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
17919 forRedeclarationInCurContext());
17920 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
17921 if (!PrevECD)
17922 return SkipBodyInfo();
17923
17924 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
17925 NamedDecl *Hidden;
17926 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
17927 SkipBodyInfo Skip;
17928 Skip.Previous = Hidden;
17929 return Skip;
17930 }
17931
17932 return SkipBodyInfo();
17933}
17934
17935Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
17936 SourceLocation IdLoc, IdentifierInfo *Id,
17937 const ParsedAttributesView &Attrs,
17938 SourceLocation EqualLoc, Expr *Val) {
17939 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
17940 EnumConstantDecl *LastEnumConst =
17941 cast_or_null<EnumConstantDecl>(lastEnumConst);
17942
17943 // The scope passed in may not be a decl scope. Zip up the scope tree until
17944 // we find one that is.
17945 S = getNonFieldDeclScope(S);
17946
17947 // Verify that there isn't already something declared with this name in this
17948 // scope.
17949 LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
17950 LookupName(R, S);
17951 NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
17952
17953 if (PrevDecl && PrevDecl->isTemplateParameter()) {
17954 // Maybe we will complain about the shadowed template parameter.
17955 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
17956 // Just pretend that we didn't see the previous declaration.
17957 PrevDecl = nullptr;
17958 }
17959
17960 // C++ [class.mem]p15:
17961 // If T is the name of a class, then each of the following shall have a name
17962 // different from T:
17963 // - every enumerator of every member of class T that is an unscoped
17964 // enumerated type
17965 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
17966 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
17967 DeclarationNameInfo(Id, IdLoc));
17968
17969 EnumConstantDecl *New =
17970 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
17971 if (!New)
17972 return nullptr;
17973
17974 if (PrevDecl) {
17975 if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
17976 // Check for other kinds of shadowing not already handled.
17977 CheckShadow(New, PrevDecl, R);
17978 }
17979
17980 // When in C++, we may get a TagDecl with the same name; in this case the
17981 // enum constant will 'hide' the tag.
17982 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&((void)0)
17983 "Received TagDecl when not in C++!")((void)0);
17984 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
17985 if (isa<EnumConstantDecl>(PrevDecl))
17986 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
17987 else
17988 Diag(IdLoc, diag::err_redefinition) << Id;
17989 notePreviousDefinition(PrevDecl, IdLoc);
17990 return nullptr;
17991 }
17992 }
17993
17994 // Process attributes.
17995 ProcessDeclAttributeList(S, New, Attrs);
17996 AddPragmaAttributes(S, New);
17997
17998 // Register this decl in the current scope stack.
17999 New->setAccess(TheEnumDecl->getAccess());
18000 PushOnScopeChains(New, S);
18001
18002 ActOnDocumentableDecl(New);
18003
18004 return New;
18005}
18006
18007// Returns true when the enum initial expression does not trigger the
18008// duplicate enum warning. A few common cases are exempted as follows:
18009// Element2 = Element1
18010// Element2 = Element1 + 1
18011// Element2 = Element1 - 1
18012// Where Element2 and Element1 are from the same enum.
18013static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
18014 Expr *InitExpr = ECD->getInitExpr();
18015 if (!InitExpr)
18016 return true;
18017 InitExpr = InitExpr->IgnoreImpCasts();
18018
18019 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18020 if (!BO->isAdditiveOp())
18021 return true;
18022 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18023 if (!IL)
18024 return true;
18025 if (IL->getValue() != 1)
18026 return true;
18027
18028 InitExpr = BO->getLHS();
18029 }
18030
18031 // This checks if the elements are from the same enum.
18032 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18033 if (!DRE)
18034 return true;
18035
18036 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18037 if (!EnumConstant)
18038 return true;
18039
18040 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18041 Enum)
18042 return true;
18043
18044 return false;
18045}
18046
18047// Emits a warning when an element is implicitly set a value that
18048// a previous element has already been set to.
18049static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
18050 EnumDecl *Enum, QualType EnumType) {
18051 // Avoid anonymous enums
18052 if (!Enum->getIdentifier())
18053 return;
18054
18055 // Only check for small enums.
18056 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18057 return;
18058
18059 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18060 return;
18061
18062 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18063 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18064
18065 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18066
18067 // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18068 typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18069
18070 // Use int64_t as a key to avoid needing special handling for map keys.
18071 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18072 llvm::APSInt Val = D->getInitVal();
18073 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18074 };
18075
18076 DuplicatesVector DupVector;
18077 ValueToVectorMap EnumMap;
18078
18079 // Populate the EnumMap with all values represented by enum constants without
18080 // an initializer.
18081 for (auto *Element : Elements) {
18082 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18083
18084 // Null EnumConstantDecl means a previous diagnostic has been emitted for
18085 // this constant. Skip this enum since it may be ill-formed.
18086 if (!ECD) {
18087 return;
18088 }
18089
18090 // Constants with initalizers are handled in the next loop.
18091 if (ECD->getInitExpr())
18092 continue;
18093
18094 // Duplicate values are handled in the next loop.
18095 EnumMap.insert({EnumConstantToKey(ECD), ECD});
18096 }
18097
18098 if (EnumMap.size() == 0)
18099 return;
18100
18101 // Create vectors for any values that has duplicates.
18102 for (auto *Element : Elements) {
18103 // The last loop returned if any constant was null.
18104 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18105 if (!ValidDuplicateEnum(ECD, Enum))
18106 continue;
18107
18108 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18109 if (Iter == EnumMap.end())
18110 continue;
18111
18112 DeclOrVector& Entry = Iter->second;
18113 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18114 // Ensure constants are different.
18115 if (D == ECD)
18116 continue;
18117
18118 // Create new vector and push values onto it.
18119 auto Vec = std::make_unique<ECDVector>();
18120 Vec->push_back(D);
18121 Vec->push_back(ECD);
18122
18123 // Update entry to point to the duplicates vector.
18124 Entry = Vec.get();
18125
18126 // Store the vector somewhere we can consult later for quick emission of
18127 // diagnostics.
18128 DupVector.emplace_back(std::move(Vec));
18129 continue;
18130 }
18131
18132 ECDVector *Vec = Entry.get<ECDVector*>();
18133 // Make sure constants are not added more than once.
18134 if (*Vec->begin() == ECD)
18135 continue;
18136
18137 Vec->push_back(ECD);
18138 }
18139
18140 // Emit diagnostics.
18141 for (const auto &Vec : DupVector) {
18142 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")((void)0);
18143
18144 // Emit warning for one enum constant.
18145 auto *FirstECD = Vec->front();
18146 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18147 << FirstECD << toString(FirstECD->getInitVal(), 10)
18148 << FirstECD->getSourceRange();
18149
18150 // Emit one note for each of the remaining enum constants with
18151 // the same value.
18152 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
18153 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18154 << ECD << toString(ECD->getInitVal(), 10)
18155 << ECD->getSourceRange();
18156 }
18157}
18158
18159bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18160 bool AllowMask) const {
18161 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")((void)0);
18162 assert(ED->isCompleteDefinition() && "expected enum definition")((void)0);
18163
18164 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18165 llvm::APInt &FlagBits = R.first->second;
18166
18167 if (R.second) {
18168 for (auto *E : ED->enumerators()) {
18169 const auto &EVal = E->getInitVal();
18170 // Only single-bit enumerators introduce new flag values.
18171 if (EVal.isPowerOf2())
18172 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18173 }
18174 }
18175
18176 // A value is in a flag enum if either its bits are a subset of the enum's
18177 // flag bits (the first condition) or we are allowing masks and the same is
18178 // true of its complement (the second condition). When masks are allowed, we
18179 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18180 //
18181 // While it's true that any value could be used as a mask, the assumption is
18182 // that a mask will have all of the insignificant bits set. Anything else is
18183 // likely a logic error.
18184 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18185 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18186}
18187
18188void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
18189 Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18190 const ParsedAttributesView &Attrs) {
18191 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18192 QualType EnumType = Context.getTypeDeclType(Enum);
18193
18194 ProcessDeclAttributeList(S, Enum, Attrs);
18195
18196 if (Enum->isDependentType()) {
18197 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18198 EnumConstantDecl *ECD =
18199 cast_or_null<EnumConstantDecl>(Elements[i]);
18200 if (!ECD) continue;
18201
18202 ECD->setType(EnumType);
18203 }
18204
18205 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18206 return;
18207 }
18208
18209 // TODO: If the result value doesn't fit in an int, it must be a long or long
18210 // long value. ISO C does not support this, but GCC does as an extension,
18211 // emit a warning.
18212 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18213 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18214 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18215
18216 // Verify that all the values are okay, compute the size of the values, and
18217 // reverse the list.
18218 unsigned NumNegativeBits = 0;
18219 unsigned NumPositiveBits = 0;
18220
18221 // Keep track of whether all elements have type int.
18222 bool AllElementsInt = true;
18223
18224 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18225 EnumConstantDecl *ECD =
18226 cast_or_null<EnumConstantDecl>(Elements[i]);
18227 if (!ECD) continue; // Already issued a diagnostic.
18228
18229 const llvm::APSInt &InitVal = ECD->getInitVal();
18230
18231 // Keep track of the size of positive and negative values.
18232 if (InitVal.isUnsigned() || InitVal.isNonNegative())
18233 NumPositiveBits = std::max(NumPositiveBits,
18234 (unsigned)InitVal.getActiveBits());
18235 else
18236 NumNegativeBits = std::max(NumNegativeBits,
18237 (unsigned)InitVal.getMinSignedBits());
18238
18239 // Keep track of whether every enum element has type int (very common).
18240 if (AllElementsInt)
18241 AllElementsInt = ECD->getType() == Context.IntTy;
18242 }
18243
18244 // Figure out the type that should be used for this enum.
18245 QualType BestType;
18246 unsigned BestWidth;
18247
18248 // C++0x N3000 [conv.prom]p3:
18249 // An rvalue of an unscoped enumeration type whose underlying
18250 // type is not fixed can be converted to an rvalue of the first
18251 // of the following types that can represent all the values of
18252 // the enumeration: int, unsigned int, long int, unsigned long
18253 // int, long long int, or unsigned long long int.
18254 // C99 6.4.4.3p2:
18255 // An identifier declared as an enumeration constant has type int.
18256 // The C99 rule is modified by a gcc extension
18257 QualType BestPromotionType;
18258
18259 bool Packed = Enum->hasAttr<PackedAttr>();
18260 // -fshort-enums is the equivalent to specifying the packed attribute on all
18261 // enum definitions.
18262 if (LangOpts.ShortEnums)
18263 Packed = true;
18264
18265 // If the enum already has a type because it is fixed or dictated by the
18266 // target, promote that type instead of analyzing the enumerators.
18267 if (Enum->isComplete()) {
18268 BestType = Enum->getIntegerType();
18269 if (BestType->isPromotableIntegerType())
18270 BestPromotionType = Context.getPromotedIntegerType(BestType);
18271 else
18272 BestPromotionType = BestType;
18273
18274 BestWidth = Context.getIntWidth(BestType);
18275 }
18276 else if (NumNegativeBits) {
18277 // If there is a negative value, figure out the smallest integer type (of
18278 // int/long/longlong) that fits.
18279 // If it's packed, check also if it fits a char or a short.
18280 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18281 BestType = Context.SignedCharTy;
18282 BestWidth = CharWidth;
18283 } else if (Packed && NumNegativeBits <= ShortWidth &&
18284 NumPositiveBits < ShortWidth) {
18285 BestType = Context.ShortTy;
18286 BestWidth = ShortWidth;
18287 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18288 BestType = Context.IntTy;
18289 BestWidth = IntWidth;
18290 } else {
18291 BestWidth = Context.getTargetInfo().getLongWidth();
18292
18293 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18294 BestType = Context.LongTy;
18295 } else {
18296 BestWidth = Context.getTargetInfo().getLongLongWidth();
18297
18298 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18299 Diag(Enum->getLocation(), diag::ext_enum_too_large);
18300 BestType = Context.LongLongTy;
18301 }
18302 }
18303 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18304 } else {
18305 // If there is no negative value, figure out the smallest type that fits
18306 // all of the enumerator values.
18307 // If it's packed, check also if it fits a char or a short.
18308 if (Packed && NumPositiveBits <= CharWidth) {
18309 BestType = Context.UnsignedCharTy;
18310 BestPromotionType = Context.IntTy;
18311 BestWidth = CharWidth;
18312 } else if (Packed && NumPositiveBits <= ShortWidth) {
18313 BestType = Context.UnsignedShortTy;
18314 BestPromotionType = Context.IntTy;
18315 BestWidth = ShortWidth;
18316 } else if (NumPositiveBits <= IntWidth) {
18317 BestType = Context.UnsignedIntTy;
18318 BestWidth = IntWidth;
18319 BestPromotionType
18320 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18321 ? Context.UnsignedIntTy : Context.IntTy;
18322 } else if (NumPositiveBits <=
18323 (BestWidth = Context.getTargetInfo().getLongWidth())) {
18324 BestType = Context.UnsignedLongTy;
18325 BestPromotionType
18326 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18327 ? Context.UnsignedLongTy : Context.LongTy;
18328 } else {
18329 BestWidth = Context.getTargetInfo().getLongLongWidth();
18330 assert(NumPositiveBits <= BestWidth &&((void)0)
18331 "How could an initializer get larger than ULL?")((void)0);
18332 BestType = Context.UnsignedLongLongTy;
18333 BestPromotionType
18334 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18335 ? Context.UnsignedLongLongTy : Context.LongLongTy;
18336 }
18337 }
18338
18339 // Loop over all of the enumerator constants, changing their types to match
18340 // the type of the enum if needed.
18341 for (auto *D : Elements) {
18342 auto *ECD = cast_or_null<EnumConstantDecl>(D);
18343 if (!ECD) continue; // Already issued a diagnostic.
18344
18345 // Standard C says the enumerators have int type, but we allow, as an
18346 // extension, the enumerators to be larger than int size. If each
18347 // enumerator value fits in an int, type it as an int, otherwise type it the
18348 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18349 // that X has type 'int', not 'unsigned'.
18350
18351 // Determine whether the value fits into an int.
18352 llvm::APSInt InitVal = ECD->getInitVal();
18353
18354 // If it fits into an integer type, force it. Otherwise force it to match
18355 // the enum decl type.
18356 QualType NewTy;
18357 unsigned NewWidth;
18358 bool NewSign;
18359 if (!getLangOpts().CPlusPlus &&
18360 !Enum->isFixed() &&
18361 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18362 NewTy = Context.IntTy;
18363 NewWidth = IntWidth;
18364 NewSign = true;
18365 } else if (ECD->getType() == BestType) {
18366 // Already the right type!
18367 if (getLangOpts().CPlusPlus)
18368 // C++ [dcl.enum]p4: Following the closing brace of an
18369 // enum-specifier, each enumerator has the type of its
18370 // enumeration.
18371 ECD->setType(EnumType);
18372 continue;
18373 } else {
18374 NewTy = BestType;
18375 NewWidth = BestWidth;
18376 NewSign = BestType->isSignedIntegerOrEnumerationType();
18377 }
18378
18379 // Adjust the APSInt value.
18380 InitVal = InitVal.extOrTrunc(NewWidth);
18381 InitVal.setIsSigned(NewSign);
18382 ECD->setInitVal(InitVal);
18383
18384 // Adjust the Expr initializer and type.
18385 if (ECD->getInitExpr() &&
18386 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18387 ECD->setInitExpr(ImplicitCastExpr::Create(
18388 Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18389 /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18390 if (getLangOpts().CPlusPlus)
18391 // C++ [dcl.enum]p4: Following the closing brace of an
18392 // enum-specifier, each enumerator has the type of its
18393 // enumeration.
18394 ECD->setType(EnumType);
18395 else
18396 ECD->setType(NewTy);
18397 }
18398
18399 Enum->completeDefinition(BestType, BestPromotionType,
18400 NumPositiveBits, NumNegativeBits);
18401
18402 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18403
18404 if (Enum->isClosedFlag()) {
18405 for (Decl *D : Elements) {
18406 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18407 if (!ECD) continue; // Already issued a diagnostic.
18408
18409 llvm::APSInt InitVal = ECD->getInitVal();
18410 if (InitVal != 0 && !InitVal.isPowerOf2() &&
18411 !IsValueInFlagEnum(Enum, InitVal, true))
18412 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18413 << ECD << Enum;
18414 }
18415 }
18416
18417 // Now that the enum type is defined, ensure it's not been underaligned.
18418 if (Enum->hasAttrs())
18419 CheckAlignasUnderalignment(Enum);
18420}
18421
18422Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
18423 SourceLocation StartLoc,
18424 SourceLocation EndLoc) {
18425 StringLiteral *AsmString = cast<StringLiteral>(expr);
18426
18427 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18428 AsmString, StartLoc,
18429 EndLoc);
18430 CurContext->addDecl(New);
18431 return New;
18432}
18433
18434void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
18435 IdentifierInfo* AliasName,
18436 SourceLocation PragmaLoc,
18437 SourceLocation NameLoc,
18438 SourceLocation AliasNameLoc) {
18439 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18440 LookupOrdinaryName);
18441 AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18442 AttributeCommonInfo::AS_Pragma);
18443 AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18444 Context, AliasName->getName(), /*LiteralLabel=*/true, Info);
18445
18446 // If a declaration that:
18447 // 1) declares a function or a variable
18448 // 2) has external linkage
18449 // already exists, add a label attribute to it.
18450 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18451 if (isDeclExternC(PrevDecl))
18452 PrevDecl->addAttr(Attr);
18453 else
18454 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18455 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18456 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18457 } else
18458 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18459}
18460
18461void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
18462 SourceLocation PragmaLoc,
18463 SourceLocation NameLoc) {
18464 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18465
18466 if (PrevDecl) {
18467 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18468 } else {
18469 (void)WeakUndeclaredIdentifiers.insert(
18470 std::pair<IdentifierInfo*,WeakInfo>
18471 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
18472 }
18473}
18474
18475void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
18476 IdentifierInfo* AliasName,
18477 SourceLocation PragmaLoc,
18478 SourceLocation NameLoc,
18479 SourceLocation AliasNameLoc) {
18480 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18481 LookupOrdinaryName);
18482 WeakInfo W = WeakInfo(Name, NameLoc);
18483
18484 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18485 if (!PrevDecl->hasAttr<AliasAttr>())
18486 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18487 DeclApplyPragmaWeak(TUScope, ND, W);
18488 } else {
18489 (void)WeakUndeclaredIdentifiers.insert(
18490 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
18491 }
18492}
18493
18494Decl *Sema::getObjCDeclContext() const {
18495 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18496}
18497
18498Sema::FunctionEmissionStatus Sema::getEmissionStatus(FunctionDecl *FD,
18499 bool Final) {
18500 assert(FD && "Expected non-null FunctionDecl")((void)0);
18501
18502 // SYCL functions can be template, so we check if they have appropriate
18503 // attribute prior to checking if it is a template.
18504 if (LangOpts.SYCLIsDevice && FD->hasAttr<SYCLKernelAttr>())
18505 return FunctionEmissionStatus::Emitted;
18506
18507 // Templates are emitted when they're instantiated.
18508 if (FD->isDependentContext())
18509 return FunctionEmissionStatus::TemplateDiscarded;
18510
18511 // Check whether this function is an externally visible definition.
18512 auto IsEmittedForExternalSymbol = [this, FD]() {
18513 // We have to check the GVA linkage of the function's *definition* -- if we
18514 // only have a declaration, we don't know whether or not the function will
18515 // be emitted, because (say) the definition could include "inline".
18516 FunctionDecl *Def = FD->getDefinition();
18517
18518 return Def && !isDiscardableGVALinkage(
18519 getASTContext().GetGVALinkageForFunction(Def));
18520 };
18521
18522 if (LangOpts.OpenMPIsDevice) {
18523 // In OpenMP device mode we will not emit host only functions, or functions
18524 // we don't need due to their linkage.
18525 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18526 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18527 // DevTy may be changed later by
18528 // #pragma omp declare target to(*) device_type(*).
18529 // Therefore DevTy having no value does not imply host. The emission status
18530 // will be checked again at the end of compilation unit with Final = true.
18531 if (DevTy.hasValue())
18532 if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18533 return FunctionEmissionStatus::OMPDiscarded;
18534 // If we have an explicit value for the device type, or we are in a target
18535 // declare context, we need to emit all extern and used symbols.
18536 if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18537 if (IsEmittedForExternalSymbol())
18538 return FunctionEmissionStatus::Emitted;
18539 // Device mode only emits what it must, if it wasn't tagged yet and needed,
18540 // we'll omit it.
18541 if (Final)
18542 return FunctionEmissionStatus::OMPDiscarded;
18543 } else if (LangOpts.OpenMP > 45) {
18544 // In OpenMP host compilation prior to 5.0 everything was an emitted host
18545 // function. In 5.0, no_host was introduced which might cause a function to
18546 // be ommitted.
18547 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
18548 OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18549 if (DevTy.hasValue())
18550 if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18551 return FunctionEmissionStatus::OMPDiscarded;
18552 }
18553
18554 if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18555 return FunctionEmissionStatus::Emitted;
18556
18557 if (LangOpts.CUDA) {
18558 // When compiling for device, host functions are never emitted. Similarly,
18559 // when compiling for host, device and global functions are never emitted.
18560 // (Technically, we do emit a host-side stub for global functions, but this
18561 // doesn't count for our purposes here.)
18562 Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18563 if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18564 return FunctionEmissionStatus::CUDADiscarded;
18565 if (!LangOpts.CUDAIsDevice &&
18566 (T == Sema::CFT_Device || T == Sema::CFT_Global))
18567 return FunctionEmissionStatus::CUDADiscarded;
18568
18569 if (IsEmittedForExternalSymbol())
18570 return FunctionEmissionStatus::Emitted;
18571 }
18572
18573 // Otherwise, the function is known-emitted if it's in our set of
18574 // known-emitted functions.
18575 return FunctionEmissionStatus::Unknown;
18576}
18577
18578bool Sema::shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee) {
18579 // Host-side references to a __global__ function refer to the stub, so the
18580 // function itself is never emitted and therefore should not be marked.
18581 // If we have host fn calls kernel fn calls host+device, the HD function
18582 // does not get instantiated on the host. We model this by omitting at the
18583 // call to the kernel from the callgraph. This ensures that, when compiling
18584 // for host, only HD functions actually called from the host get marked as
18585 // known-emitted.
18586 return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18587 IdentifyCUDATarget(Callee) == CFT_Global;
18588}

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

/usr/src/gnu/usr.bin/clang/libclangSema/../../../llvm/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
136class StreamingDiagnostic;
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.
141template <class Ptr> struct IsResultPtrLowBitFree {
142 static const bool value = false;
143 };
144
145 /// ActionResult - This structure is used while parsing/acting on
146 /// expressions, stmts, etc. It encapsulates both the object returned by
147 /// the action, plus a sense of whether or not it is valid.
148 /// When CompressInvalid is true, the "invalid" flag will be
149 /// stored in the low bit of the Val pointer.
150 template<class PtrTy,
151 bool CompressInvalid = IsResultPtrLowBitFree<PtrTy>::value>
152 class ActionResult {
153 PtrTy Val;
154 bool Invalid;
155
156 public:
157 ActionResult(bool Invalid = false) : Val(PtrTy()), Invalid(Invalid) {}
158 ActionResult(PtrTy val) : Val(val), Invalid(false) {}
159 ActionResult(const DiagnosticBuilder &) : Val(PtrTy()), Invalid(true) {}
160
161 // These two overloads prevent void* -> bool conversions.
162 ActionResult(const void *) = delete;
163 ActionResult(volatile void *) = delete;
164
165 bool isInvalid() const { return Invalid; }
166 bool isUsable() const { return !Invalid && Val; }
167 bool isUnset() const { return !Invalid && !Val; }
168
169 PtrTy get() const { return Val; }
170 template <typename T> T *getAs() { return static_cast<T*>(get()); }
171
172 void set(PtrTy V) { Val = V; }
173
174 const ActionResult &operator=(PtrTy RHS) {
175 Val = RHS;
176 Invalid = false;
177 return *this;
178 }
179 };
180
181 // This ActionResult partial specialization places the "invalid"
182 // flag into the low bit of the pointer.
183 template<typename PtrTy>
184 class ActionResult<PtrTy, true> {
185 // A pointer whose low bit is 1 if this result is invalid, 0
186 // otherwise.
187 uintptr_t PtrWithInvalid;
188
189 using PtrTraits = llvm::PointerLikeTypeTraits<PtrTy>;
190
191 public:
192 ActionResult(bool Invalid = false)
193 : PtrWithInvalid(static_cast<uintptr_t>(Invalid)) {}
194
195 ActionResult(PtrTy V) {
196 void *VP = PtrTraits::getAsVoidPointer(V);
197 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
198 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")((void)0);
199 }
200
201 ActionResult(const DiagnosticBuilder &) : PtrWithInvalid(0x01) {}
202
203 // These two overloads prevent void* -> bool conversions.
204 ActionResult(const void *) = delete;
205 ActionResult(volatile void *) = delete;
206
207 bool isInvalid() const { return PtrWithInvalid & 0x01; }
208 bool isUsable() const { return PtrWithInvalid > 0x01; }
15
Assuming field 'PtrWithInvalid' is > 1
16
Returning the value 1, which participates in a condition later
209 bool isUnset() const { return PtrWithInvalid == 0; }
210
211 PtrTy get() const {
212 void *VP = reinterpret_cast<void *>(PtrWithInvalid & ~0x01);
213 return PtrTraits::getFromVoidPointer(VP);
214 }
215
216 template <typename T> T *getAs() { return static_cast<T*>(get()); }
217
218 void set(PtrTy V) {
219 void *VP = PtrTraits::getAsVoidPointer(V);
220 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
221 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")((void)0);
222 }
223
224 const ActionResult &operator=(PtrTy RHS) {
225 void *VP = PtrTraits::getAsVoidPointer(RHS);
226 PtrWithInvalid = reinterpret_cast<uintptr_t>(VP);
227 assert((PtrWithInvalid & 0x01) == 0 && "Badly aligned pointer")((void)0);
228 return *this;
229 }
230
231 // For types where we can fit a flag in with the pointer, provide
232 // conversions to/from pointer type.
233 static ActionResult getFromOpaquePointer(void *P) {
234 ActionResult Result;
235 Result.PtrWithInvalid = (uintptr_t)P;
236 return Result;
237 }
238 void *getAsOpaquePointer() const { return (void*)PtrWithInvalid; }
239 };
240
241 /// An opaque type for threading parsed type information through the
242 /// parser.
243 using ParsedType = OpaquePtr<QualType>;
244 using UnionParsedType = UnionOpaquePtr<QualType>;
245
246 // We can re-use the low bit of expression, statement, base, and
247 // member-initializer pointers for the "invalid" flag of
248 // ActionResult.
249 template<> struct IsResultPtrLowBitFree<Expr*> {
250 static const bool value = true;
251 };
252 template<> struct IsResultPtrLowBitFree<Stmt*> {
253 static const bool value = true;
254 };
255 template<> struct IsResultPtrLowBitFree<CXXBaseSpecifier*> {
256 static const bool value = true;
257 };
258 template<> struct IsResultPtrLowBitFree<CXXCtorInitializer*> {
259 static const bool value = true;
260 };
261
262 using ExprResult = ActionResult<Expr *>;
263 using StmtResult = ActionResult<Stmt *>;
264 using TypeResult = ActionResult<ParsedType>;
265 using BaseResult = ActionResult<CXXBaseSpecifier *>;
266 using MemInitResult = ActionResult<CXXCtorInitializer *>;
267
268 using DeclResult = ActionResult<Decl *>;
269 using ParsedTemplateTy = OpaquePtr<TemplateName>;
270 using UnionParsedTemplateTy = UnionOpaquePtr<TemplateName>;
271
272 using MultiExprArg = MutableArrayRef<Expr *>;
273 using MultiStmtArg = MutableArrayRef<Stmt *>;
274 using ASTTemplateArgsPtr = MutableArrayRef<ParsedTemplateArgument>;
275 using MultiTypeArg = MutableArrayRef<ParsedType>;
276 using MultiTemplateParamsArg = MutableArrayRef<TemplateParameterList *>;
277
278 inline ExprResult ExprError() { return ExprResult(true); }
279 inline StmtResult StmtError() { return StmtResult(true); }
280 inline TypeResult TypeError() { return TypeResult(true); }
281
282 inline ExprResult ExprError(const StreamingDiagnostic &) {
283 return ExprError();
284 }
285 inline StmtResult StmtError(const StreamingDiagnostic &) {
286 return StmtError();
287 }
288
289 inline ExprResult ExprEmpty() { return ExprResult(false); }
290 inline StmtResult StmtEmpty() { return StmtResult(false); }
291
292 inline Expr *AssertSuccess(ExprResult R) {
293 assert(!R.isInvalid() && "operation was asserted to never fail!")((void)0);
294 return R.get();
295 }
296
297 inline Stmt *AssertSuccess(StmtResult R) {
298 assert(!R.isInvalid() && "operation was asserted to never fail!")((void)0);
299 return R.get();
300 }
301
302} // namespace clang
303
304#endif // LLVM_CLANG_SEMA_OWNERSHIP_H