Bug Summary

File:clang/include/clang/AST/ASTContext.h
Warning:line 1529, column 9
Access to field 'TypeForDecl' results in a dereference of a null pointer (loaded from variable 'Decl')

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDeclCXX.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaDeclCXX.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaDeclCXX.cpp

1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ 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 C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/EvaluatedExprVisitor.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/AST/RecordLayout.h"
23#include "clang/AST/RecursiveASTVisitor.h"
24#include "clang/AST/StmtVisitor.h"
25#include "clang/AST/TypeLoc.h"
26#include "clang/AST/TypeOrdering.h"
27#include "clang/Basic/AttributeCommonInfo.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/LiteralSupport.h"
31#include "clang/Lex/Preprocessor.h"
32#include "clang/Sema/CXXFieldCollector.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/Initialization.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/Scope.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
40#include "clang/Sema/Template.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallString.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/StringExtras.h"
45#include <map>
46#include <set>
47
48using namespace clang;
49
50//===----------------------------------------------------------------------===//
51// CheckDefaultArgumentVisitor
52//===----------------------------------------------------------------------===//
53
54namespace {
55/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
56/// the default argument of a parameter to determine whether it
57/// contains any ill-formed subexpressions. For example, this will
58/// diagnose the use of local variables or parameters within the
59/// default argument expression.
60class CheckDefaultArgumentVisitor
61 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
62 Sema &S;
63 const Expr *DefaultArg;
64
65public:
66 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
67 : S(S), DefaultArg(DefaultArg) {}
68
69 bool VisitExpr(const Expr *Node);
70 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
71 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
72 bool VisitLambdaExpr(const LambdaExpr *Lambda);
73 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
74};
75
76/// VisitExpr - Visit all of the children of this expression.
77bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
78 bool IsInvalid = false;
79 for (const Stmt *SubStmt : Node->children())
80 IsInvalid |= Visit(SubStmt);
81 return IsInvalid;
82}
83
84/// VisitDeclRefExpr - Visit a reference to a declaration, to
85/// determine whether this declaration can be used in the default
86/// argument expression.
87bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
88 const NamedDecl *Decl = DRE->getDecl();
89 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
90 // C++ [dcl.fct.default]p9:
91 // [...] parameters of a function shall not be used in default
92 // argument expressions, even if they are not evaluated. [...]
93 //
94 // C++17 [dcl.fct.default]p9 (by CWG 2082):
95 // [...] A parameter shall not appear as a potentially-evaluated
96 // expression in a default argument. [...]
97 //
98 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
99 return S.Diag(DRE->getBeginLoc(),
100 diag::err_param_default_argument_references_param)
101 << Param->getDeclName() << DefaultArg->getSourceRange();
102 } else if (const auto *VDecl = dyn_cast<VarDecl>(Decl)) {
103 // C++ [dcl.fct.default]p7:
104 // Local variables shall not be used in default argument
105 // expressions.
106 //
107 // C++17 [dcl.fct.default]p7 (by CWG 2082):
108 // A local variable shall not appear as a potentially-evaluated
109 // expression in a default argument.
110 //
111 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
112 // Note: A local variable cannot be odr-used (6.3) in a default argument.
113 //
114 if (VDecl->isLocalVarDecl() && !DRE->isNonOdrUse())
115 return S.Diag(DRE->getBeginLoc(),
116 diag::err_param_default_argument_references_local)
117 << VDecl->getDeclName() << DefaultArg->getSourceRange();
118 }
119
120 return false;
121}
122
123/// VisitCXXThisExpr - Visit a C++ "this" expression.
124bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
125 // C++ [dcl.fct.default]p8:
126 // The keyword this shall not be used in a default argument of a
127 // member function.
128 return S.Diag(ThisE->getBeginLoc(),
129 diag::err_param_default_argument_references_this)
130 << ThisE->getSourceRange();
131}
132
133bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
134 const PseudoObjectExpr *POE) {
135 bool Invalid = false;
136 for (const Expr *E : POE->semantics()) {
137 // Look through bindings.
138 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
139 E = OVE->getSourceExpr();
140 assert(E && "pseudo-object binding without source expression?")(static_cast<void> (0));
141 }
142
143 Invalid |= Visit(E);
144 }
145 return Invalid;
146}
147
148bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
149 // C++11 [expr.lambda.prim]p13:
150 // A lambda-expression appearing in a default argument shall not
151 // implicitly or explicitly capture any entity.
152 if (Lambda->capture_begin() == Lambda->capture_end())
153 return false;
154
155 return S.Diag(Lambda->getBeginLoc(), diag::err_lambda_capture_default_arg);
156}
157} // namespace
158
159void
160Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
161 const CXXMethodDecl *Method) {
162 // If we have an MSAny spec already, don't bother.
163 if (!Method || ComputedEST == EST_MSAny)
164 return;
165
166 const FunctionProtoType *Proto
167 = Method->getType()->getAs<FunctionProtoType>();
168 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
169 if (!Proto)
170 return;
171
172 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
173
174 // If we have a throw-all spec at this point, ignore the function.
175 if (ComputedEST == EST_None)
176 return;
177
178 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
179 EST = EST_BasicNoexcept;
180
181 switch (EST) {
182 case EST_Unparsed:
183 case EST_Uninstantiated:
184 case EST_Unevaluated:
185 llvm_unreachable("should not see unresolved exception specs here")__builtin_unreachable();
186
187 // If this function can throw any exceptions, make a note of that.
188 case EST_MSAny:
189 case EST_None:
190 // FIXME: Whichever we see last of MSAny and None determines our result.
191 // We should make a consistent, order-independent choice here.
192 ClearExceptions();
193 ComputedEST = EST;
194 return;
195 case EST_NoexceptFalse:
196 ClearExceptions();
197 ComputedEST = EST_None;
198 return;
199 // FIXME: If the call to this decl is using any of its default arguments, we
200 // need to search them for potentially-throwing calls.
201 // If this function has a basic noexcept, it doesn't affect the outcome.
202 case EST_BasicNoexcept:
203 case EST_NoexceptTrue:
204 case EST_NoThrow:
205 return;
206 // If we're still at noexcept(true) and there's a throw() callee,
207 // change to that specification.
208 case EST_DynamicNone:
209 if (ComputedEST == EST_BasicNoexcept)
210 ComputedEST = EST_DynamicNone;
211 return;
212 case EST_DependentNoexcept:
213 llvm_unreachable(__builtin_unreachable()
214 "should not generate implicit declarations for dependent cases")__builtin_unreachable();
215 case EST_Dynamic:
216 break;
217 }
218 assert(EST == EST_Dynamic && "EST case not considered earlier.")(static_cast<void> (0));
219 assert(ComputedEST != EST_None &&(static_cast<void> (0))
220 "Shouldn't collect exceptions when throw-all is guaranteed.")(static_cast<void> (0));
221 ComputedEST = EST_Dynamic;
222 // Record the exceptions in this function's exception specification.
223 for (const auto &E : Proto->exceptions())
224 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
225 Exceptions.push_back(E);
226}
227
228void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
229 if (!S || ComputedEST == EST_MSAny)
230 return;
231
232 // FIXME:
233 //
234 // C++0x [except.spec]p14:
235 // [An] implicit exception-specification specifies the type-id T if and
236 // only if T is allowed by the exception-specification of a function directly
237 // invoked by f's implicit definition; f shall allow all exceptions if any
238 // function it directly invokes allows all exceptions, and f shall allow no
239 // exceptions if every function it directly invokes allows no exceptions.
240 //
241 // Note in particular that if an implicit exception-specification is generated
242 // for a function containing a throw-expression, that specification can still
243 // be noexcept(true).
244 //
245 // Note also that 'directly invoked' is not defined in the standard, and there
246 // is no indication that we should only consider potentially-evaluated calls.
247 //
248 // Ultimately we should implement the intent of the standard: the exception
249 // specification should be the set of exceptions which can be thrown by the
250 // implicit definition. For now, we assume that any non-nothrow expression can
251 // throw any exception.
252
253 if (Self->canThrow(S))
254 ComputedEST = EST_None;
255}
256
257ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
258 SourceLocation EqualLoc) {
259 if (RequireCompleteType(Param->getLocation(), Param->getType(),
260 diag::err_typecheck_decl_incomplete_type))
261 return true;
262
263 // C++ [dcl.fct.default]p5
264 // A default argument expression is implicitly converted (clause
265 // 4) to the parameter type. The default argument expression has
266 // the same semantic constraints as the initializer expression in
267 // a declaration of a variable of the parameter type, using the
268 // copy-initialization semantics (8.5).
269 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
270 Param);
271 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
272 EqualLoc);
273 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
274 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
275 if (Result.isInvalid())
276 return true;
277 Arg = Result.getAs<Expr>();
278
279 CheckCompletedExpr(Arg, EqualLoc);
280 Arg = MaybeCreateExprWithCleanups(Arg);
281
282 return Arg;
283}
284
285void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
286 SourceLocation EqualLoc) {
287 // Add the default argument to the parameter
288 Param->setDefaultArg(Arg);
289
290 // We have already instantiated this parameter; provide each of the
291 // instantiations with the uninstantiated default argument.
292 UnparsedDefaultArgInstantiationsMap::iterator InstPos
293 = UnparsedDefaultArgInstantiations.find(Param);
294 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
295 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
296 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
297
298 // We're done tracking this parameter's instantiations.
299 UnparsedDefaultArgInstantiations.erase(InstPos);
300 }
301}
302
303/// ActOnParamDefaultArgument - Check whether the default argument
304/// provided for a function parameter is well-formed. If so, attach it
305/// to the parameter declaration.
306void
307Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
308 Expr *DefaultArg) {
309 if (!param || !DefaultArg)
310 return;
311
312 ParmVarDecl *Param = cast<ParmVarDecl>(param);
313 UnparsedDefaultArgLocs.erase(Param);
314
315 auto Fail = [&] {
316 Param->setInvalidDecl();
317 Param->setDefaultArg(new (Context) OpaqueValueExpr(
318 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
319 };
320
321 // Default arguments are only permitted in C++
322 if (!getLangOpts().CPlusPlus) {
323 Diag(EqualLoc, diag::err_param_default_argument)
324 << DefaultArg->getSourceRange();
325 return Fail();
326 }
327
328 // Check for unexpanded parameter packs.
329 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
330 return Fail();
331 }
332
333 // C++11 [dcl.fct.default]p3
334 // A default argument expression [...] shall not be specified for a
335 // parameter pack.
336 if (Param->isParameterPack()) {
337 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
338 << DefaultArg->getSourceRange();
339 // Recover by discarding the default argument.
340 Param->setDefaultArg(nullptr);
341 return;
342 }
343
344 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
345 if (Result.isInvalid())
346 return Fail();
347
348 DefaultArg = Result.getAs<Expr>();
349
350 // Check that the default argument is well-formed
351 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
352 if (DefaultArgChecker.Visit(DefaultArg))
353 return Fail();
354
355 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
356}
357
358/// ActOnParamUnparsedDefaultArgument - We've seen a default
359/// argument for a function parameter, but we can't parse it yet
360/// because we're inside a class definition. Note that this default
361/// argument will be parsed later.
362void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
363 SourceLocation EqualLoc,
364 SourceLocation ArgLoc) {
365 if (!param)
366 return;
367
368 ParmVarDecl *Param = cast<ParmVarDecl>(param);
369 Param->setUnparsedDefaultArg();
370 UnparsedDefaultArgLocs[Param] = ArgLoc;
371}
372
373/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
374/// the default argument for the parameter param failed.
375void Sema::ActOnParamDefaultArgumentError(Decl *param,
376 SourceLocation EqualLoc) {
377 if (!param)
378 return;
379
380 ParmVarDecl *Param = cast<ParmVarDecl>(param);
381 Param->setInvalidDecl();
382 UnparsedDefaultArgLocs.erase(Param);
383 Param->setDefaultArg(new (Context) OpaqueValueExpr(
384 EqualLoc, Param->getType().getNonReferenceType(), VK_PRValue));
385}
386
387/// CheckExtraCXXDefaultArguments - Check for any extra default
388/// arguments in the declarator, which is not a function declaration
389/// or definition and therefore is not permitted to have default
390/// arguments. This routine should be invoked for every declarator
391/// that is not a function declaration or definition.
392void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
393 // C++ [dcl.fct.default]p3
394 // A default argument expression shall be specified only in the
395 // parameter-declaration-clause of a function declaration or in a
396 // template-parameter (14.1). It shall not be specified for a
397 // parameter pack. If it is specified in a
398 // parameter-declaration-clause, it shall not occur within a
399 // declarator or abstract-declarator of a parameter-declaration.
400 bool MightBeFunction = D.isFunctionDeclarationContext();
401 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
402 DeclaratorChunk &chunk = D.getTypeObject(i);
403 if (chunk.Kind == DeclaratorChunk::Function) {
404 if (MightBeFunction) {
405 // This is a function declaration. It can have default arguments, but
406 // keep looking in case its return type is a function type with default
407 // arguments.
408 MightBeFunction = false;
409 continue;
410 }
411 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
412 ++argIdx) {
413 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
414 if (Param->hasUnparsedDefaultArg()) {
415 std::unique_ptr<CachedTokens> Toks =
416 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
417 SourceRange SR;
418 if (Toks->size() > 1)
419 SR = SourceRange((*Toks)[1].getLocation(),
420 Toks->back().getLocation());
421 else
422 SR = UnparsedDefaultArgLocs[Param];
423 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
424 << SR;
425 } else if (Param->getDefaultArg()) {
426 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
427 << Param->getDefaultArg()->getSourceRange();
428 Param->setDefaultArg(nullptr);
429 }
430 }
431 } else if (chunk.Kind != DeclaratorChunk::Paren) {
432 MightBeFunction = false;
433 }
434 }
435}
436
437static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
438 return std::any_of(FD->param_begin(), FD->param_end(), [](ParmVarDecl *P) {
439 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
440 });
441}
442
443/// MergeCXXFunctionDecl - Merge two declarations of the same C++
444/// function, once we already know that they have the same
445/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
446/// error, false otherwise.
447bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
448 Scope *S) {
449 bool Invalid = false;
450
451 // The declaration context corresponding to the scope is the semantic
452 // parent, unless this is a local function declaration, in which case
453 // it is that surrounding function.
454 DeclContext *ScopeDC = New->isLocalExternDecl()
455 ? New->getLexicalDeclContext()
456 : New->getDeclContext();
457
458 // Find the previous declaration for the purpose of default arguments.
459 FunctionDecl *PrevForDefaultArgs = Old;
460 for (/**/; PrevForDefaultArgs;
461 // Don't bother looking back past the latest decl if this is a local
462 // extern declaration; nothing else could work.
463 PrevForDefaultArgs = New->isLocalExternDecl()
464 ? nullptr
465 : PrevForDefaultArgs->getPreviousDecl()) {
466 // Ignore hidden declarations.
467 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
468 continue;
469
470 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
471 !New->isCXXClassMember()) {
472 // Ignore default arguments of old decl if they are not in
473 // the same scope and this is not an out-of-line definition of
474 // a member function.
475 continue;
476 }
477
478 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
479 // If only one of these is a local function declaration, then they are
480 // declared in different scopes, even though isDeclInScope may think
481 // they're in the same scope. (If both are local, the scope check is
482 // sufficient, and if neither is local, then they are in the same scope.)
483 continue;
484 }
485
486 // We found the right previous declaration.
487 break;
488 }
489
490 // C++ [dcl.fct.default]p4:
491 // For non-template functions, default arguments can be added in
492 // later declarations of a function in the same
493 // scope. Declarations in different scopes have completely
494 // distinct sets of default arguments. That is, declarations in
495 // inner scopes do not acquire default arguments from
496 // declarations in outer scopes, and vice versa. In a given
497 // function declaration, all parameters subsequent to a
498 // parameter with a default argument shall have default
499 // arguments supplied in this or previous declarations. A
500 // default argument shall not be redefined by a later
501 // declaration (not even to the same value).
502 //
503 // C++ [dcl.fct.default]p6:
504 // Except for member functions of class templates, the default arguments
505 // in a member function definition that appears outside of the class
506 // definition are added to the set of default arguments provided by the
507 // member function declaration in the class definition.
508 for (unsigned p = 0, NumParams = PrevForDefaultArgs
509 ? PrevForDefaultArgs->getNumParams()
510 : 0;
511 p < NumParams; ++p) {
512 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
513 ParmVarDecl *NewParam = New->getParamDecl(p);
514
515 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
516 bool NewParamHasDfl = NewParam->hasDefaultArg();
517
518 if (OldParamHasDfl && NewParamHasDfl) {
519 unsigned DiagDefaultParamID =
520 diag::err_param_default_argument_redefinition;
521
522 // MSVC accepts that default parameters be redefined for member functions
523 // of template class. The new default parameter's value is ignored.
524 Invalid = true;
525 if (getLangOpts().MicrosoftExt) {
526 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
527 if (MD && MD->getParent()->getDescribedClassTemplate()) {
528 // Merge the old default argument into the new parameter.
529 NewParam->setHasInheritedDefaultArg();
530 if (OldParam->hasUninstantiatedDefaultArg())
531 NewParam->setUninstantiatedDefaultArg(
532 OldParam->getUninstantiatedDefaultArg());
533 else
534 NewParam->setDefaultArg(OldParam->getInit());
535 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
536 Invalid = false;
537 }
538 }
539
540 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
541 // hint here. Alternatively, we could walk the type-source information
542 // for NewParam to find the last source location in the type... but it
543 // isn't worth the effort right now. This is the kind of test case that
544 // is hard to get right:
545 // int f(int);
546 // void g(int (*fp)(int) = f);
547 // void g(int (*fp)(int) = &f);
548 Diag(NewParam->getLocation(), DiagDefaultParamID)
549 << NewParam->getDefaultArgRange();
550
551 // Look for the function declaration where the default argument was
552 // actually written, which may be a declaration prior to Old.
553 for (auto Older = PrevForDefaultArgs;
554 OldParam->hasInheritedDefaultArg(); /**/) {
555 Older = Older->getPreviousDecl();
556 OldParam = Older->getParamDecl(p);
557 }
558
559 Diag(OldParam->getLocation(), diag::note_previous_definition)
560 << OldParam->getDefaultArgRange();
561 } else if (OldParamHasDfl) {
562 // Merge the old default argument into the new parameter unless the new
563 // function is a friend declaration in a template class. In the latter
564 // case the default arguments will be inherited when the friend
565 // declaration will be instantiated.
566 if (New->getFriendObjectKind() == Decl::FOK_None ||
567 !New->getLexicalDeclContext()->isDependentContext()) {
568 // It's important to use getInit() here; getDefaultArg()
569 // strips off any top-level ExprWithCleanups.
570 NewParam->setHasInheritedDefaultArg();
571 if (OldParam->hasUnparsedDefaultArg())
572 NewParam->setUnparsedDefaultArg();
573 else if (OldParam->hasUninstantiatedDefaultArg())
574 NewParam->setUninstantiatedDefaultArg(
575 OldParam->getUninstantiatedDefaultArg());
576 else
577 NewParam->setDefaultArg(OldParam->getInit());
578 }
579 } else if (NewParamHasDfl) {
580 if (New->getDescribedFunctionTemplate()) {
581 // Paragraph 4, quoted above, only applies to non-template functions.
582 Diag(NewParam->getLocation(),
583 diag::err_param_default_argument_template_redecl)
584 << NewParam->getDefaultArgRange();
585 Diag(PrevForDefaultArgs->getLocation(),
586 diag::note_template_prev_declaration)
587 << false;
588 } else if (New->getTemplateSpecializationKind()
589 != TSK_ImplicitInstantiation &&
590 New->getTemplateSpecializationKind() != TSK_Undeclared) {
591 // C++ [temp.expr.spec]p21:
592 // Default function arguments shall not be specified in a declaration
593 // or a definition for one of the following explicit specializations:
594 // - the explicit specialization of a function template;
595 // - the explicit specialization of a member function template;
596 // - the explicit specialization of a member function of a class
597 // template where the class template specialization to which the
598 // member function specialization belongs is implicitly
599 // instantiated.
600 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
601 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
602 << New->getDeclName()
603 << NewParam->getDefaultArgRange();
604 } else if (New->getDeclContext()->isDependentContext()) {
605 // C++ [dcl.fct.default]p6 (DR217):
606 // Default arguments for a member function of a class template shall
607 // be specified on the initial declaration of the member function
608 // within the class template.
609 //
610 // Reading the tea leaves a bit in DR217 and its reference to DR205
611 // leads me to the conclusion that one cannot add default function
612 // arguments for an out-of-line definition of a member function of a
613 // dependent type.
614 int WhichKind = 2;
615 if (CXXRecordDecl *Record
616 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
617 if (Record->getDescribedClassTemplate())
618 WhichKind = 0;
619 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
620 WhichKind = 1;
621 else
622 WhichKind = 2;
623 }
624
625 Diag(NewParam->getLocation(),
626 diag::err_param_default_argument_member_template_redecl)
627 << WhichKind
628 << NewParam->getDefaultArgRange();
629 }
630 }
631 }
632
633 // DR1344: If a default argument is added outside a class definition and that
634 // default argument makes the function a special member function, the program
635 // is ill-formed. This can only happen for constructors.
636 if (isa<CXXConstructorDecl>(New) &&
637 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
638 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
639 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
640 if (NewSM != OldSM) {
641 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
642 assert(NewParam->hasDefaultArg())(static_cast<void> (0));
643 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
644 << NewParam->getDefaultArgRange() << NewSM;
645 Diag(Old->getLocation(), diag::note_previous_declaration);
646 }
647 }
648
649 const FunctionDecl *Def;
650 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
651 // template has a constexpr specifier then all its declarations shall
652 // contain the constexpr specifier.
653 if (New->getConstexprKind() != Old->getConstexprKind()) {
654 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
655 << New << static_cast<int>(New->getConstexprKind())
656 << static_cast<int>(Old->getConstexprKind());
657 Diag(Old->getLocation(), diag::note_previous_declaration);
658 Invalid = true;
659 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
660 Old->isDefined(Def) &&
661 // If a friend function is inlined but does not have 'inline'
662 // specifier, it is a definition. Do not report attribute conflict
663 // in this case, redefinition will be diagnosed later.
664 (New->isInlineSpecified() ||
665 New->getFriendObjectKind() == Decl::FOK_None)) {
666 // C++11 [dcl.fcn.spec]p4:
667 // If the definition of a function appears in a translation unit before its
668 // first declaration as inline, the program is ill-formed.
669 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
670 Diag(Def->getLocation(), diag::note_previous_definition);
671 Invalid = true;
672 }
673
674 // C++17 [temp.deduct.guide]p3:
675 // Two deduction guide declarations in the same translation unit
676 // for the same class template shall not have equivalent
677 // parameter-declaration-clauses.
678 if (isa<CXXDeductionGuideDecl>(New) &&
679 !New->isFunctionTemplateSpecialization() && isVisible(Old)) {
680 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
681 Diag(Old->getLocation(), diag::note_previous_declaration);
682 }
683
684 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
685 // argument expression, that declaration shall be a definition and shall be
686 // the only declaration of the function or function template in the
687 // translation unit.
688 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
689 functionDeclHasDefaultArgument(Old)) {
690 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
691 Diag(Old->getLocation(), diag::note_previous_declaration);
692 Invalid = true;
693 }
694
695 // C++11 [temp.friend]p4 (DR329):
696 // When a function is defined in a friend function declaration in a class
697 // template, the function is instantiated when the function is odr-used.
698 // The same restrictions on multiple declarations and definitions that
699 // apply to non-template function declarations and definitions also apply
700 // to these implicit definitions.
701 const FunctionDecl *OldDefinition = nullptr;
702 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
703 Old->isDefined(OldDefinition, true))
704 CheckForFunctionRedefinition(New, OldDefinition);
705
706 return Invalid;
707}
708
709NamedDecl *
710Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
711 MultiTemplateParamsArg TemplateParamLists) {
712 assert(D.isDecompositionDeclarator())(static_cast<void> (0));
713 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
714
715 // The syntax only allows a decomposition declarator as a simple-declaration,
716 // a for-range-declaration, or a condition in Clang, but we parse it in more
717 // cases than that.
718 if (!D.mayHaveDecompositionDeclarator()) {
719 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
720 << Decomp.getSourceRange();
721 return nullptr;
722 }
723
724 if (!TemplateParamLists.empty()) {
725 // FIXME: There's no rule against this, but there are also no rules that
726 // would actually make it usable, so we reject it for now.
727 Diag(TemplateParamLists.front()->getTemplateLoc(),
728 diag::err_decomp_decl_template);
729 return nullptr;
730 }
731
732 Diag(Decomp.getLSquareLoc(),
733 !getLangOpts().CPlusPlus17
734 ? diag::ext_decomp_decl
735 : D.getContext() == DeclaratorContext::Condition
736 ? diag::ext_decomp_decl_cond
737 : diag::warn_cxx14_compat_decomp_decl)
738 << Decomp.getSourceRange();
739
740 // The semantic context is always just the current context.
741 DeclContext *const DC = CurContext;
742
743 // C++17 [dcl.dcl]/8:
744 // The decl-specifier-seq shall contain only the type-specifier auto
745 // and cv-qualifiers.
746 // C++2a [dcl.dcl]/8:
747 // If decl-specifier-seq contains any decl-specifier other than static,
748 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
749 auto &DS = D.getDeclSpec();
750 {
751 SmallVector<StringRef, 8> BadSpecifiers;
752 SmallVector<SourceLocation, 8> BadSpecifierLocs;
753 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
754 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
755 if (auto SCS = DS.getStorageClassSpec()) {
756 if (SCS == DeclSpec::SCS_static) {
757 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
758 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
759 } else {
760 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
761 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
762 }
763 }
764 if (auto TSCS = DS.getThreadStorageClassSpec()) {
765 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
766 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
767 }
768 if (DS.hasConstexprSpecifier()) {
769 BadSpecifiers.push_back(
770 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
771 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
772 }
773 if (DS.isInlineSpecified()) {
774 BadSpecifiers.push_back("inline");
775 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
776 }
777 if (!BadSpecifiers.empty()) {
778 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
779 Err << (int)BadSpecifiers.size()
780 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
781 // Don't add FixItHints to remove the specifiers; we do still respect
782 // them when building the underlying variable.
783 for (auto Loc : BadSpecifierLocs)
784 Err << SourceRange(Loc, Loc);
785 } else if (!CPlusPlus20Specifiers.empty()) {
786 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
787 getLangOpts().CPlusPlus20
788 ? diag::warn_cxx17_compat_decomp_decl_spec
789 : diag::ext_decomp_decl_spec);
790 Warn << (int)CPlusPlus20Specifiers.size()
791 << llvm::join(CPlusPlus20Specifiers.begin(),
792 CPlusPlus20Specifiers.end(), " ");
793 for (auto Loc : CPlusPlus20SpecifierLocs)
794 Warn << SourceRange(Loc, Loc);
795 }
796 // We can't recover from it being declared as a typedef.
797 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
798 return nullptr;
799 }
800
801 // C++2a [dcl.struct.bind]p1:
802 // A cv that includes volatile is deprecated
803 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
804 getLangOpts().CPlusPlus20)
805 Diag(DS.getVolatileSpecLoc(),
806 diag::warn_deprecated_volatile_structured_binding);
807
808 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
809 QualType R = TInfo->getType();
810
811 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
812 UPPC_DeclarationType))
813 D.setInvalidType();
814
815 // The syntax only allows a single ref-qualifier prior to the decomposition
816 // declarator. No other declarator chunks are permitted. Also check the type
817 // specifier here.
818 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
819 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
820 (D.getNumTypeObjects() == 1 &&
821 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
822 Diag(Decomp.getLSquareLoc(),
823 (D.hasGroupingParens() ||
824 (D.getNumTypeObjects() &&
825 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
826 ? diag::err_decomp_decl_parens
827 : diag::err_decomp_decl_type)
828 << R;
829
830 // In most cases, there's no actual problem with an explicitly-specified
831 // type, but a function type won't work here, and ActOnVariableDeclarator
832 // shouldn't be called for such a type.
833 if (R->isFunctionType())
834 D.setInvalidType();
835 }
836
837 // Build the BindingDecls.
838 SmallVector<BindingDecl*, 8> Bindings;
839
840 // Build the BindingDecls.
841 for (auto &B : D.getDecompositionDeclarator().bindings()) {
842 // Check for name conflicts.
843 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
844 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
845 ForVisibleRedeclaration);
846 LookupName(Previous, S,
847 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
848
849 // It's not permitted to shadow a template parameter name.
850 if (Previous.isSingleResult() &&
851 Previous.getFoundDecl()->isTemplateParameter()) {
852 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
853 Previous.getFoundDecl());
854 Previous.clear();
855 }
856
857 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
858
859 // Find the shadowed declaration before filtering for scope.
860 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
861 ? getShadowedDeclaration(BD, Previous)
862 : nullptr;
863
864 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
865 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
866 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
867 /*AllowInlineNamespace*/false);
868
869 if (!Previous.empty()) {
870 auto *Old = Previous.getRepresentativeDecl();
871 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
872 Diag(Old->getLocation(), diag::note_previous_definition);
873 } else if (ShadowedDecl && !D.isRedeclaration()) {
874 CheckShadow(BD, ShadowedDecl, Previous);
875 }
876 PushOnScopeChains(BD, S, true);
877 Bindings.push_back(BD);
878 ParsingInitForAutoVars.insert(BD);
879 }
880
881 // There are no prior lookup results for the variable itself, because it
882 // is unnamed.
883 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
884 Decomp.getLSquareLoc());
885 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
886 ForVisibleRedeclaration);
887
888 // Build the variable that holds the non-decomposed object.
889 bool AddToScope = true;
890 NamedDecl *New =
891 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
892 MultiTemplateParamsArg(), AddToScope, Bindings);
893 if (AddToScope) {
894 S->AddDecl(New);
895 CurContext->addHiddenDecl(New);
896 }
897
898 if (isInOpenMPDeclareTargetContext())
899 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
900
901 return New;
902}
903
904static bool checkSimpleDecomposition(
905 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
906 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
907 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
908 if ((int64_t)Bindings.size() != NumElems) {
909 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
910 << DecompType << (unsigned)Bindings.size()
911 << (unsigned)NumElems.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
912 << toString(NumElems, 10) << (NumElems < Bindings.size());
913 return true;
914 }
915
916 unsigned I = 0;
917 for (auto *B : Bindings) {
918 SourceLocation Loc = B->getLocation();
919 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
920 if (E.isInvalid())
921 return true;
922 E = GetInit(Loc, E.get(), I++);
923 if (E.isInvalid())
924 return true;
925 B->setBinding(ElemType, E.get());
926 }
927
928 return false;
929}
930
931static bool checkArrayLikeDecomposition(Sema &S,
932 ArrayRef<BindingDecl *> Bindings,
933 ValueDecl *Src, QualType DecompType,
934 const llvm::APSInt &NumElems,
935 QualType ElemType) {
936 return checkSimpleDecomposition(
937 S, Bindings, Src, DecompType, NumElems, ElemType,
938 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
939 ExprResult E = S.ActOnIntegerConstant(Loc, I);
940 if (E.isInvalid())
941 return ExprError();
942 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
943 });
944}
945
946static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
947 ValueDecl *Src, QualType DecompType,
948 const ConstantArrayType *CAT) {
949 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
950 llvm::APSInt(CAT->getSize()),
951 CAT->getElementType());
952}
953
954static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
955 ValueDecl *Src, QualType DecompType,
956 const VectorType *VT) {
957 return checkArrayLikeDecomposition(
958 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
959 S.Context.getQualifiedType(VT->getElementType(),
960 DecompType.getQualifiers()));
961}
962
963static bool checkComplexDecomposition(Sema &S,
964 ArrayRef<BindingDecl *> Bindings,
965 ValueDecl *Src, QualType DecompType,
966 const ComplexType *CT) {
967 return checkSimpleDecomposition(
968 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
969 S.Context.getQualifiedType(CT->getElementType(),
970 DecompType.getQualifiers()),
971 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
972 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
973 });
974}
975
976static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
977 TemplateArgumentListInfo &Args,
978 const TemplateParameterList *Params) {
979 SmallString<128> SS;
980 llvm::raw_svector_ostream OS(SS);
981 bool First = true;
982 unsigned I = 0;
983 for (auto &Arg : Args.arguments()) {
984 if (!First)
985 OS << ", ";
986 Arg.getArgument().print(
987 PrintingPolicy, OS,
988 TemplateParameterList::shouldIncludeTypeForArgument(Params, I));
989 First = false;
990 I++;
991 }
992 return std::string(OS.str());
993}
994
995static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
996 SourceLocation Loc, StringRef Trait,
997 TemplateArgumentListInfo &Args,
998 unsigned DiagID) {
999 auto DiagnoseMissing = [&] {
1000 if (DiagID)
1001 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1002 Args, /*Params*/ nullptr);
1003 return true;
1004 };
1005
1006 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1007 NamespaceDecl *Std = S.getStdNamespace();
1008 if (!Std)
1009 return DiagnoseMissing();
1010
1011 // Look up the trait itself, within namespace std. We can diagnose various
1012 // problems with this lookup even if we've been asked to not diagnose a
1013 // missing specialization, because this can only fail if the user has been
1014 // declaring their own names in namespace std or we don't support the
1015 // standard library implementation in use.
1016 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
1017 Loc, Sema::LookupOrdinaryName);
1018 if (!S.LookupQualifiedName(Result, Std))
1019 return DiagnoseMissing();
1020 if (Result.isAmbiguous())
1021 return true;
1022
1023 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1024 if (!TraitTD) {
1025 Result.suppressDiagnostics();
1026 NamedDecl *Found = *Result.begin();
1027 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1028 S.Diag(Found->getLocation(), diag::note_declared_at);
1029 return true;
1030 }
1031
1032 // Build the template-id.
1033 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1034 if (TraitTy.isNull())
1035 return true;
1036 if (!S.isCompleteType(Loc, TraitTy)) {
1037 if (DiagID)
1038 S.RequireCompleteType(
1039 Loc, TraitTy, DiagID,
1040 printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1041 TraitTD->getTemplateParameters()));
1042 return true;
1043 }
1044
1045 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1046 assert(RD && "specialization of class template is not a class?")(static_cast<void> (0));
1047
1048 // Look up the member of the trait type.
1049 S.LookupQualifiedName(TraitMemberLookup, RD);
1050 return TraitMemberLookup.isAmbiguous();
1051}
1052
1053static TemplateArgumentLoc
1054getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1055 uint64_t I) {
1056 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
1057 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1058}
1059
1060static TemplateArgumentLoc
1061getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1062 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1063}
1064
1065namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1066
1067static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1068 llvm::APSInt &Size) {
1069 EnterExpressionEvaluationContext ContextRAII(
1070 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1071
1072 DeclarationName Value = S.PP.getIdentifierInfo("value");
1073 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1074
1075 // Form template argument list for tuple_size<T>.
1076 TemplateArgumentListInfo Args(Loc, Loc);
1077 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1078
1079 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1080 // it's not tuple-like.
1081 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1082 R.empty())
1083 return IsTupleLike::NotTupleLike;
1084
1085 // If we get this far, we've committed to the tuple interpretation, but
1086 // we can still fail if there actually isn't a usable ::value.
1087
1088 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1089 LookupResult &R;
1090 TemplateArgumentListInfo &Args;
1091 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1092 : R(R), Args(Args) {}
1093 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1094 SourceLocation Loc) override {
1095 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1096 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1097 /*Params*/ nullptr);
1098 }
1099 } Diagnoser(R, Args);
1100
1101 ExprResult E =
1102 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1103 if (E.isInvalid())
1104 return IsTupleLike::Error;
1105
1106 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1107 if (E.isInvalid())
1108 return IsTupleLike::Error;
1109
1110 return IsTupleLike::TupleLike;
1111}
1112
1113/// \return std::tuple_element<I, T>::type.
1114static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1115 unsigned I, QualType T) {
1116 // Form template argument list for tuple_element<I, T>.
1117 TemplateArgumentListInfo Args(Loc, Loc);
1118 Args.addArgument(
1119 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1120 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1121
1122 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1123 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1124 if (lookupStdTypeTraitMember(
1125 S, R, Loc, "tuple_element", Args,
1126 diag::err_decomp_decl_std_tuple_element_not_specialized))
1127 return QualType();
1128
1129 auto *TD = R.getAsSingle<TypeDecl>();
1130 if (!TD) {
1131 R.suppressDiagnostics();
1132 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1133 << printTemplateArgs(S.Context.getPrintingPolicy(), Args,
1134 /*Params*/ nullptr);
1135 if (!R.empty())
1136 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1137 return QualType();
1138 }
1139
1140 return S.Context.getTypeDeclType(TD);
1141}
1142
1143namespace {
1144struct InitializingBinding {
1145 Sema &S;
1146 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1147 Sema::CodeSynthesisContext Ctx;
1148 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1149 Ctx.PointOfInstantiation = BD->getLocation();
1150 Ctx.Entity = BD;
1151 S.pushCodeSynthesisContext(Ctx);
1152 }
1153 ~InitializingBinding() {
1154 S.popCodeSynthesisContext();
1155 }
1156};
1157}
1158
1159static bool checkTupleLikeDecomposition(Sema &S,
1160 ArrayRef<BindingDecl *> Bindings,
1161 VarDecl *Src, QualType DecompType,
1162 const llvm::APSInt &TupleSize) {
1163 if ((int64_t)Bindings.size() != TupleSize) {
1164 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1165 << DecompType << (unsigned)Bindings.size()
1166 << (unsigned)TupleSize.getLimitedValue(UINT_MAX(2147483647 *2U +1U))
1167 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1168 return true;
1169 }
1170
1171 if (Bindings.empty())
1172 return false;
1173
1174 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1175
1176 // [dcl.decomp]p3:
1177 // The unqualified-id get is looked up in the scope of E by class member
1178 // access lookup ...
1179 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1180 bool UseMemberGet = false;
1181 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1182 if (auto *RD = DecompType->getAsCXXRecordDecl())
1183 S.LookupQualifiedName(MemberGet, RD);
1184 if (MemberGet.isAmbiguous())
1185 return true;
1186 // ... and if that finds at least one declaration that is a function
1187 // template whose first template parameter is a non-type parameter ...
1188 for (NamedDecl *D : MemberGet) {
1189 if (FunctionTemplateDecl *FTD =
1190 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1191 TemplateParameterList *TPL = FTD->getTemplateParameters();
1192 if (TPL->size() != 0 &&
1193 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1194 // ... the initializer is e.get<i>().
1195 UseMemberGet = true;
1196 break;
1197 }
1198 }
1199 }
1200 }
1201
1202 unsigned I = 0;
1203 for (auto *B : Bindings) {
1204 InitializingBinding InitContext(S, B);
1205 SourceLocation Loc = B->getLocation();
1206
1207 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1208 if (E.isInvalid())
1209 return true;
1210
1211 // e is an lvalue if the type of the entity is an lvalue reference and
1212 // an xvalue otherwise
1213 if (!Src->getType()->isLValueReferenceType())
1214 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1215 E.get(), nullptr, VK_XValue,
1216 FPOptionsOverride());
1217
1218 TemplateArgumentListInfo Args(Loc, Loc);
1219 Args.addArgument(
1220 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1221
1222 if (UseMemberGet) {
1223 // if [lookup of member get] finds at least one declaration, the
1224 // initializer is e.get<i-1>().
1225 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1226 CXXScopeSpec(), SourceLocation(), nullptr,
1227 MemberGet, &Args, nullptr);
1228 if (E.isInvalid())
1229 return true;
1230
1231 E = S.BuildCallExpr(nullptr, E.get(), Loc, None, Loc);
1232 } else {
1233 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1234 // in the associated namespaces.
1235 Expr *Get = UnresolvedLookupExpr::Create(
1236 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1237 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1238 UnresolvedSetIterator(), UnresolvedSetIterator());
1239
1240 Expr *Arg = E.get();
1241 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1242 }
1243 if (E.isInvalid())
1244 return true;
1245 Expr *Init = E.get();
1246
1247 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1248 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1249 if (T.isNull())
1250 return true;
1251
1252 // each vi is a variable of type "reference to T" initialized with the
1253 // initializer, where the reference is an lvalue reference if the
1254 // initializer is an lvalue and an rvalue reference otherwise
1255 QualType RefType =
1256 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1257 if (RefType.isNull())
1258 return true;
1259 auto *RefVD = VarDecl::Create(
1260 S.Context, Src->getDeclContext(), Loc, Loc,
1261 B->getDeclName().getAsIdentifierInfo(), RefType,
1262 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1263 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1264 RefVD->setTSCSpec(Src->getTSCSpec());
1265 RefVD->setImplicit();
1266 if (Src->isInlineSpecified())
1267 RefVD->setInlineSpecified();
1268 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1269
1270 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1271 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1272 InitializationSequence Seq(S, Entity, Kind, Init);
1273 E = Seq.Perform(S, Entity, Kind, Init);
1274 if (E.isInvalid())
1275 return true;
1276 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1277 if (E.isInvalid())
1278 return true;
1279 RefVD->setInit(E.get());
1280 S.CheckCompleteVariableDeclaration(RefVD);
1281
1282 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1283 DeclarationNameInfo(B->getDeclName(), Loc),
1284 RefVD);
1285 if (E.isInvalid())
1286 return true;
1287
1288 B->setBinding(T, E.get());
1289 I++;
1290 }
1291
1292 return false;
1293}
1294
1295/// Find the base class to decompose in a built-in decomposition of a class type.
1296/// This base class search is, unfortunately, not quite like any other that we
1297/// perform anywhere else in C++.
1298static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1299 const CXXRecordDecl *RD,
1300 CXXCastPath &BasePath) {
1301 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1302 CXXBasePath &Path) {
1303 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1304 };
1305
1306 const CXXRecordDecl *ClassWithFields = nullptr;
1307 AccessSpecifier AS = AS_public;
1308 if (RD->hasDirectFields())
1309 // [dcl.decomp]p4:
1310 // Otherwise, all of E's non-static data members shall be public direct
1311 // members of E ...
1312 ClassWithFields = RD;
1313 else {
1314 // ... or of ...
1315 CXXBasePaths Paths;
1316 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1317 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1318 // If no classes have fields, just decompose RD itself. (This will work
1319 // if and only if zero bindings were provided.)
1320 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1321 }
1322
1323 CXXBasePath *BestPath = nullptr;
1324 for (auto &P : Paths) {
1325 if (!BestPath)
1326 BestPath = &P;
1327 else if (!S.Context.hasSameType(P.back().Base->getType(),
1328 BestPath->back().Base->getType())) {
1329 // ... the same ...
1330 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1331 << false << RD << BestPath->back().Base->getType()
1332 << P.back().Base->getType();
1333 return DeclAccessPair();
1334 } else if (P.Access < BestPath->Access) {
1335 BestPath = &P;
1336 }
1337 }
1338
1339 // ... unambiguous ...
1340 QualType BaseType = BestPath->back().Base->getType();
1341 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1342 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1343 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1344 return DeclAccessPair();
1345 }
1346
1347 // ... [accessible, implied by other rules] base class of E.
1348 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1349 *BestPath, diag::err_decomp_decl_inaccessible_base);
1350 AS = BestPath->Access;
1351
1352 ClassWithFields = BaseType->getAsCXXRecordDecl();
1353 S.BuildBasePathArray(Paths, BasePath);
1354 }
1355
1356 // The above search did not check whether the selected class itself has base
1357 // classes with fields, so check that now.
1358 CXXBasePaths Paths;
1359 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1360 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1361 << (ClassWithFields == RD) << RD << ClassWithFields
1362 << Paths.front().back().Base->getType();
1363 return DeclAccessPair();
1364 }
1365
1366 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1367}
1368
1369static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1370 ValueDecl *Src, QualType DecompType,
1371 const CXXRecordDecl *OrigRD) {
1372 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1373 diag::err_incomplete_type))
1374 return true;
1375
1376 CXXCastPath BasePath;
1377 DeclAccessPair BasePair =
1378 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1379 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1380 if (!RD)
1381 return true;
1382 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1383 DecompType.getQualifiers());
1384
1385 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1386 unsigned NumFields =
1387 std::count_if(RD->field_begin(), RD->field_end(),
1388 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1389 assert(Bindings.size() != NumFields)(static_cast<void> (0));
1390 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1391 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1392 << (NumFields < Bindings.size());
1393 return true;
1394 };
1395
1396 // all of E's non-static data members shall be [...] well-formed
1397 // when named as e.name in the context of the structured binding,
1398 // E shall not have an anonymous union member, ...
1399 unsigned I = 0;
1400 for (auto *FD : RD->fields()) {
1401 if (FD->isUnnamedBitfield())
1402 continue;
1403
1404 // All the non-static data members are required to be nameable, so they
1405 // must all have names.
1406 if (!FD->getDeclName()) {
1407 if (RD->isLambda()) {
1408 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1409 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1410 return true;
1411 }
1412
1413 if (FD->isAnonymousStructOrUnion()) {
1414 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1415 << DecompType << FD->getType()->isUnionType();
1416 S.Diag(FD->getLocation(), diag::note_declared_at);
1417 return true;
1418 }
1419
1420 // FIXME: Are there any other ways we could have an anonymous member?
1421 }
1422
1423 // We have a real field to bind.
1424 if (I >= Bindings.size())
1425 return DiagnoseBadNumberOfBindings();
1426 auto *B = Bindings[I++];
1427 SourceLocation Loc = B->getLocation();
1428
1429 // The field must be accessible in the context of the structured binding.
1430 // We already checked that the base class is accessible.
1431 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1432 // const_cast here.
1433 S.CheckStructuredBindingMemberAccess(
1434 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1435 DeclAccessPair::make(FD, CXXRecordDecl::MergeAccess(
1436 BasePair.getAccess(), FD->getAccess())));
1437
1438 // Initialize the binding to Src.FD.
1439 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1440 if (E.isInvalid())
1441 return true;
1442 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1443 VK_LValue, &BasePath);
1444 if (E.isInvalid())
1445 return true;
1446 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1447 CXXScopeSpec(), FD,
1448 DeclAccessPair::make(FD, FD->getAccess()),
1449 DeclarationNameInfo(FD->getDeclName(), Loc));
1450 if (E.isInvalid())
1451 return true;
1452
1453 // If the type of the member is T, the referenced type is cv T, where cv is
1454 // the cv-qualification of the decomposition expression.
1455 //
1456 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1457 // 'const' to the type of the field.
1458 Qualifiers Q = DecompType.getQualifiers();
1459 if (FD->isMutable())
1460 Q.removeConst();
1461 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1462 }
1463
1464 if (I != Bindings.size())
1465 return DiagnoseBadNumberOfBindings();
1466
1467 return false;
1468}
1469
1470void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1471 QualType DecompType = DD->getType();
1472
1473 // If the type of the decomposition is dependent, then so is the type of
1474 // each binding.
1475 if (DecompType->isDependentType()) {
1476 for (auto *B : DD->bindings())
1477 B->setType(Context.DependentTy);
1478 return;
1479 }
1480
1481 DecompType = DecompType.getNonReferenceType();
1482 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1483
1484 // C++1z [dcl.decomp]/2:
1485 // If E is an array type [...]
1486 // As an extension, we also support decomposition of built-in complex and
1487 // vector types.
1488 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1489 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1490 DD->setInvalidDecl();
1491 return;
1492 }
1493 if (auto *VT = DecompType->getAs<VectorType>()) {
1494 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1495 DD->setInvalidDecl();
1496 return;
1497 }
1498 if (auto *CT = DecompType->getAs<ComplexType>()) {
1499 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1500 DD->setInvalidDecl();
1501 return;
1502 }
1503
1504 // C++1z [dcl.decomp]/3:
1505 // if the expression std::tuple_size<E>::value is a well-formed integral
1506 // constant expression, [...]
1507 llvm::APSInt TupleSize(32);
1508 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1509 case IsTupleLike::Error:
1510 DD->setInvalidDecl();
1511 return;
1512
1513 case IsTupleLike::TupleLike:
1514 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1515 DD->setInvalidDecl();
1516 return;
1517
1518 case IsTupleLike::NotTupleLike:
1519 break;
1520 }
1521
1522 // C++1z [dcl.dcl]/8:
1523 // [E shall be of array or non-union class type]
1524 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1525 if (!RD || RD->isUnion()) {
1526 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1527 << DD << !RD << DecompType;
1528 DD->setInvalidDecl();
1529 return;
1530 }
1531
1532 // C++1z [dcl.decomp]/4:
1533 // all of E's non-static data members shall be [...] direct members of
1534 // E or of the same unambiguous public base class of E, ...
1535 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1536 DD->setInvalidDecl();
1537}
1538
1539/// Merge the exception specifications of two variable declarations.
1540///
1541/// This is called when there's a redeclaration of a VarDecl. The function
1542/// checks if the redeclaration might have an exception specification and
1543/// validates compatibility and merges the specs if necessary.
1544void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1545 // Shortcut if exceptions are disabled.
1546 if (!getLangOpts().CXXExceptions)
1547 return;
1548
1549 assert(Context.hasSameType(New->getType(), Old->getType()) &&(static_cast<void> (0))
1550 "Should only be called if types are otherwise the same.")(static_cast<void> (0));
1551
1552 QualType NewType = New->getType();
1553 QualType OldType = Old->getType();
1554
1555 // We're only interested in pointers and references to functions, as well
1556 // as pointers to member functions.
1557 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1558 NewType = R->getPointeeType();
1559 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1560 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1561 NewType = P->getPointeeType();
1562 OldType = OldType->castAs<PointerType>()->getPointeeType();
1563 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1564 NewType = M->getPointeeType();
1565 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1566 }
1567
1568 if (!NewType->isFunctionProtoType())
1569 return;
1570
1571 // There's lots of special cases for functions. For function pointers, system
1572 // libraries are hopefully not as broken so that we don't need these
1573 // workarounds.
1574 if (CheckEquivalentExceptionSpec(
1575 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1576 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1577 New->setInvalidDecl();
1578 }
1579}
1580
1581/// CheckCXXDefaultArguments - Verify that the default arguments for a
1582/// function declaration are well-formed according to C++
1583/// [dcl.fct.default].
1584void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1585 unsigned NumParams = FD->getNumParams();
1586 unsigned ParamIdx = 0;
1587
1588 // This checking doesn't make sense for explicit specializations; their
1589 // default arguments are determined by the declaration we're specializing,
1590 // not by FD.
1591 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1592 return;
1593 if (auto *FTD = FD->getDescribedFunctionTemplate())
1594 if (FTD->isMemberSpecialization())
1595 return;
1596
1597 // Find first parameter with a default argument
1598 for (; ParamIdx < NumParams; ++ParamIdx) {
1599 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1600 if (Param->hasDefaultArg())
1601 break;
1602 }
1603
1604 // C++20 [dcl.fct.default]p4:
1605 // In a given function declaration, each parameter subsequent to a parameter
1606 // with a default argument shall have a default argument supplied in this or
1607 // a previous declaration, unless the parameter was expanded from a
1608 // parameter pack, or shall be a function parameter pack.
1609 for (; ParamIdx < NumParams; ++ParamIdx) {
1610 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1611 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1612 !(CurrentInstantiationScope &&
1613 CurrentInstantiationScope->isLocalPackExpansion(Param))) {
1614 if (Param->isInvalidDecl())
1615 /* We already complained about this parameter. */;
1616 else if (Param->getIdentifier())
1617 Diag(Param->getLocation(),
1618 diag::err_param_default_argument_missing_name)
1619 << Param->getIdentifier();
1620 else
1621 Diag(Param->getLocation(),
1622 diag::err_param_default_argument_missing);
1623 }
1624 }
1625}
1626
1627/// Check that the given type is a literal type. Issue a diagnostic if not,
1628/// if Kind is Diagnose.
1629/// \return \c true if a problem has been found (and optionally diagnosed).
1630template <typename... Ts>
1631static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1632 SourceLocation Loc, QualType T, unsigned DiagID,
1633 Ts &&...DiagArgs) {
1634 if (T->isDependentType())
1635 return false;
1636
1637 switch (Kind) {
1638 case Sema::CheckConstexprKind::Diagnose:
1639 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1640 std::forward<Ts>(DiagArgs)...);
1641
1642 case Sema::CheckConstexprKind::CheckValid:
1643 return !T->isLiteralType(SemaRef.Context);
1644 }
1645
1646 llvm_unreachable("unknown CheckConstexprKind")__builtin_unreachable();
1647}
1648
1649/// Determine whether a destructor cannot be constexpr due to
1650static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1651 const CXXDestructorDecl *DD,
1652 Sema::CheckConstexprKind Kind) {
1653 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1654 const CXXRecordDecl *RD =
1655 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1656 if (!RD || RD->hasConstexprDestructor())
1657 return true;
1658
1659 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1660 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1661 << static_cast<int>(DD->getConstexprKind()) << !FD
1662 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1663 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1664 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1665 }
1666 return false;
1667 };
1668
1669 const CXXRecordDecl *RD = DD->getParent();
1670 for (const CXXBaseSpecifier &B : RD->bases())
1671 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1672 return false;
1673 for (const FieldDecl *FD : RD->fields())
1674 if (!Check(FD->getLocation(), FD->getType(), FD))
1675 return false;
1676 return true;
1677}
1678
1679/// Check whether a function's parameter types are all literal types. If so,
1680/// return true. If not, produce a suitable diagnostic and return false.
1681static bool CheckConstexprParameterTypes(Sema &SemaRef,
1682 const FunctionDecl *FD,
1683 Sema::CheckConstexprKind Kind) {
1684 unsigned ArgIndex = 0;
1685 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1686 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1687 e = FT->param_type_end();
1688 i != e; ++i, ++ArgIndex) {
1689 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1690 SourceLocation ParamLoc = PD->getLocation();
1691 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1692 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1693 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1694 FD->isConsteval()))
1695 return false;
1696 }
1697 return true;
1698}
1699
1700/// Check whether a function's return type is a literal type. If so, return
1701/// true. If not, produce a suitable diagnostic and return false.
1702static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1703 Sema::CheckConstexprKind Kind) {
1704 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1705 diag::err_constexpr_non_literal_return,
1706 FD->isConsteval()))
1707 return false;
1708 return true;
1709}
1710
1711/// Get diagnostic %select index for tag kind for
1712/// record diagnostic message.
1713/// WARNING: Indexes apply to particular diagnostics only!
1714///
1715/// \returns diagnostic %select index.
1716static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1717 switch (Tag) {
1718 case TTK_Struct: return 0;
1719 case TTK_Interface: return 1;
1720 case TTK_Class: return 2;
1721 default: llvm_unreachable("Invalid tag kind for record diagnostic!")__builtin_unreachable();
1722 }
1723}
1724
1725static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1726 Stmt *Body,
1727 Sema::CheckConstexprKind Kind);
1728
1729// Check whether a function declaration satisfies the requirements of a
1730// constexpr function definition or a constexpr constructor definition. If so,
1731// return true. If not, produce appropriate diagnostics (unless asked not to by
1732// Kind) and return false.
1733//
1734// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1735bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1736 CheckConstexprKind Kind) {
1737 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1738 if (MD && MD->isInstance()) {
1739 // C++11 [dcl.constexpr]p4:
1740 // The definition of a constexpr constructor shall satisfy the following
1741 // constraints:
1742 // - the class shall not have any virtual base classes;
1743 //
1744 // FIXME: This only applies to constructors and destructors, not arbitrary
1745 // member functions.
1746 const CXXRecordDecl *RD = MD->getParent();
1747 if (RD->getNumVBases()) {
1748 if (Kind == CheckConstexprKind::CheckValid)
1749 return false;
1750
1751 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1752 << isa<CXXConstructorDecl>(NewFD)
1753 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1754 for (const auto &I : RD->vbases())
1755 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1756 << I.getSourceRange();
1757 return false;
1758 }
1759 }
1760
1761 if (!isa<CXXConstructorDecl>(NewFD)) {
1762 // C++11 [dcl.constexpr]p3:
1763 // The definition of a constexpr function shall satisfy the following
1764 // constraints:
1765 // - it shall not be virtual; (removed in C++20)
1766 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1767 if (Method && Method->isVirtual()) {
1768 if (getLangOpts().CPlusPlus20) {
1769 if (Kind == CheckConstexprKind::Diagnose)
1770 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1771 } else {
1772 if (Kind == CheckConstexprKind::CheckValid)
1773 return false;
1774
1775 Method = Method->getCanonicalDecl();
1776 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1777
1778 // If it's not obvious why this function is virtual, find an overridden
1779 // function which uses the 'virtual' keyword.
1780 const CXXMethodDecl *WrittenVirtual = Method;
1781 while (!WrittenVirtual->isVirtualAsWritten())
1782 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1783 if (WrittenVirtual != Method)
1784 Diag(WrittenVirtual->getLocation(),
1785 diag::note_overridden_virtual_function);
1786 return false;
1787 }
1788 }
1789
1790 // - its return type shall be a literal type;
1791 if (!CheckConstexprReturnType(*this, NewFD, Kind))
1792 return false;
1793 }
1794
1795 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1796 // A destructor can be constexpr only if the defaulted destructor could be;
1797 // we don't need to check the members and bases if we already know they all
1798 // have constexpr destructors.
1799 if (!Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1800 if (Kind == CheckConstexprKind::CheckValid)
1801 return false;
1802 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1803 return false;
1804 }
1805 }
1806
1807 // - each of its parameter types shall be a literal type;
1808 if (!CheckConstexprParameterTypes(*this, NewFD, Kind))
1809 return false;
1810
1811 Stmt *Body = NewFD->getBody();
1812 assert(Body &&(static_cast<void> (0))
1813 "CheckConstexprFunctionDefinition called on function with no body")(static_cast<void> (0));
1814 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1815}
1816
1817/// Check the given declaration statement is legal within a constexpr function
1818/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1819///
1820/// \return true if the body is OK (maybe only as an extension), false if we
1821/// have diagnosed a problem.
1822static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1823 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1824 Sema::CheckConstexprKind Kind) {
1825 // C++11 [dcl.constexpr]p3 and p4:
1826 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1827 // contain only
1828 for (const auto *DclIt : DS->decls()) {
1829 switch (DclIt->getKind()) {
1830 case Decl::StaticAssert:
1831 case Decl::Using:
1832 case Decl::UsingShadow:
1833 case Decl::UsingDirective:
1834 case Decl::UnresolvedUsingTypename:
1835 case Decl::UnresolvedUsingValue:
1836 case Decl::UsingEnum:
1837 // - static_assert-declarations
1838 // - using-declarations,
1839 // - using-directives,
1840 // - using-enum-declaration
1841 continue;
1842
1843 case Decl::Typedef:
1844 case Decl::TypeAlias: {
1845 // - typedef declarations and alias-declarations that do not define
1846 // classes or enumerations,
1847 const auto *TN = cast<TypedefNameDecl>(DclIt);
1848 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1849 // Don't allow variably-modified types in constexpr functions.
1850 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1851 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1852 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1853 << TL.getSourceRange() << TL.getType()
1854 << isa<CXXConstructorDecl>(Dcl);
1855 }
1856 return false;
1857 }
1858 continue;
1859 }
1860
1861 case Decl::Enum:
1862 case Decl::CXXRecord:
1863 // C++1y allows types to be defined, not just declared.
1864 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1865 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866 SemaRef.Diag(DS->getBeginLoc(),
1867 SemaRef.getLangOpts().CPlusPlus14
1868 ? diag::warn_cxx11_compat_constexpr_type_definition
1869 : diag::ext_constexpr_type_definition)
1870 << isa<CXXConstructorDecl>(Dcl);
1871 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1872 return false;
1873 }
1874 }
1875 continue;
1876
1877 case Decl::EnumConstant:
1878 case Decl::IndirectField:
1879 case Decl::ParmVar:
1880 // These can only appear with other declarations which are banned in
1881 // C++11 and permitted in C++1y, so ignore them.
1882 continue;
1883
1884 case Decl::Var:
1885 case Decl::Decomposition: {
1886 // C++1y [dcl.constexpr]p3 allows anything except:
1887 // a definition of a variable of non-literal type or of static or
1888 // thread storage duration or [before C++2a] for which no
1889 // initialization is performed.
1890 const auto *VD = cast<VarDecl>(DclIt);
1891 if (VD->isThisDeclarationADefinition()) {
1892 if (VD->isStaticLocal()) {
1893 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1894 SemaRef.Diag(VD->getLocation(),
1895 diag::err_constexpr_local_var_static)
1896 << isa<CXXConstructorDecl>(Dcl)
1897 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1898 }
1899 return false;
1900 }
1901 if (CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1902 diag::err_constexpr_local_var_non_literal_type,
1903 isa<CXXConstructorDecl>(Dcl)))
1904 return false;
1905 if (!VD->getType()->isDependentType() &&
1906 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1907 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1908 SemaRef.Diag(
1909 VD->getLocation(),
1910 SemaRef.getLangOpts().CPlusPlus20
1911 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
1912 : diag::ext_constexpr_local_var_no_init)
1913 << isa<CXXConstructorDecl>(Dcl);
1914 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
1915 return false;
1916 }
1917 continue;
1918 }
1919 }
1920 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1921 SemaRef.Diag(VD->getLocation(),
1922 SemaRef.getLangOpts().CPlusPlus14
1923 ? diag::warn_cxx11_compat_constexpr_local_var
1924 : diag::ext_constexpr_local_var)
1925 << isa<CXXConstructorDecl>(Dcl);
1926 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1927 return false;
1928 }
1929 continue;
1930 }
1931
1932 case Decl::NamespaceAlias:
1933 case Decl::Function:
1934 // These are disallowed in C++11 and permitted in C++1y. Allow them
1935 // everywhere as an extension.
1936 if (!Cxx1yLoc.isValid())
1937 Cxx1yLoc = DS->getBeginLoc();
1938 continue;
1939
1940 default:
1941 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1942 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
1943 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
1944 }
1945 return false;
1946 }
1947 }
1948
1949 return true;
1950}
1951
1952/// Check that the given field is initialized within a constexpr constructor.
1953///
1954/// \param Dcl The constexpr constructor being checked.
1955/// \param Field The field being checked. This may be a member of an anonymous
1956/// struct or union nested within the class being checked.
1957/// \param Inits All declarations, including anonymous struct/union members and
1958/// indirect members, for which any initialization was provided.
1959/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
1960/// multiple notes for different members to the same error.
1961/// \param Kind Whether we're diagnosing a constructor as written or determining
1962/// whether the formal requirements are satisfied.
1963/// \return \c false if we're checking for validity and the constructor does
1964/// not satisfy the requirements on a constexpr constructor.
1965static bool CheckConstexprCtorInitializer(Sema &SemaRef,
1966 const FunctionDecl *Dcl,
1967 FieldDecl *Field,
1968 llvm::SmallSet<Decl*, 16> &Inits,
1969 bool &Diagnosed,
1970 Sema::CheckConstexprKind Kind) {
1971 // In C++20 onwards, there's nothing to check for validity.
1972 if (Kind == Sema::CheckConstexprKind::CheckValid &&
1973 SemaRef.getLangOpts().CPlusPlus20)
1974 return true;
1975
1976 if (Field->isInvalidDecl())
1977 return true;
1978
1979 if (Field->isUnnamedBitfield())
1980 return true;
1981
1982 // Anonymous unions with no variant members and empty anonymous structs do not
1983 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1984 // indirect fields don't need initializing.
1985 if (Field->isAnonymousStructOrUnion() &&
1986 (Field->getType()->isUnionType()
1987 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1988 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1989 return true;
1990
1991 if (!Inits.count(Field)) {
1992 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1993 if (!Diagnosed) {
1994 SemaRef.Diag(Dcl->getLocation(),
1995 SemaRef.getLangOpts().CPlusPlus20
1996 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
1997 : diag::ext_constexpr_ctor_missing_init);
1998 Diagnosed = true;
1999 }
2000 SemaRef.Diag(Field->getLocation(),
2001 diag::note_constexpr_ctor_missing_init);
2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003 return false;
2004 }
2005 } else if (Field->isAnonymousStructOrUnion()) {
2006 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2007 for (auto *I : RD->fields())
2008 // If an anonymous union contains an anonymous struct of which any member
2009 // is initialized, all members must be initialized.
2010 if (!RD->isUnion() || Inits.count(I))
2011 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2012 Kind))
2013 return false;
2014 }
2015 return true;
2016}
2017
2018/// Check the provided statement is allowed in a constexpr function
2019/// definition.
2020static bool
2021CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2022 SmallVectorImpl<SourceLocation> &ReturnStmts,
2023 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2024 Sema::CheckConstexprKind Kind) {
2025 // - its function-body shall be [...] a compound-statement that contains only
2026 switch (S->getStmtClass()) {
2027 case Stmt::NullStmtClass:
2028 // - null statements,
2029 return true;
2030
2031 case Stmt::DeclStmtClass:
2032 // - static_assert-declarations
2033 // - using-declarations,
2034 // - using-directives,
2035 // - typedef declarations and alias-declarations that do not define
2036 // classes or enumerations,
2037 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2038 return false;
2039 return true;
2040
2041 case Stmt::ReturnStmtClass:
2042 // - and exactly one return statement;
2043 if (isa<CXXConstructorDecl>(Dcl)) {
2044 // C++1y allows return statements in constexpr constructors.
2045 if (!Cxx1yLoc.isValid())
2046 Cxx1yLoc = S->getBeginLoc();
2047 return true;
2048 }
2049
2050 ReturnStmts.push_back(S->getBeginLoc());
2051 return true;
2052
2053 case Stmt::CompoundStmtClass: {
2054 // C++1y allows compound-statements.
2055 if (!Cxx1yLoc.isValid())
2056 Cxx1yLoc = S->getBeginLoc();
2057
2058 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2059 for (auto *BodyIt : CompStmt->body()) {
2060 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2061 Cxx1yLoc, Cxx2aLoc, Kind))
2062 return false;
2063 }
2064 return true;
2065 }
2066
2067 case Stmt::AttributedStmtClass:
2068 if (!Cxx1yLoc.isValid())
2069 Cxx1yLoc = S->getBeginLoc();
2070 return true;
2071
2072 case Stmt::IfStmtClass: {
2073 // C++1y allows if-statements.
2074 if (!Cxx1yLoc.isValid())
2075 Cxx1yLoc = S->getBeginLoc();
2076
2077 IfStmt *If = cast<IfStmt>(S);
2078 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2079 Cxx1yLoc, Cxx2aLoc, Kind))
2080 return false;
2081 if (If->getElse() &&
2082 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2083 Cxx1yLoc, Cxx2aLoc, Kind))
2084 return false;
2085 return true;
2086 }
2087
2088 case Stmt::WhileStmtClass:
2089 case Stmt::DoStmtClass:
2090 case Stmt::ForStmtClass:
2091 case Stmt::CXXForRangeStmtClass:
2092 case Stmt::ContinueStmtClass:
2093 // C++1y allows all of these. We don't allow them as extensions in C++11,
2094 // because they don't make sense without variable mutation.
2095 if (!SemaRef.getLangOpts().CPlusPlus14)
2096 break;
2097 if (!Cxx1yLoc.isValid())
2098 Cxx1yLoc = S->getBeginLoc();
2099 for (Stmt *SubStmt : S->children())
2100 if (SubStmt &&
2101 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2102 Cxx1yLoc, Cxx2aLoc, Kind))
2103 return false;
2104 return true;
2105
2106 case Stmt::SwitchStmtClass:
2107 case Stmt::CaseStmtClass:
2108 case Stmt::DefaultStmtClass:
2109 case Stmt::BreakStmtClass:
2110 // C++1y allows switch-statements, and since they don't need variable
2111 // mutation, we can reasonably allow them in C++11 as an extension.
2112 if (!Cxx1yLoc.isValid())
2113 Cxx1yLoc = S->getBeginLoc();
2114 for (Stmt *SubStmt : S->children())
2115 if (SubStmt &&
2116 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2117 Cxx1yLoc, Cxx2aLoc, Kind))
2118 return false;
2119 return true;
2120
2121 case Stmt::GCCAsmStmtClass:
2122 case Stmt::MSAsmStmtClass:
2123 // C++2a allows inline assembly statements.
2124 case Stmt::CXXTryStmtClass:
2125 if (Cxx2aLoc.isInvalid())
2126 Cxx2aLoc = S->getBeginLoc();
2127 for (Stmt *SubStmt : S->children()) {
2128 if (SubStmt &&
2129 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2130 Cxx1yLoc, Cxx2aLoc, Kind))
2131 return false;
2132 }
2133 return true;
2134
2135 case Stmt::CXXCatchStmtClass:
2136 // Do not bother checking the language mode (already covered by the
2137 // try block check).
2138 if (!CheckConstexprFunctionStmt(SemaRef, Dcl,
2139 cast<CXXCatchStmt>(S)->getHandlerBlock(),
2140 ReturnStmts, Cxx1yLoc, Cxx2aLoc, Kind))
2141 return false;
2142 return true;
2143
2144 default:
2145 if (!isa<Expr>(S))
2146 break;
2147
2148 // C++1y allows expression-statements.
2149 if (!Cxx1yLoc.isValid())
2150 Cxx1yLoc = S->getBeginLoc();
2151 return true;
2152 }
2153
2154 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2155 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2156 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2157 }
2158 return false;
2159}
2160
2161/// Check the body for the given constexpr function declaration only contains
2162/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2163///
2164/// \return true if the body is OK, false if we have found or diagnosed a
2165/// problem.
2166static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2167 Stmt *Body,
2168 Sema::CheckConstexprKind Kind) {
2169 SmallVector<SourceLocation, 4> ReturnStmts;
2170
2171 if (isa<CXXTryStmt>(Body)) {
2172 // C++11 [dcl.constexpr]p3:
2173 // The definition of a constexpr function shall satisfy the following
2174 // constraints: [...]
2175 // - its function-body shall be = delete, = default, or a
2176 // compound-statement
2177 //
2178 // C++11 [dcl.constexpr]p4:
2179 // In the definition of a constexpr constructor, [...]
2180 // - its function-body shall not be a function-try-block;
2181 //
2182 // This restriction is lifted in C++2a, as long as inner statements also
2183 // apply the general constexpr rules.
2184 switch (Kind) {
2185 case Sema::CheckConstexprKind::CheckValid:
2186 if (!SemaRef.getLangOpts().CPlusPlus20)
2187 return false;
2188 break;
2189
2190 case Sema::CheckConstexprKind::Diagnose:
2191 SemaRef.Diag(Body->getBeginLoc(),
2192 !SemaRef.getLangOpts().CPlusPlus20
2193 ? diag::ext_constexpr_function_try_block_cxx20
2194 : diag::warn_cxx17_compat_constexpr_function_try_block)
2195 << isa<CXXConstructorDecl>(Dcl);
2196 break;
2197 }
2198 }
2199
2200 // - its function-body shall be [...] a compound-statement that contains only
2201 // [... list of cases ...]
2202 //
2203 // Note that walking the children here is enough to properly check for
2204 // CompoundStmt and CXXTryStmt body.
2205 SourceLocation Cxx1yLoc, Cxx2aLoc;
2206 for (Stmt *SubStmt : Body->children()) {
2207 if (SubStmt &&
2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2209 Cxx1yLoc, Cxx2aLoc, Kind))
2210 return false;
2211 }
2212
2213 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2214 // If this is only valid as an extension, report that we don't satisfy the
2215 // constraints of the current language.
2216 if ((Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2217 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2218 return false;
2219 } else if (Cxx2aLoc.isValid()) {
2220 SemaRef.Diag(Cxx2aLoc,
2221 SemaRef.getLangOpts().CPlusPlus20
2222 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2223 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2224 << isa<CXXConstructorDecl>(Dcl);
2225 } else if (Cxx1yLoc.isValid()) {
2226 SemaRef.Diag(Cxx1yLoc,
2227 SemaRef.getLangOpts().CPlusPlus14
2228 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2229 : diag::ext_constexpr_body_invalid_stmt)
2230 << isa<CXXConstructorDecl>(Dcl);
2231 }
2232
2233 if (const CXXConstructorDecl *Constructor
2234 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2235 const CXXRecordDecl *RD = Constructor->getParent();
2236 // DR1359:
2237 // - every non-variant non-static data member and base class sub-object
2238 // shall be initialized;
2239 // DR1460:
2240 // - if the class is a union having variant members, exactly one of them
2241 // shall be initialized;
2242 if (RD->isUnion()) {
2243 if (Constructor->getNumCtorInitializers() == 0 &&
2244 RD->hasVariantMembers()) {
2245 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2246 SemaRef.Diag(
2247 Dcl->getLocation(),
2248 SemaRef.getLangOpts().CPlusPlus20
2249 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2250 : diag::ext_constexpr_union_ctor_no_init);
2251 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2252 return false;
2253 }
2254 }
2255 } else if (!Constructor->isDependentContext() &&
2256 !Constructor->isDelegatingConstructor()) {
2257 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases")(static_cast<void> (0));
2258
2259 // Skip detailed checking if we have enough initializers, and we would
2260 // allow at most one initializer per member.
2261 bool AnyAnonStructUnionMembers = false;
2262 unsigned Fields = 0;
2263 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2264 E = RD->field_end(); I != E; ++I, ++Fields) {
2265 if (I->isAnonymousStructOrUnion()) {
2266 AnyAnonStructUnionMembers = true;
2267 break;
2268 }
2269 }
2270 // DR1460:
2271 // - if the class is a union-like class, but is not a union, for each of
2272 // its anonymous union members having variant members, exactly one of
2273 // them shall be initialized;
2274 if (AnyAnonStructUnionMembers ||
2275 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2276 // Check initialization of non-static data members. Base classes are
2277 // always initialized so do not need to be checked. Dependent bases
2278 // might not have initializers in the member initializer list.
2279 llvm::SmallSet<Decl*, 16> Inits;
2280 for (const auto *I: Constructor->inits()) {
2281 if (FieldDecl *FD = I->getMember())
2282 Inits.insert(FD);
2283 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2284 Inits.insert(ID->chain_begin(), ID->chain_end());
2285 }
2286
2287 bool Diagnosed = false;
2288 for (auto *I : RD->fields())
2289 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2290 Kind))
2291 return false;
2292 }
2293 }
2294 } else {
2295 if (ReturnStmts.empty()) {
2296 // C++1y doesn't require constexpr functions to contain a 'return'
2297 // statement. We still do, unless the return type might be void, because
2298 // otherwise if there's no return statement, the function cannot
2299 // be used in a core constant expression.
2300 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2301 (Dcl->getReturnType()->isVoidType() ||
2302 Dcl->getReturnType()->isDependentType());
2303 switch (Kind) {
2304 case Sema::CheckConstexprKind::Diagnose:
2305 SemaRef.Diag(Dcl->getLocation(),
2306 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2307 : diag::err_constexpr_body_no_return)
2308 << Dcl->isConsteval();
2309 if (!OK)
2310 return false;
2311 break;
2312
2313 case Sema::CheckConstexprKind::CheckValid:
2314 // The formal requirements don't include this rule in C++14, even
2315 // though the "must be able to produce a constant expression" rules
2316 // still imply it in some cases.
2317 if (!SemaRef.getLangOpts().CPlusPlus14)
2318 return false;
2319 break;
2320 }
2321 } else if (ReturnStmts.size() > 1) {
2322 switch (Kind) {
2323 case Sema::CheckConstexprKind::Diagnose:
2324 SemaRef.Diag(
2325 ReturnStmts.back(),
2326 SemaRef.getLangOpts().CPlusPlus14
2327 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2328 : diag::ext_constexpr_body_multiple_return);
2329 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2330 SemaRef.Diag(ReturnStmts[I],
2331 diag::note_constexpr_body_previous_return);
2332 break;
2333
2334 case Sema::CheckConstexprKind::CheckValid:
2335 if (!SemaRef.getLangOpts().CPlusPlus14)
2336 return false;
2337 break;
2338 }
2339 }
2340 }
2341
2342 // C++11 [dcl.constexpr]p5:
2343 // if no function argument values exist such that the function invocation
2344 // substitution would produce a constant expression, the program is
2345 // ill-formed; no diagnostic required.
2346 // C++11 [dcl.constexpr]p3:
2347 // - every constructor call and implicit conversion used in initializing the
2348 // return value shall be one of those allowed in a constant expression.
2349 // C++11 [dcl.constexpr]p4:
2350 // - every constructor involved in initializing non-static data members and
2351 // base class sub-objects shall be a constexpr constructor.
2352 //
2353 // Note that this rule is distinct from the "requirements for a constexpr
2354 // function", so is not checked in CheckValid mode.
2355 SmallVector<PartialDiagnosticAt, 8> Diags;
2356 if (Kind == Sema::CheckConstexprKind::Diagnose &&
2357 !Expr::isPotentialConstantExpr(Dcl, Diags)) {
2358 SemaRef.Diag(Dcl->getLocation(),
2359 diag::ext_constexpr_function_never_constant_expr)
2360 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2361 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2362 SemaRef.Diag(Diags[I].first, Diags[I].second);
2363 // Don't return false here: we allow this for compatibility in
2364 // system headers.
2365 }
2366
2367 return true;
2368}
2369
2370/// Get the class that is directly named by the current context. This is the
2371/// class for which an unqualified-id in this scope could name a constructor
2372/// or destructor.
2373///
2374/// If the scope specifier denotes a class, this will be that class.
2375/// If the scope specifier is empty, this will be the class whose
2376/// member-specification we are currently within. Otherwise, there
2377/// is no such class.
2378CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2379 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast<void> (0));
2380
2381 if (SS && SS->isInvalid())
2382 return nullptr;
2383
2384 if (SS && SS->isNotEmpty()) {
2385 DeclContext *DC = computeDeclContext(*SS, true);
2386 return dyn_cast_or_null<CXXRecordDecl>(DC);
2387 }
2388
2389 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2390}
2391
2392/// isCurrentClassName - Determine whether the identifier II is the
2393/// name of the class type currently being defined. In the case of
2394/// nested classes, this will only return true if II is the name of
2395/// the innermost class.
2396bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2397 const CXXScopeSpec *SS) {
2398 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2399 return CurDecl && &II == CurDecl->getIdentifier();
2400}
2401
2402/// Determine whether the identifier II is a typo for the name of
2403/// the class type currently being defined. If so, update it to the identifier
2404/// that should have been used.
2405bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2406 assert(getLangOpts().CPlusPlus && "No class names in C!")(static_cast<void> (0));
2407
2408 if (!getLangOpts().SpellChecking)
2409 return false;
2410
2411 CXXRecordDecl *CurDecl;
2412 if (SS && SS->isSet() && !SS->isInvalid()) {
2413 DeclContext *DC = computeDeclContext(*SS, true);
2414 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2415 } else
2416 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2417
2418 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2419 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2420 < II->getLength()) {
2421 II = CurDecl->getIdentifier();
2422 return true;
2423 }
2424
2425 return false;
2426}
2427
2428/// Determine whether the given class is a base class of the given
2429/// class, including looking at dependent bases.
2430static bool findCircularInheritance(const CXXRecordDecl *Class,
2431 const CXXRecordDecl *Current) {
2432 SmallVector<const CXXRecordDecl*, 8> Queue;
2433
2434 Class = Class->getCanonicalDecl();
2435 while (true) {
2436 for (const auto &I : Current->bases()) {
2437 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2438 if (!Base)
2439 continue;
2440
2441 Base = Base->getDefinition();
2442 if (!Base)
2443 continue;
2444
2445 if (Base->getCanonicalDecl() == Class)
2446 return true;
2447
2448 Queue.push_back(Base);
2449 }
2450
2451 if (Queue.empty())
2452 return false;
2453
2454 Current = Queue.pop_back_val();
2455 }
2456
2457 return false;
2458}
2459
2460/// Check the validity of a C++ base class specifier.
2461///
2462/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2463/// and returns NULL otherwise.
2464CXXBaseSpecifier *
2465Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2466 SourceRange SpecifierRange,
2467 bool Virtual, AccessSpecifier Access,
2468 TypeSourceInfo *TInfo,
2469 SourceLocation EllipsisLoc) {
2470 QualType BaseType = TInfo->getType();
2471 if (BaseType->containsErrors()) {
2472 // Already emitted a diagnostic when parsing the error type.
2473 return nullptr;
2474 }
2475 // C++ [class.union]p1:
2476 // A union shall not have base classes.
2477 if (Class->isUnion()) {
2478 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2479 << SpecifierRange;
2480 return nullptr;
2481 }
2482
2483 if (EllipsisLoc.isValid() &&
2484 !TInfo->getType()->containsUnexpandedParameterPack()) {
2485 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2486 << TInfo->getTypeLoc().getSourceRange();
2487 EllipsisLoc = SourceLocation();
2488 }
2489
2490 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2491
2492 if (BaseType->isDependentType()) {
2493 // Make sure that we don't have circular inheritance among our dependent
2494 // bases. For non-dependent bases, the check for completeness below handles
2495 // this.
2496 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2497 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2498 ((BaseDecl = BaseDecl->getDefinition()) &&
2499 findCircularInheritance(Class, BaseDecl))) {
2500 Diag(BaseLoc, diag::err_circular_inheritance)
2501 << BaseType << Context.getTypeDeclType(Class);
2502
2503 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2504 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2505 << BaseType;
2506
2507 return nullptr;
2508 }
2509 }
2510
2511 // Make sure that we don't make an ill-formed AST where the type of the
2512 // Class is non-dependent and its attached base class specifier is an
2513 // dependent type, which violates invariants in many clang code paths (e.g.
2514 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2515 // explicitly mark the Class decl invalid. The diagnostic was already
2516 // emitted.
2517 if (!Class->getTypeForDecl()->isDependentType())
2518 Class->setInvalidDecl();
2519 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2520 Class->getTagKind() == TTK_Class,
2521 Access, TInfo, EllipsisLoc);
2522 }
2523
2524 // Base specifiers must be record types.
2525 if (!BaseType->isRecordType()) {
2526 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2527 return nullptr;
2528 }
2529
2530 // C++ [class.union]p1:
2531 // A union shall not be used as a base class.
2532 if (BaseType->isUnionType()) {
2533 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2534 return nullptr;
2535 }
2536
2537 // For the MS ABI, propagate DLL attributes to base class templates.
2538 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2539 if (Attr *ClassAttr = getDLLAttr(Class)) {
2540 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2541 BaseType->getAsCXXRecordDecl())) {
2542 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2543 BaseLoc);
2544 }
2545 }
2546 }
2547
2548 // C++ [class.derived]p2:
2549 // The class-name in a base-specifier shall not be an incompletely
2550 // defined class.
2551 if (RequireCompleteType(BaseLoc, BaseType,
2552 diag::err_incomplete_base_class, SpecifierRange)) {
2553 Class->setInvalidDecl();
2554 return nullptr;
2555 }
2556
2557 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2558 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2559 assert(BaseDecl && "Record type has no declaration")(static_cast<void> (0));
2560 BaseDecl = BaseDecl->getDefinition();
2561 assert(BaseDecl && "Base type is not incomplete, but has no definition")(static_cast<void> (0));
2562 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2563 assert(CXXBaseDecl && "Base type is not a C++ type")(static_cast<void> (0));
2564
2565 // Microsoft docs say:
2566 // "If a base-class has a code_seg attribute, derived classes must have the
2567 // same attribute."
2568 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2569 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2570 if ((DerivedCSA || BaseCSA) &&
2571 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2572 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2573 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2574 << CXXBaseDecl;
2575 return nullptr;
2576 }
2577
2578 // A class which contains a flexible array member is not suitable for use as a
2579 // base class:
2580 // - If the layout determines that a base comes before another base,
2581 // the flexible array member would index into the subsequent base.
2582 // - If the layout determines that base comes before the derived class,
2583 // the flexible array member would index into the derived class.
2584 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2585 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2586 << CXXBaseDecl->getDeclName();
2587 return nullptr;
2588 }
2589
2590 // C++ [class]p3:
2591 // If a class is marked final and it appears as a base-type-specifier in
2592 // base-clause, the program is ill-formed.
2593 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2594 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2595 << CXXBaseDecl->getDeclName()
2596 << FA->isSpelledAsSealed();
2597 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2598 << CXXBaseDecl->getDeclName() << FA->getRange();
2599 return nullptr;
2600 }
2601
2602 if (BaseDecl->isInvalidDecl())
2603 Class->setInvalidDecl();
2604
2605 // Create the base specifier.
2606 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2607 Class->getTagKind() == TTK_Class,
2608 Access, TInfo, EllipsisLoc);
2609}
2610
2611/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2612/// one entry in the base class list of a class specifier, for
2613/// example:
2614/// class foo : public bar, virtual private baz {
2615/// 'public bar' and 'virtual private baz' are each base-specifiers.
2616BaseResult
2617Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2618 ParsedAttributes &Attributes,
2619 bool Virtual, AccessSpecifier Access,
2620 ParsedType basetype, SourceLocation BaseLoc,
2621 SourceLocation EllipsisLoc) {
2622 if (!classdecl)
2623 return true;
2624
2625 AdjustDeclIfTemplate(classdecl);
2626 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2627 if (!Class)
2628 return true;
2629
2630 // We haven't yet attached the base specifiers.
2631 Class->setIsParsingBaseSpecifiers();
2632
2633 // We do not support any C++11 attributes on base-specifiers yet.
2634 // Diagnose any attributes we see.
2635 for (const ParsedAttr &AL : Attributes) {
2636 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2637 continue;
2638 Diag(AL.getLoc(), AL.getKind() == ParsedAttr::UnknownAttribute
2639 ? (unsigned)diag::warn_unknown_attribute_ignored
2640 : (unsigned)diag::err_base_specifier_attribute)
2641 << AL << AL.getRange();
2642 }
2643
2644 TypeSourceInfo *TInfo = nullptr;
2645 GetTypeFromParser(basetype, &TInfo);
2646
2647 if (EllipsisLoc.isInvalid() &&
2648 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2649 UPPC_BaseType))
2650 return true;
2651
2652 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2653 Virtual, Access, TInfo,
2654 EllipsisLoc))
2655 return BaseSpec;
2656 else
2657 Class->setInvalidDecl();
2658
2659 return true;
2660}
2661
2662/// Use small set to collect indirect bases. As this is only used
2663/// locally, there's no need to abstract the small size parameter.
2664typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2665
2666/// Recursively add the bases of Type. Don't add Type itself.
2667static void
2668NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2669 const QualType &Type)
2670{
2671 // Even though the incoming type is a base, it might not be
2672 // a class -- it could be a template parm, for instance.
2673 if (auto Rec = Type->getAs<RecordType>()) {
2674 auto Decl = Rec->getAsCXXRecordDecl();
2675
2676 // Iterate over its bases.
2677 for (const auto &BaseSpec : Decl->bases()) {
2678 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2679 .getUnqualifiedType();
2680 if (Set.insert(Base).second)
2681 // If we've not already seen it, recurse.
2682 NoteIndirectBases(Context, Set, Base);
2683 }
2684 }
2685}
2686
2687/// Performs the actual work of attaching the given base class
2688/// specifiers to a C++ class.
2689bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2690 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2691 if (Bases.empty())
2692 return false;
2693
2694 // Used to keep track of which base types we have already seen, so
2695 // that we can properly diagnose redundant direct base types. Note
2696 // that the key is always the unqualified canonical type of the base
2697 // class.
2698 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2699
2700 // Used to track indirect bases so we can see if a direct base is
2701 // ambiguous.
2702 IndirectBaseSet IndirectBaseTypes;
2703
2704 // Copy non-redundant base specifiers into permanent storage.
2705 unsigned NumGoodBases = 0;
2706 bool Invalid = false;
2707 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2708 QualType NewBaseType
2709 = Context.getCanonicalType(Bases[idx]->getType());
2710 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2711
2712 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2713 if (KnownBase) {
2714 // C++ [class.mi]p3:
2715 // A class shall not be specified as a direct base class of a
2716 // derived class more than once.
2717 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2718 << KnownBase->getType() << Bases[idx]->getSourceRange();
2719
2720 // Delete the duplicate base class specifier; we're going to
2721 // overwrite its pointer later.
2722 Context.Deallocate(Bases[idx]);
2723
2724 Invalid = true;
2725 } else {
2726 // Okay, add this new base class.
2727 KnownBase = Bases[idx];
2728 Bases[NumGoodBases++] = Bases[idx];
2729
2730 // Note this base's direct & indirect bases, if there could be ambiguity.
2731 if (Bases.size() > 1)
2732 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2733
2734 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2735 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2736 if (Class->isInterface() &&
2737 (!RD->isInterfaceLike() ||
2738 KnownBase->getAccessSpecifier() != AS_public)) {
2739 // The Microsoft extension __interface does not permit bases that
2740 // are not themselves public interfaces.
2741 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2742 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2743 << RD->getSourceRange();
2744 Invalid = true;
2745 }
2746 if (RD->hasAttr<WeakAttr>())
2747 Class->addAttr(WeakAttr::CreateImplicit(Context));
2748 }
2749 }
2750 }
2751
2752 // Attach the remaining base class specifiers to the derived class.
2753 Class->setBases(Bases.data(), NumGoodBases);
2754
2755 // Check that the only base classes that are duplicate are virtual.
2756 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2757 // Check whether this direct base is inaccessible due to ambiguity.
2758 QualType BaseType = Bases[idx]->getType();
2759
2760 // Skip all dependent types in templates being used as base specifiers.
2761 // Checks below assume that the base specifier is a CXXRecord.
2762 if (BaseType->isDependentType())
2763 continue;
2764
2765 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2766 .getUnqualifiedType();
2767
2768 if (IndirectBaseTypes.count(CanonicalBase)) {
2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2770 /*DetectVirtual=*/true);
2771 bool found
2772 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2773 assert(found)(static_cast<void> (0));
2774 (void)found;
2775
2776 if (Paths.isAmbiguous(CanonicalBase))
2777 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
2778 << BaseType << getAmbiguousPathsDisplayString(Paths)
2779 << Bases[idx]->getSourceRange();
2780 else
2781 assert(Bases[idx]->isVirtual())(static_cast<void> (0));
2782 }
2783
2784 // Delete the base class specifier, since its data has been copied
2785 // into the CXXRecordDecl.
2786 Context.Deallocate(Bases[idx]);
2787 }
2788
2789 return Invalid;
2790}
2791
2792/// ActOnBaseSpecifiers - Attach the given base specifiers to the
2793/// class, after checking whether there are any duplicate base
2794/// classes.
2795void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2796 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2797 if (!ClassDecl || Bases.empty())
2798 return;
2799
2800 AdjustDeclIfTemplate(ClassDecl);
2801 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2802}
2803
2804/// Determine whether the type \p Derived is a C++ class that is
2805/// derived from the type \p Base.
2806bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2807 if (!getLangOpts().CPlusPlus)
2808 return false;
2809
2810 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2811 if (!DerivedRD)
2812 return false;
2813
2814 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2815 if (!BaseRD)
2816 return false;
2817
2818 // If either the base or the derived type is invalid, don't try to
2819 // check whether one is derived from the other.
2820 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2821 return false;
2822
2823 // FIXME: In a modules build, do we need the entire path to be visible for us
2824 // to be able to use the inheritance relationship?
2825 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2826 return false;
2827
2828 return DerivedRD->isDerivedFrom(BaseRD);
2829}
2830
2831/// Determine whether the type \p Derived is a C++ class that is
2832/// derived from the type \p Base.
2833bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2834 CXXBasePaths &Paths) {
2835 if (!getLangOpts().CPlusPlus)
2836 return false;
2837
2838 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2839 if (!DerivedRD)
2840 return false;
2841
2842 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2843 if (!BaseRD)
2844 return false;
2845
2846 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2847 return false;
2848
2849 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2850}
2851
2852static void BuildBasePathArray(const CXXBasePath &Path,
2853 CXXCastPath &BasePathArray) {
2854 // We first go backward and check if we have a virtual base.
2855 // FIXME: It would be better if CXXBasePath had the base specifier for
2856 // the nearest virtual base.
2857 unsigned Start = 0;
2858 for (unsigned I = Path.size(); I != 0; --I) {
2859 if (Path[I - 1].Base->isVirtual()) {
2860 Start = I - 1;
2861 break;
2862 }
2863 }
2864
2865 // Now add all bases.
2866 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2867 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2868}
2869
2870
2871void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2872 CXXCastPath &BasePathArray) {
2873 assert(BasePathArray.empty() && "Base path array must be empty!")(static_cast<void> (0));
2874 assert(Paths.isRecordingPaths() && "Must record paths!")(static_cast<void> (0));
2875 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2876}
2877/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2878/// conversion (where Derived and Base are class types) is
2879/// well-formed, meaning that the conversion is unambiguous (and
2880/// that all of the base classes are accessible). Returns true
2881/// and emits a diagnostic if the code is ill-formed, returns false
2882/// otherwise. Loc is the location where this routine should point to
2883/// if there is an error, and Range is the source range to highlight
2884/// if there is an error.
2885///
2886/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
2887/// diagnostic for the respective type of error will be suppressed, but the
2888/// check for ill-formed code will still be performed.
2889bool
2890Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2891 unsigned InaccessibleBaseID,
2892 unsigned AmbiguousBaseConvID,
2893 SourceLocation Loc, SourceRange Range,
2894 DeclarationName Name,
2895 CXXCastPath *BasePath,
2896 bool IgnoreAccess) {
2897 // First, determine whether the path from Derived to Base is
2898 // ambiguous. This is slightly more expensive than checking whether
2899 // the Derived to Base conversion exists, because here we need to
2900 // explore multiple paths to determine if there is an ambiguity.
2901 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2902 /*DetectVirtual=*/false);
2903 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2904 if (!DerivationOkay)
2905 return true;
2906
2907 const CXXBasePath *Path = nullptr;
2908 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2909 Path = &Paths.front();
2910
2911 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2912 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2913 // user to access such bases.
2914 if (!Path && getLangOpts().MSVCCompat) {
2915 for (const CXXBasePath &PossiblePath : Paths) {
2916 if (PossiblePath.size() == 1) {
2917 Path = &PossiblePath;
2918 if (AmbiguousBaseConvID)
2919 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2920 << Base << Derived << Range;
2921 break;
2922 }
2923 }
2924 }
2925
2926 if (Path) {
2927 if (!IgnoreAccess) {
2928 // Check that the base class can be accessed.
2929 switch (
2930 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2931 case AR_inaccessible:
2932 return true;
2933 case AR_accessible:
2934 case AR_dependent:
2935 case AR_delayed:
2936 break;
2937 }
2938 }
2939
2940 // Build a base path if necessary.
2941 if (BasePath)
2942 ::BuildBasePathArray(*Path, *BasePath);
2943 return false;
2944 }
2945
2946 if (AmbiguousBaseConvID) {
2947 // We know that the derived-to-base conversion is ambiguous, and
2948 // we're going to produce a diagnostic. Perform the derived-to-base
2949 // search just one more time to compute all of the possible paths so
2950 // that we can print them out. This is more expensive than any of
2951 // the previous derived-to-base checks we've done, but at this point
2952 // performance isn't as much of an issue.
2953 Paths.clear();
2954 Paths.setRecordingPaths(true);
2955 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2956 assert(StillOkay && "Can only be used with a derived-to-base conversion")(static_cast<void> (0));
2957 (void)StillOkay;
2958
2959 // Build up a textual representation of the ambiguous paths, e.g.,
2960 // D -> B -> A, that will be used to illustrate the ambiguous
2961 // conversions in the diagnostic. We only print one of the paths
2962 // to each base class subobject.
2963 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2964
2965 Diag(Loc, AmbiguousBaseConvID)
2966 << Derived << Base << PathDisplayStr << Range << Name;
2967 }
2968 return true;
2969}
2970
2971bool
2972Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2973 SourceLocation Loc, SourceRange Range,
2974 CXXCastPath *BasePath,
2975 bool IgnoreAccess) {
2976 return CheckDerivedToBaseConversion(
2977 Derived, Base, diag::err_upcast_to_inaccessible_base,
2978 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2979 BasePath, IgnoreAccess);
2980}
2981
2982
2983/// Builds a string representing ambiguous paths from a
2984/// specific derived class to different subobjects of the same base
2985/// class.
2986///
2987/// This function builds a string that can be used in error messages
2988/// to show the different paths that one can take through the
2989/// inheritance hierarchy to go from the derived class to different
2990/// subobjects of a base class. The result looks something like this:
2991/// @code
2992/// struct D -> struct B -> struct A
2993/// struct D -> struct C -> struct A
2994/// @endcode
2995std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2996 std::string PathDisplayStr;
2997 std::set<unsigned> DisplayedPaths;
2998 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2999 Path != Paths.end(); ++Path) {
3000 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3001 // We haven't displayed a path to this particular base
3002 // class subobject yet.
3003 PathDisplayStr += "\n ";
3004 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3005 for (CXXBasePath::const_iterator Element = Path->begin();
3006 Element != Path->end(); ++Element)
3007 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3008 }
3009 }
3010
3011 return PathDisplayStr;
3012}
3013
3014//===----------------------------------------------------------------------===//
3015// C++ class member Handling
3016//===----------------------------------------------------------------------===//
3017
3018/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3019bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3020 SourceLocation ColonLoc,
3021 const ParsedAttributesView &Attrs) {
3022 assert(Access != AS_none && "Invalid kind for syntactic access specifier!")(static_cast<void> (0));
3023 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
3024 ASLoc, ColonLoc);
3025 CurContext->addHiddenDecl(ASDecl);
3026 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3027}
3028
3029/// CheckOverrideControl - Check C++11 override control semantics.
3030void Sema::CheckOverrideControl(NamedDecl *D) {
3031 if (D->isInvalidDecl())
3032 return;
3033
3034 // We only care about "override" and "final" declarations.
3035 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3036 return;
3037
3038 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3039
3040 // We can't check dependent instance methods.
3041 if (MD && MD->isInstance() &&
3042 (MD->getParent()->hasAnyDependentBases() ||
3043 MD->getType()->isDependentType()))
3044 return;
3045
3046 if (MD && !MD->isVirtual()) {
3047 // If we have a non-virtual method, check if if hides a virtual method.
3048 // (In that case, it's most likely the method has the wrong type.)
3049 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3050 FindHiddenVirtualMethods(MD, OverloadedMethods);
3051
3052 if (!OverloadedMethods.empty()) {
3053 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3054 Diag(OA->getLocation(),
3055 diag::override_keyword_hides_virtual_member_function)
3056 << "override" << (OverloadedMethods.size() > 1);
3057 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3058 Diag(FA->getLocation(),
3059 diag::override_keyword_hides_virtual_member_function)
3060 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3061 << (OverloadedMethods.size() > 1);
3062 }
3063 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3064 MD->setInvalidDecl();
3065 return;
3066 }
3067 // Fall through into the general case diagnostic.
3068 // FIXME: We might want to attempt typo correction here.
3069 }
3070
3071 if (!MD || !MD->isVirtual()) {
3072 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3073 Diag(OA->getLocation(),
3074 diag::override_keyword_only_allowed_on_virtual_member_functions)
3075 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3076 D->dropAttr<OverrideAttr>();
3077 }
3078 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3079 Diag(FA->getLocation(),
3080 diag::override_keyword_only_allowed_on_virtual_member_functions)
3081 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3082 << FixItHint::CreateRemoval(FA->getLocation());
3083 D->dropAttr<FinalAttr>();
3084 }
3085 return;
3086 }
3087
3088 // C++11 [class.virtual]p5:
3089 // If a function is marked with the virt-specifier override and
3090 // does not override a member function of a base class, the program is
3091 // ill-formed.
3092 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3093 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3094 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3095 << MD->getDeclName();
3096}
3097
3098void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3099 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3100 return;
3101 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3102 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3103 return;
3104
3105 SourceLocation Loc = MD->getLocation();
3106 SourceLocation SpellingLoc = Loc;
3107 if (getSourceManager().isMacroArgExpansion(Loc))
3108 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3109 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3110 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3111 return;
3112
3113 if (MD->size_overridden_methods() > 0) {
3114 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3115 unsigned DiagID =
3116 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3117 ? DiagInconsistent
3118 : DiagSuggest;
3119 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3120 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3121 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3122 };
3123 if (isa<CXXDestructorDecl>(MD))
3124 EmitDiag(
3125 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3126 diag::warn_suggest_destructor_marked_not_override_overriding);
3127 else
3128 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3129 diag::warn_suggest_function_marked_not_override_overriding);
3130 }
3131}
3132
3133/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3134/// function overrides a virtual member function marked 'final', according to
3135/// C++11 [class.virtual]p4.
3136bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3137 const CXXMethodDecl *Old) {
3138 FinalAttr *FA = Old->getAttr<FinalAttr>();
3139 if (!FA)
3140 return false;
3141
3142 Diag(New->getLocation(), diag::err_final_function_overridden)
3143 << New->getDeclName()
3144 << FA->isSpelledAsSealed();
3145 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3146 return true;
3147}
3148
3149static bool InitializationHasSideEffects(const FieldDecl &FD) {
3150 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3151 // FIXME: Destruction of ObjC lifetime types has side-effects.
3152 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3153 return !RD->isCompleteDefinition() ||
3154 !RD->hasTrivialDefaultConstructor() ||
3155 !RD->hasTrivialDestructor();
3156 return false;
3157}
3158
3159static const ParsedAttr *getMSPropertyAttr(const ParsedAttributesView &list) {
3160 ParsedAttributesView::const_iterator Itr =
3161 llvm::find_if(list, [](const ParsedAttr &AL) {
3162 return AL.isDeclspecPropertyAttribute();
3163 });
3164 if (Itr != list.end())
3165 return &*Itr;
3166 return nullptr;
3167}
3168
3169// Check if there is a field shadowing.
3170void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3171 DeclarationName FieldName,
3172 const CXXRecordDecl *RD,
3173 bool DeclIsField) {
3174 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3175 return;
3176
3177 // To record a shadowed field in a base
3178 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3179 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3180 CXXBasePath &Path) {
3181 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3182 // Record an ambiguous path directly
3183 if (Bases.find(Base) != Bases.end())
3184 return true;
3185 for (const auto Field : Base->lookup(FieldName)) {
3186 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3187 Field->getAccess() != AS_private) {
3188 assert(Field->getAccess() != AS_none)(static_cast<void> (0));
3189 assert(Bases.find(Base) == Bases.end())(static_cast<void> (0));
3190 Bases[Base] = Field;
3191 return true;
3192 }
3193 }
3194 return false;
3195 };
3196
3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3198 /*DetectVirtual=*/true);
3199 if (!RD->lookupInBases(FieldShadowed, Paths))
3200 return;
3201
3202 for (const auto &P : Paths) {
3203 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3204 auto It = Bases.find(Base);
3205 // Skip duplicated bases
3206 if (It == Bases.end())
3207 continue;
3208 auto BaseField = It->second;
3209 assert(BaseField->getAccess() != AS_private)(static_cast<void> (0));
3210 if (AS_none !=
3211 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3212 Diag(Loc, diag::warn_shadow_field)
3213 << FieldName << RD << Base << DeclIsField;
3214 Diag(BaseField->getLocation(), diag::note_shadow_field);
3215 Bases.erase(It);
3216 }
3217 }
3218}
3219
3220/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3221/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3222/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3223/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3224/// present (but parsing it has been deferred).
3225NamedDecl *
3226Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3227 MultiTemplateParamsArg TemplateParameterLists,
3228 Expr *BW, const VirtSpecifiers &VS,
3229 InClassInitStyle InitStyle) {
3230 const DeclSpec &DS = D.getDeclSpec();
3231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3232 DeclarationName Name = NameInfo.getName();
3233 SourceLocation Loc = NameInfo.getLoc();
3234
3235 // For anonymous bitfields, the location should point to the type.
3236 if (Loc.isInvalid())
3237 Loc = D.getBeginLoc();
3238
3239 Expr *BitWidth = static_cast<Expr*>(BW);
3240
3241 assert(isa<CXXRecordDecl>(CurContext))(static_cast<void> (0));
3242 assert(!DS.isFriendSpecified())(static_cast<void> (0));
3243
3244 bool isFunc = D.isDeclarationOfFunction();
3245 const ParsedAttr *MSPropertyAttr =
3246 getMSPropertyAttr(D.getDeclSpec().getAttributes());
3247
3248 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3249 // The Microsoft extension __interface only permits public member functions
3250 // and prohibits constructors, destructors, operators, non-public member
3251 // functions, static methods and data members.
3252 unsigned InvalidDecl;
3253 bool ShowDeclName = true;
3254 if (!isFunc &&
3255 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3256 InvalidDecl = 0;
3257 else if (!isFunc)
3258 InvalidDecl = 1;
3259 else if (AS != AS_public)
3260 InvalidDecl = 2;
3261 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3262 InvalidDecl = 3;
3263 else switch (Name.getNameKind()) {
3264 case DeclarationName::CXXConstructorName:
3265 InvalidDecl = 4;
3266 ShowDeclName = false;
3267 break;
3268
3269 case DeclarationName::CXXDestructorName:
3270 InvalidDecl = 5;
3271 ShowDeclName = false;
3272 break;
3273
3274 case DeclarationName::CXXOperatorName:
3275 case DeclarationName::CXXConversionFunctionName:
3276 InvalidDecl = 6;
3277 break;
3278
3279 default:
3280 InvalidDecl = 0;
3281 break;
3282 }
3283
3284 if (InvalidDecl) {
3285 if (ShowDeclName)
3286 Diag(Loc, diag::err_invalid_member_in_interface)
3287 << (InvalidDecl-1) << Name;
3288 else
3289 Diag(Loc, diag::err_invalid_member_in_interface)
3290 << (InvalidDecl-1) << "";
3291 return nullptr;
3292 }
3293 }
3294
3295 // C++ 9.2p6: A member shall not be declared to have automatic storage
3296 // duration (auto, register) or with the extern storage-class-specifier.
3297 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3298 // data members and cannot be applied to names declared const or static,
3299 // and cannot be applied to reference members.
3300 switch (DS.getStorageClassSpec()) {
3301 case DeclSpec::SCS_unspecified:
3302 case DeclSpec::SCS_typedef:
3303 case DeclSpec::SCS_static:
3304 break;
3305 case DeclSpec::SCS_mutable:
3306 if (isFunc) {
3307 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3308
3309 // FIXME: It would be nicer if the keyword was ignored only for this
3310 // declarator. Otherwise we could get follow-up errors.
3311 D.getMutableDeclSpec().ClearStorageClassSpecs();
3312 }
3313 break;
3314 default:
3315 Diag(DS.getStorageClassSpecLoc(),
3316 diag::err_storageclass_invalid_for_member);
3317 D.getMutableDeclSpec().ClearStorageClassSpecs();
3318 break;
3319 }
3320
3321 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3322 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3323 !isFunc);
3324
3325 if (DS.hasConstexprSpecifier() && isInstField) {
3326 SemaDiagnosticBuilder B =
3327 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3328 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3329 if (InitStyle == ICIS_NoInit) {
3330 B << 0 << 0;
3331 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3332 B << FixItHint::CreateRemoval(ConstexprLoc);
3333 else {
3334 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3335 D.getMutableDeclSpec().ClearConstexprSpec();
3336 const char *PrevSpec;
3337 unsigned DiagID;
3338 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3339 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3340 (void)Failed;
3341 assert(!Failed && "Making a constexpr member const shouldn't fail")(static_cast<void> (0));
3342 }
3343 } else {
3344 B << 1;
3345 const char *PrevSpec;
3346 unsigned DiagID;
3347 if (D.getMutableDeclSpec().SetStorageClassSpec(
3348 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3349 Context.getPrintingPolicy())) {
3350 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&(static_cast<void> (0))
3351 "This is the only DeclSpec that should fail to be applied")(static_cast<void> (0));
3352 B << 1;
3353 } else {
3354 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3355 isInstField = false;
3356 }
3357 }
3358 }
3359
3360 NamedDecl *Member;
3361 if (isInstField) {
3362 CXXScopeSpec &SS = D.getCXXScopeSpec();
3363
3364 // Data members must have identifiers for names.
3365 if (!Name.isIdentifier()) {
3366 Diag(Loc, diag::err_bad_variable_name)
3367 << Name;
3368 return nullptr;
3369 }
3370
3371 IdentifierInfo *II = Name.getAsIdentifierInfo();
3372
3373 // Member field could not be with "template" keyword.
3374 // So TemplateParameterLists should be empty in this case.
3375 if (TemplateParameterLists.size()) {
3376 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3377 if (TemplateParams->size()) {
3378 // There is no such thing as a member field template.
3379 Diag(D.getIdentifierLoc(), diag::err_template_member)
3380 << II
3381 << SourceRange(TemplateParams->getTemplateLoc(),
3382 TemplateParams->getRAngleLoc());
3383 } else {
3384 // There is an extraneous 'template<>' for this member.
3385 Diag(TemplateParams->getTemplateLoc(),
3386 diag::err_template_member_noparams)
3387 << II
3388 << SourceRange(TemplateParams->getTemplateLoc(),
3389 TemplateParams->getRAngleLoc());
3390 }
3391 return nullptr;
3392 }
3393
3394 if (SS.isSet() && !SS.isInvalid()) {
3395 // The user provided a superfluous scope specifier inside a class
3396 // definition:
3397 //
3398 // class X {
3399 // int X::member;
3400 // };
3401 if (DeclContext *DC = computeDeclContext(SS, false))
3402 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc(),
3403 D.getName().getKind() ==
3404 UnqualifiedIdKind::IK_TemplateId);
3405 else
3406 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3407 << Name << SS.getRange();
3408
3409 SS.clear();
3410 }
3411
3412 if (MSPropertyAttr) {
3413 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3414 BitWidth, InitStyle, AS, *MSPropertyAttr);
3415 if (!Member)
3416 return nullptr;
3417 isInstField = false;
3418 } else {
3419 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3420 BitWidth, InitStyle, AS);
3421 if (!Member)
3422 return nullptr;
3423 }
3424
3425 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3426 } else {
3427 Member = HandleDeclarator(S, D, TemplateParameterLists);
3428 if (!Member)
3429 return nullptr;
3430
3431 // Non-instance-fields can't have a bitfield.
3432 if (BitWidth) {
3433 if (Member->isInvalidDecl()) {
3434 // don't emit another diagnostic.
3435 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3436 // C++ 9.6p3: A bit-field shall not be a static member.
3437 // "static member 'A' cannot be a bit-field"
3438 Diag(Loc, diag::err_static_not_bitfield)
3439 << Name << BitWidth->getSourceRange();
3440 } else if (isa<TypedefDecl>(Member)) {
3441 // "typedef member 'x' cannot be a bit-field"
3442 Diag(Loc, diag::err_typedef_not_bitfield)
3443 << Name << BitWidth->getSourceRange();
3444 } else {
3445 // A function typedef ("typedef int f(); f a;").
3446 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3447 Diag(Loc, diag::err_not_integral_type_bitfield)
3448 << Name << cast<ValueDecl>(Member)->getType()
3449 << BitWidth->getSourceRange();
3450 }
3451
3452 BitWidth = nullptr;
3453 Member->setInvalidDecl();
3454 }
3455
3456 NamedDecl *NonTemplateMember = Member;
3457 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3458 NonTemplateMember = FunTmpl->getTemplatedDecl();
3459 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3460 NonTemplateMember = VarTmpl->getTemplatedDecl();
3461
3462 Member->setAccess(AS);
3463
3464 // If we have declared a member function template or static data member
3465 // template, set the access of the templated declaration as well.
3466 if (NonTemplateMember != Member)
3467 NonTemplateMember->setAccess(AS);
3468
3469 // C++ [temp.deduct.guide]p3:
3470 // A deduction guide [...] for a member class template [shall be
3471 // declared] with the same access [as the template].
3472 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3473 auto *TD = DG->getDeducedTemplate();
3474 // Access specifiers are only meaningful if both the template and the
3475 // deduction guide are from the same scope.
3476 if (AS != TD->getAccess() &&
3477 TD->getDeclContext()->getRedeclContext()->Equals(
3478 DG->getDeclContext()->getRedeclContext())) {
3479 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3480 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3481 << TD->getAccess();
3482 const AccessSpecDecl *LastAccessSpec = nullptr;
3483 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3484 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3485 LastAccessSpec = AccessSpec;
3486 }
3487 assert(LastAccessSpec && "differing access with no access specifier")(static_cast<void> (0));
3488 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3489 << AS;
3490 }
3491 }
3492 }
3493
3494 if (VS.isOverrideSpecified())
3495 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc(),
3496 AttributeCommonInfo::AS_Keyword));
3497 if (VS.isFinalSpecified())
3498 Member->addAttr(FinalAttr::Create(
3499 Context, VS.getFinalLoc(), AttributeCommonInfo::AS_Keyword,
3500 static_cast<FinalAttr::Spelling>(VS.isFinalSpelledSealed())));
3501
3502 if (VS.getLastLocation().isValid()) {
3503 // Update the end location of a method that has a virt-specifiers.
3504 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3505 MD->setRangeEnd(VS.getLastLocation());
3506 }
3507
3508 CheckOverrideControl(Member);
3509
3510 assert((Name || isInstField) && "No identifier for non-field ?")(static_cast<void> (0));
3511
3512 if (isInstField) {
3513 FieldDecl *FD = cast<FieldDecl>(Member);
3514 FieldCollector->Add(FD);
3515
3516 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3517 // Remember all explicit private FieldDecls that have a name, no side
3518 // effects and are not part of a dependent type declaration.
3519 if (!FD->isImplicit() && FD->getDeclName() &&
3520 FD->getAccess() == AS_private &&
3521 !FD->hasAttr<UnusedAttr>() &&
3522 !FD->getParent()->isDependentContext() &&
3523 !InitializationHasSideEffects(*FD))
3524 UnusedPrivateFields.insert(FD);
3525 }
3526 }
3527
3528 return Member;
3529}
3530
3531namespace {
3532 class UninitializedFieldVisitor
3533 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3534 Sema &S;
3535 // List of Decls to generate a warning on. Also remove Decls that become
3536 // initialized.
3537 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3538 // List of base classes of the record. Classes are removed after their
3539 // initializers.
3540 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3541 // Vector of decls to be removed from the Decl set prior to visiting the
3542 // nodes. These Decls may have been initialized in the prior initializer.
3543 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3544 // If non-null, add a note to the warning pointing back to the constructor.
3545 const CXXConstructorDecl *Constructor;
3546 // Variables to hold state when processing an initializer list. When
3547 // InitList is true, special case initialization of FieldDecls matching
3548 // InitListFieldDecl.
3549 bool InitList;
3550 FieldDecl *InitListFieldDecl;
3551 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3552
3553 public:
3554 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3555 UninitializedFieldVisitor(Sema &S,
3556 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3557 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3558 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3559 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3560
3561 // Returns true if the use of ME is not an uninitialized use.
3562 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3563 bool CheckReferenceOnly) {
3564 llvm::SmallVector<FieldDecl*, 4> Fields;
3565 bool ReferenceField = false;
3566 while (ME) {
3567 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3568 if (!FD)
3569 return false;
3570 Fields.push_back(FD);
3571 if (FD->getType()->isReferenceType())
3572 ReferenceField = true;
3573 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3574 }
3575
3576 // Binding a reference to an uninitialized field is not an
3577 // uninitialized use.
3578 if (CheckReferenceOnly && !ReferenceField)
3579 return true;
3580
3581 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3582 // Discard the first field since it is the field decl that is being
3583 // initialized.
3584 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3585 UsedFieldIndex.push_back((*I)->getFieldIndex());
3586 }
3587
3588 for (auto UsedIter = UsedFieldIndex.begin(),
3589 UsedEnd = UsedFieldIndex.end(),
3590 OrigIter = InitFieldIndex.begin(),
3591 OrigEnd = InitFieldIndex.end();
3592 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3593 if (*UsedIter < *OrigIter)
3594 return true;
3595 if (*UsedIter > *OrigIter)
3596 break;
3597 }
3598
3599 return false;
3600 }
3601
3602 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3603 bool AddressOf) {
3604 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3605 return;
3606
3607 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3608 // or union.
3609 MemberExpr *FieldME = ME;
3610
3611 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3612
3613 Expr *Base = ME;
3614 while (MemberExpr *SubME =
3615 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3616
3617 if (isa<VarDecl>(SubME->getMemberDecl()))
3618 return;
3619
3620 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3621 if (!FD->isAnonymousStructOrUnion())
3622 FieldME = SubME;
3623
3624 if (!FieldME->getType().isPODType(S.Context))
3625 AllPODFields = false;
3626
3627 Base = SubME->getBase();
3628 }
3629
3630 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3631 Visit(Base);
3632 return;
3633 }
3634
3635 if (AddressOf && AllPODFields)
3636 return;
3637
3638 ValueDecl* FoundVD = FieldME->getMemberDecl();
3639
3640 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3641 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3642 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3643 }
3644
3645 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3646 QualType T = BaseCast->getType();
3647 if (T->isPointerType() &&
3648 BaseClasses.count(T->getPointeeType())) {
3649 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3650 << T->getPointeeType() << FoundVD;
3651 }
3652 }
3653 }
3654
3655 if (!Decls.count(FoundVD))
3656 return;
3657
3658 const bool IsReference = FoundVD->getType()->isReferenceType();
3659
3660 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3661 // Special checking for initializer lists.
3662 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3663 return;
3664 }
3665 } else {
3666 // Prevent double warnings on use of unbounded references.
3667 if (CheckReferenceOnly && !IsReference)
3668 return;
3669 }
3670
3671 unsigned diag = IsReference
3672 ? diag::warn_reference_field_is_uninit
3673 : diag::warn_field_is_uninit;
3674 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3675 if (Constructor)
3676 S.Diag(Constructor->getLocation(),
3677 diag::note_uninit_in_this_constructor)
3678 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3679
3680 }
3681
3682 void HandleValue(Expr *E, bool AddressOf) {
3683 E = E->IgnoreParens();
3684
3685 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3686 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3687 AddressOf /*AddressOf*/);
3688 return;
3689 }
3690
3691 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3692 Visit(CO->getCond());
3693 HandleValue(CO->getTrueExpr(), AddressOf);
3694 HandleValue(CO->getFalseExpr(), AddressOf);
3695 return;
3696 }
3697
3698 if (BinaryConditionalOperator *BCO =
3699 dyn_cast<BinaryConditionalOperator>(E)) {
3700 Visit(BCO->getCond());
3701 HandleValue(BCO->getFalseExpr(), AddressOf);
3702 return;
3703 }
3704
3705 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3706 HandleValue(OVE->getSourceExpr(), AddressOf);
3707 return;
3708 }
3709
3710 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3711 switch (BO->getOpcode()) {
3712 default:
3713 break;
3714 case(BO_PtrMemD):
3715 case(BO_PtrMemI):
3716 HandleValue(BO->getLHS(), AddressOf);
3717 Visit(BO->getRHS());
3718 return;
3719 case(BO_Comma):
3720 Visit(BO->getLHS());
3721 HandleValue(BO->getRHS(), AddressOf);
3722 return;
3723 }
3724 }
3725
3726 Visit(E);
3727 }
3728
3729 void CheckInitListExpr(InitListExpr *ILE) {
3730 InitFieldIndex.push_back(0);
3731 for (auto Child : ILE->children()) {
3732 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3733 CheckInitListExpr(SubList);
3734 } else {
3735 Visit(Child);
3736 }
3737 ++InitFieldIndex.back();
3738 }
3739 InitFieldIndex.pop_back();
3740 }
3741
3742 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3743 FieldDecl *Field, const Type *BaseClass) {
3744 // Remove Decls that may have been initialized in the previous
3745 // initializer.
3746 for (ValueDecl* VD : DeclsToRemove)
3747 Decls.erase(VD);
3748 DeclsToRemove.clear();
3749
3750 Constructor = FieldConstructor;
3751 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3752
3753 if (ILE && Field) {
3754 InitList = true;
3755 InitListFieldDecl = Field;
3756 InitFieldIndex.clear();
3757 CheckInitListExpr(ILE);
3758 } else {
3759 InitList = false;
3760 Visit(E);
3761 }
3762
3763 if (Field)
3764 Decls.erase(Field);
3765 if (BaseClass)
3766 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3767 }
3768
3769 void VisitMemberExpr(MemberExpr *ME) {
3770 // All uses of unbounded reference fields will warn.
3771 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3772 }
3773
3774 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3775 if (E->getCastKind() == CK_LValueToRValue) {
3776 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3777 return;
3778 }
3779
3780 Inherited::VisitImplicitCastExpr(E);
3781 }
3782
3783 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3784 if (E->getConstructor()->isCopyConstructor()) {
3785 Expr *ArgExpr = E->getArg(0);
3786 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3787 if (ILE->getNumInits() == 1)
3788 ArgExpr = ILE->getInit(0);
3789 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3790 if (ICE->getCastKind() == CK_NoOp)
3791 ArgExpr = ICE->getSubExpr();
3792 HandleValue(ArgExpr, false /*AddressOf*/);
3793 return;
3794 }
3795 Inherited::VisitCXXConstructExpr(E);
3796 }
3797
3798 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3799 Expr *Callee = E->getCallee();
3800 if (isa<MemberExpr>(Callee)) {
3801 HandleValue(Callee, false /*AddressOf*/);
3802 for (auto Arg : E->arguments())
3803 Visit(Arg);
3804 return;
3805 }
3806
3807 Inherited::VisitCXXMemberCallExpr(E);
3808 }
3809
3810 void VisitCallExpr(CallExpr *E) {
3811 // Treat std::move as a use.
3812 if (E->isCallToStdMove()) {
3813 HandleValue(E->getArg(0), /*AddressOf=*/false);
3814 return;
3815 }
3816
3817 Inherited::VisitCallExpr(E);
3818 }
3819
3820 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3821 Expr *Callee = E->getCallee();
3822
3823 if (isa<UnresolvedLookupExpr>(Callee))
3824 return Inherited::VisitCXXOperatorCallExpr(E);
3825
3826 Visit(Callee);
3827 for (auto Arg : E->arguments())
3828 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3829 }
3830
3831 void VisitBinaryOperator(BinaryOperator *E) {
3832 // If a field assignment is detected, remove the field from the
3833 // uninitiailized field set.
3834 if (E->getOpcode() == BO_Assign)
3835 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3836 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3837 if (!FD->getType()->isReferenceType())
3838 DeclsToRemove.push_back(FD);
3839
3840 if (E->isCompoundAssignmentOp()) {
3841 HandleValue(E->getLHS(), false /*AddressOf*/);
3842 Visit(E->getRHS());
3843 return;
3844 }
3845
3846 Inherited::VisitBinaryOperator(E);
3847 }
3848
3849 void VisitUnaryOperator(UnaryOperator *E) {
3850 if (E->isIncrementDecrementOp()) {
3851 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3852 return;
3853 }
3854 if (E->getOpcode() == UO_AddrOf) {
3855 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3856 HandleValue(ME->getBase(), true /*AddressOf*/);
3857 return;
3858 }
3859 }
3860
3861 Inherited::VisitUnaryOperator(E);
3862 }
3863 };
3864
3865 // Diagnose value-uses of fields to initialize themselves, e.g.
3866 // foo(foo)
3867 // where foo is not also a parameter to the constructor.
3868 // Also diagnose across field uninitialized use such as
3869 // x(y), y(x)
3870 // TODO: implement -Wuninitialized and fold this into that framework.
3871 static void DiagnoseUninitializedFields(
3872 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3873
3874 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3875 Constructor->getLocation())) {
3876 return;
3877 }
3878
3879 if (Constructor->isInvalidDecl())
3880 return;
3881
3882 const CXXRecordDecl *RD = Constructor->getParent();
3883
3884 if (RD->isDependentContext())
3885 return;
3886
3887 // Holds fields that are uninitialized.
3888 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3889
3890 // At the beginning, all fields are uninitialized.
3891 for (auto *I : RD->decls()) {
3892 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3893 UninitializedFields.insert(FD);
3894 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3895 UninitializedFields.insert(IFD->getAnonField());
3896 }
3897 }
3898
3899 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3900 for (auto I : RD->bases())
3901 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3902
3903 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3904 return;
3905
3906 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3907 UninitializedFields,
3908 UninitializedBaseClasses);
3909
3910 for (const auto *FieldInit : Constructor->inits()) {
3911 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3912 break;
3913
3914 Expr *InitExpr = FieldInit->getInit();
3915 if (!InitExpr)
3916 continue;
3917
3918 if (CXXDefaultInitExpr *Default =
3919 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3920 InitExpr = Default->getExpr();
3921 if (!InitExpr)
3922 continue;
3923 // In class initializers will point to the constructor.
3924 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3925 FieldInit->getAnyMember(),
3926 FieldInit->getBaseClass());
3927 } else {
3928 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3929 FieldInit->getAnyMember(),
3930 FieldInit->getBaseClass());
3931 }
3932 }
3933 }
3934} // namespace
3935
3936/// Enter a new C++ default initializer scope. After calling this, the
3937/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3938/// parsing or instantiating the initializer failed.
3939void Sema::ActOnStartCXXInClassMemberInitializer() {
3940 // Create a synthetic function scope to represent the call to the constructor
3941 // that notionally surrounds a use of this initializer.
3942 PushFunctionScope();
3943}
3944
3945void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
3946 if (!D.isFunctionDeclarator())
3947 return;
3948 auto &FTI = D.getFunctionTypeInfo();
3949 if (!FTI.Params)
3950 return;
3951 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
3952 FTI.NumParams)) {
3953 auto *ParamDecl = cast<NamedDecl>(Param.Param);
3954 if (ParamDecl->getDeclName())
3955 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
3956 }
3957}
3958
3959ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
3960 return ActOnRequiresClause(ConstraintExpr);
3961}
3962
3963ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
3964 if (ConstraintExpr.isInvalid())
3965 return ExprError();
3966
3967 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
3968 if (ConstraintExpr.isInvalid())
3969 return ExprError();
3970
3971 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
3972 UPPC_RequiresClause))
3973 return ExprError();
3974
3975 return ConstraintExpr;
3976}
3977
3978/// This is invoked after parsing an in-class initializer for a
3979/// non-static C++ class member, and after instantiating an in-class initializer
3980/// in a class template. Such actions are deferred until the class is complete.
3981void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3982 SourceLocation InitLoc,
3983 Expr *InitExpr) {
3984 // Pop the notional constructor scope we created earlier.
3985 PopFunctionScopeInfo(nullptr, D);
3986
3987 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3988 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&(static_cast<void> (0))
3989 "must set init style when field is created")(static_cast<void> (0));
3990
3991 if (!InitExpr) {
3992 D->setInvalidDecl();
3993 if (FD)
3994 FD->removeInClassInitializer();
3995 return;
3996 }
3997
3998 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3999 FD->setInvalidDecl();
4000 FD->removeInClassInitializer();
4001 return;
4002 }
4003
4004 ExprResult Init = InitExpr;
4005 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
4006 InitializedEntity Entity =
4007 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(FD);
4008 InitializationKind Kind =
4009 FD->getInClassInitStyle() == ICIS_ListInit
4010 ? InitializationKind::CreateDirectList(InitExpr->getBeginLoc(),
4011 InitExpr->getBeginLoc(),
4012 InitExpr->getEndLoc())
4013 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4014 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4015 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
4016 if (Init.isInvalid()) {
4017 FD->setInvalidDecl();
4018 return;
4019 }
4020 }
4021
4022 // C++11 [class.base.init]p7:
4023 // The initialization of each base and member constitutes a
4024 // full-expression.
4025 Init = ActOnFinishFullExpr(Init.get(), InitLoc, /*DiscardedValue*/ false);
4026 if (Init.isInvalid()) {
4027 FD->setInvalidDecl();
4028 return;
4029 }
4030
4031 InitExpr = Init.get();
4032
4033 FD->setInClassInitializer(InitExpr);
4034}
4035
4036/// Find the direct and/or virtual base specifiers that
4037/// correspond to the given base type, for use in base initialization
4038/// within a constructor.
4039static bool FindBaseInitializer(Sema &SemaRef,
4040 CXXRecordDecl *ClassDecl,
4041 QualType BaseType,
4042 const CXXBaseSpecifier *&DirectBaseSpec,
4043 const CXXBaseSpecifier *&VirtualBaseSpec) {
4044 // First, check for a direct base class.
4045 DirectBaseSpec = nullptr;
4046 for (const auto &Base : ClassDecl->bases()) {
4047 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4048 // We found a direct base of this type. That's what we're
4049 // initializing.
4050 DirectBaseSpec = &Base;
4051 break;
4052 }
4053 }
4054
4055 // Check for a virtual base class.
4056 // FIXME: We might be able to short-circuit this if we know in advance that
4057 // there are no virtual bases.
4058 VirtualBaseSpec = nullptr;
4059 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4060 // We haven't found a base yet; search the class hierarchy for a
4061 // virtual base class.
4062 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4063 /*DetectVirtual=*/false);
4064 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4065 SemaRef.Context.getTypeDeclType(ClassDecl),
4066 BaseType, Paths)) {
4067 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4068 Path != Paths.end(); ++Path) {
4069 if (Path->back().Base->isVirtual()) {
4070 VirtualBaseSpec = Path->back().Base;
4071 break;
4072 }
4073 }
4074 }
4075 }
4076
4077 return DirectBaseSpec || VirtualBaseSpec;
4078}
4079
4080/// Handle a C++ member initializer using braced-init-list syntax.
4081MemInitResult
4082Sema::ActOnMemInitializer(Decl *ConstructorD,
4083 Scope *S,
4084 CXXScopeSpec &SS,
4085 IdentifierInfo *MemberOrBase,
4086 ParsedType TemplateTypeTy,
4087 const DeclSpec &DS,
4088 SourceLocation IdLoc,
4089 Expr *InitList,
4090 SourceLocation EllipsisLoc) {
4091 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
1
Calling 'Sema::BuildMemInitializer'
4092 DS, IdLoc, InitList,
4093 EllipsisLoc);
4094}
4095
4096/// Handle a C++ member initializer using parentheses syntax.
4097MemInitResult
4098Sema::ActOnMemInitializer(Decl *ConstructorD,
4099 Scope *S,
4100 CXXScopeSpec &SS,
4101 IdentifierInfo *MemberOrBase,
4102 ParsedType TemplateTypeTy,
4103 const DeclSpec &DS,
4104 SourceLocation IdLoc,
4105 SourceLocation LParenLoc,
4106 ArrayRef<Expr *> Args,
4107 SourceLocation RParenLoc,
4108 SourceLocation EllipsisLoc) {
4109 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4110 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4111 DS, IdLoc, List, EllipsisLoc);
4112}
4113
4114namespace {
4115
4116// Callback to only accept typo corrections that can be a valid C++ member
4117// intializer: either a non-static field member or a base class.
4118class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4119public:
4120 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4121 : ClassDecl(ClassDecl) {}
4122
4123 bool ValidateCandidate(const TypoCorrection &candidate) override {
4124 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4125 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4126 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4127 return isa<TypeDecl>(ND);
4128 }
4129 return false;
4130 }
4131
4132 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4133 return std::make_unique<MemInitializerValidatorCCC>(*this);
4134 }
4135
4136private:
4137 CXXRecordDecl *ClassDecl;
4138};
4139
4140}
4141
4142ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4143 CXXScopeSpec &SS,
4144 ParsedType TemplateTypeTy,
4145 IdentifierInfo *MemberOrBase) {
4146 if (SS.getScopeRep() || TemplateTypeTy)
4147 return nullptr;
4148 for (auto *D : ClassDecl->lookup(MemberOrBase))
4149 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
4150 return cast<ValueDecl>(D);
4151 return nullptr;
4152}
4153
4154/// Handle a C++ member initializer.
4155MemInitResult
4156Sema::BuildMemInitializer(Decl *ConstructorD,
4157 Scope *S,
4158 CXXScopeSpec &SS,
4159 IdentifierInfo *MemberOrBase,
4160 ParsedType TemplateTypeTy,
4161 const DeclSpec &DS,
4162 SourceLocation IdLoc,
4163 Expr *Init,
4164 SourceLocation EllipsisLoc) {
4165 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4166 /*RecoverUncorrectedTypos=*/true);
4167 if (!Res.isUsable())
2
Calling 'ActionResult::isUsable'
5
Returning from 'ActionResult::isUsable'
6
Taking false branch
4168 return true;
4169 Init = Res.get();
4170
4171 if (!ConstructorD)
7
Assuming 'ConstructorD' is non-null
8
Taking false branch
4172 return true;
4173
4174 AdjustDeclIfTemplate(ConstructorD);
4175
4176 CXXConstructorDecl *Constructor
4177 = dyn_cast<CXXConstructorDecl>(ConstructorD);
9
Assuming 'ConstructorD' is a 'CXXConstructorDecl'
4178 if (!Constructor
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
9.1
'Constructor' is non-null
) {
10
Taking false branch
4179 // The user wrote a constructor initializer on a function that is
4180 // not a C++ constructor. Ignore the error for now, because we may
4181 // have more member initializers coming; we'll diagnose it just
4182 // once in ActOnMemInitializers.
4183 return true;
4184 }
4185
4186 CXXRecordDecl *ClassDecl = Constructor->getParent();
4187
4188 // C++ [class.base.init]p2:
4189 // Names in a mem-initializer-id are looked up in the scope of the
4190 // constructor's class and, if not found in that scope, are looked
4191 // up in the scope containing the constructor's definition.
4192 // [Note: if the constructor's class contains a member with the
4193 // same name as a direct or virtual base class of the class, a
4194 // mem-initializer-id naming the member or base class and composed
4195 // of a single identifier refers to the class member. A
4196 // mem-initializer-id for the hidden base class may be specified
4197 // using a qualified name. ]
4198
4199 // Look for a member, first.
4200 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
11
Assuming 'Member' is null
12
Taking false branch
4201 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4202 if (EllipsisLoc.isValid())
4203 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4204 << MemberOrBase
4205 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4206
4207 return BuildMemberInitializer(Member, Init, IdLoc);
4208 }
4209 // It didn't name a member, so see if it names a class.
4210 QualType BaseType;
4211 TypeSourceInfo *TInfo = nullptr;
4212
4213 if (TemplateTypeTy) {
13
Calling 'OpaquePtr::operator bool'
16
Returning from 'OpaquePtr::operator bool'
17
Taking false branch
4214 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4215 if (BaseType.isNull())
4216 return true;
4217 } else if (DS.getTypeSpecType() == TST_decltype) {
18
Assuming the condition is false
19
Taking false branch
4218 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
4219 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
20
Assuming the condition is false
21
Taking false branch
4220 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4221 return true;
4222 } else {
4223 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4224 LookupParsedName(R, S, &SS);
4225
4226 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
22
'TyD' initialized here
4227 if (!TyD) {
23
Assuming 'TyD' is null
24
Taking true branch
4228 if (R.isAmbiguous()) return true;
25
Assuming the condition is false
26
Taking false branch
4229
4230 // We don't want access-control diagnostics here.
4231 R.suppressDiagnostics();
4232
4233 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
27
Calling 'CXXScopeSpec::isSet'
30
Returning from 'CXXScopeSpec::isSet'
31
Assuming the condition is true
32
Taking true branch
4234 bool NotUnknownSpecialization = false;
4235 DeclContext *DC = computeDeclContext(SS, false);
4236 if (CXXRecordDecl *Record
33.1
'Record' is null
33.1
'Record' is null
33.1
'Record' is null
33.1
'Record' is null
33.1
'Record' is null
33.1
'Record' is null
= dyn_cast_or_null<CXXRecordDecl>(DC))
33
Assuming null pointer is passed into cast
34
Taking false branch
4237 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4238
4239 if (!NotUnknownSpecialization
34.1
'NotUnknownSpecialization' is false
34.1
'NotUnknownSpecialization' is false
34.1
'NotUnknownSpecialization' is false
34.1
'NotUnknownSpecialization' is false
34.1
'NotUnknownSpecialization' is false
34.1
'NotUnknownSpecialization' is false
) {
35
Taking true branch
4240 // When the scope specifier can refer to a member of an unknown
4241 // specialization, we take it as a type name.
4242 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
4243 SS.getWithLocInContext(Context),
4244 *MemberOrBase, IdLoc);
4245 if (BaseType.isNull())
36
Calling 'QualType::isNull'
42
Returning from 'QualType::isNull'
43
Taking false branch
4246 return true;
4247
4248 TInfo = Context.CreateTypeSourceInfo(BaseType);
4249 DependentNameTypeLoc TL =
4250 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4251 if (!TL.isNull()) {
44
Taking true branch
4252 TL.setNameLoc(IdLoc);
4253 TL.setElaboratedKeywordLoc(SourceLocation());
4254 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4255 }
4256
4257 R.clear();
4258 R.setLookupName(MemberOrBase);
4259 }
4260 }
4261
4262 // If no results were found, try to correct typos.
4263 TypoCorrection Corr;
4264 MemInitializerValidatorCCC CCC(ClassDecl);
4265 if (R.empty() && BaseType.isNull() &&
45
Assuming the condition is false
4266 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4267 CCC, CTK_ErrorRecovery, ClassDecl))) {
4268 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4269 // We have found a non-static data member with a similar
4270 // name to what was typed; complain and initialize that
4271 // member.
4272 diagnoseTypo(Corr,
4273 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4274 << MemberOrBase << true);
4275 return BuildMemberInitializer(Member, Init, IdLoc);
4276 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4277 const CXXBaseSpecifier *DirectBaseSpec;
4278 const CXXBaseSpecifier *VirtualBaseSpec;
4279 if (FindBaseInitializer(*this, ClassDecl,
4280 Context.getTypeDeclType(Type),
4281 DirectBaseSpec, VirtualBaseSpec)) {
4282 // We have found a direct or virtual base class with a
4283 // similar name to what was typed; complain and initialize
4284 // that base class.
4285 diagnoseTypo(Corr,
4286 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4287 << MemberOrBase << false,
4288 PDiag() /*Suppress note, we provide our own.*/);
4289
4290 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4291 : VirtualBaseSpec;
4292 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4293 << BaseSpec->getType() << BaseSpec->getSourceRange();
4294
4295 TyD = Type;
4296 }
4297 }
4298 }
4299
4300 if (!TyD
45.1
'TyD' is null
45.1
'TyD' is null
45.1
'TyD' is null
45.1
'TyD' is null
45.1
'TyD' is null
45.1
'TyD' is null
&& BaseType.isNull()) {
46
Calling 'QualType::isNull'
52
Returning from 'QualType::isNull'
53
Taking false branch
4301 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4302 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4303 return true;
4304 }
4305 }
4306
4307 if (BaseType.isNull()) {
54
Calling 'QualType::isNull'
60
Returning from 'QualType::isNull'
61
Taking true branch
4308 BaseType = Context.getTypeDeclType(TyD);
62
Passing null pointer value via 1st parameter 'Decl'
63
Calling 'ASTContext::getTypeDeclType'
4309 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4310 if (SS.isSet()) {
4311 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
4312 BaseType);
4313 TInfo = Context.CreateTypeSourceInfo(BaseType);
4314 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
4315 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4316 TL.setElaboratedKeywordLoc(SourceLocation());
4317 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4318 }
4319 }
4320 }
4321
4322 if (!TInfo)
4323 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4324
4325 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4326}
4327
4328MemInitResult
4329Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4330 SourceLocation IdLoc) {
4331 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4332 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4333 assert((DirectMember || IndirectMember) &&(static_cast<void> (0))
4334 "Member must be a FieldDecl or IndirectFieldDecl")(static_cast<void> (0));
4335
4336 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4337 return true;
4338
4339 if (Member->isInvalidDecl())
4340 return true;
4341
4342 MultiExprArg Args;
4343 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4344 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4345 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4346 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4347 } else {
4348 // Template instantiation doesn't reconstruct ParenListExprs for us.
4349 Args = Init;
4350 }
4351
4352 SourceRange InitRange = Init->getSourceRange();
4353
4354 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4355 // Can't check initialization for a member of dependent type or when
4356 // any of the arguments are type-dependent expressions.
4357 DiscardCleanupsInEvaluationContext();
4358 } else {
4359 bool InitList = false;
4360 if (isa<InitListExpr>(Init)) {
4361 InitList = true;
4362 Args = Init;
4363 }
4364
4365 // Initialize the member.
4366 InitializedEntity MemberEntity =
4367 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4368 : InitializedEntity::InitializeMember(IndirectMember,
4369 nullptr);
4370 InitializationKind Kind =
4371 InitList ? InitializationKind::CreateDirectList(
4372 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4373 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4374 InitRange.getEnd());
4375
4376 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4377 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4378 nullptr);
4379 if (!MemberInit.isInvalid()) {
4380 // C++11 [class.base.init]p7:
4381 // The initialization of each base and member constitutes a
4382 // full-expression.
4383 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4384 /*DiscardedValue*/ false);
4385 }
4386
4387 if (MemberInit.isInvalid()) {
4388 // Args were sensible expressions but we couldn't initialize the member
4389 // from them. Preserve them in a RecoveryExpr instead.
4390 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4391 Member->getType())
4392 .get();
4393 if (!Init)
4394 return true;
4395 } else {
4396 Init = MemberInit.get();
4397 }
4398 }
4399
4400 if (DirectMember) {
4401 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4402 InitRange.getBegin(), Init,
4403 InitRange.getEnd());
4404 } else {
4405 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4406 InitRange.getBegin(), Init,
4407 InitRange.getEnd());
4408 }
4409}
4410
4411MemInitResult
4412Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4413 CXXRecordDecl *ClassDecl) {
4414 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4415 if (!LangOpts.CPlusPlus11)
4416 return Diag(NameLoc, diag::err_delegating_ctor)
4417 << TInfo->getTypeLoc().getLocalSourceRange();
4418 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4419
4420 bool InitList = true;
4421 MultiExprArg Args = Init;
4422 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4423 InitList = false;
4424 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4425 }
4426
4427 SourceRange InitRange = Init->getSourceRange();
4428 // Initialize the object.
4429 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4430 QualType(ClassDecl->getTypeForDecl(), 0));
4431 InitializationKind Kind =
4432 InitList ? InitializationKind::CreateDirectList(
4433 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4434 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4435 InitRange.getEnd());
4436 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4437 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4438 Args, nullptr);
4439 if (!DelegationInit.isInvalid()) {
4440 assert((DelegationInit.get()->containsErrors() ||(static_cast<void> (0))
4441 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&(static_cast<void> (0))
4442 "Delegating constructor with no target?")(static_cast<void> (0));
4443
4444 // C++11 [class.base.init]p7:
4445 // The initialization of each base and member constitutes a
4446 // full-expression.
4447 DelegationInit = ActOnFinishFullExpr(
4448 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4449 }
4450
4451 if (DelegationInit.isInvalid()) {
4452 DelegationInit =
4453 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4454 QualType(ClassDecl->getTypeForDecl(), 0));
4455 if (DelegationInit.isInvalid())
4456 return true;
4457 } else {
4458 // If we are in a dependent context, template instantiation will
4459 // perform this type-checking again. Just save the arguments that we
4460 // received in a ParenListExpr.
4461 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4462 // of the information that we have about the base
4463 // initializer. However, deconstructing the ASTs is a dicey process,
4464 // and this approach is far more likely to get the corner cases right.
4465 if (CurContext->isDependentContext())
4466 DelegationInit = Init;
4467 }
4468
4469 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4470 DelegationInit.getAs<Expr>(),
4471 InitRange.getEnd());
4472}
4473
4474MemInitResult
4475Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4476 Expr *Init, CXXRecordDecl *ClassDecl,
4477 SourceLocation EllipsisLoc) {
4478 SourceLocation BaseLoc
4479 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4480
4481 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4482 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4483 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4484
4485 // C++ [class.base.init]p2:
4486 // [...] Unless the mem-initializer-id names a nonstatic data
4487 // member of the constructor's class or a direct or virtual base
4488 // of that class, the mem-initializer is ill-formed. A
4489 // mem-initializer-list can initialize a base class using any
4490 // name that denotes that base class type.
4491
4492 // We can store the initializers in "as-written" form and delay analysis until
4493 // instantiation if the constructor is dependent. But not for dependent
4494 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4495 bool Dependent = CurContext->isDependentContext() &&
4496 (BaseType->isDependentType() || Init->isTypeDependent());
4497
4498 SourceRange InitRange = Init->getSourceRange();
4499 if (EllipsisLoc.isValid()) {
4500 // This is a pack expansion.
4501 if (!BaseType->containsUnexpandedParameterPack()) {
4502 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4503 << SourceRange(BaseLoc, InitRange.getEnd());
4504
4505 EllipsisLoc = SourceLocation();
4506 }
4507 } else {
4508 // Check for any unexpanded parameter packs.
4509 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4510 return true;
4511
4512 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4513 return true;
4514 }
4515
4516 // Check for direct and virtual base classes.
4517 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4518 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4519 if (!Dependent) {
4520 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4521 BaseType))
4522 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4523
4524 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4525 VirtualBaseSpec);
4526
4527 // C++ [base.class.init]p2:
4528 // Unless the mem-initializer-id names a nonstatic data member of the
4529 // constructor's class or a direct or virtual base of that class, the
4530 // mem-initializer is ill-formed.
4531 if (!DirectBaseSpec && !VirtualBaseSpec) {
4532 // If the class has any dependent bases, then it's possible that
4533 // one of those types will resolve to the same type as
4534 // BaseType. Therefore, just treat this as a dependent base
4535 // class initialization. FIXME: Should we try to check the
4536 // initialization anyway? It seems odd.
4537 if (ClassDecl->hasAnyDependentBases())
4538 Dependent = true;
4539 else
4540 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4541 << BaseType << Context.getTypeDeclType(ClassDecl)
4542 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4543 }
4544 }
4545
4546 if (Dependent) {
4547 DiscardCleanupsInEvaluationContext();
4548
4549 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4550 /*IsVirtual=*/false,
4551 InitRange.getBegin(), Init,
4552 InitRange.getEnd(), EllipsisLoc);
4553 }
4554
4555 // C++ [base.class.init]p2:
4556 // If a mem-initializer-id is ambiguous because it designates both
4557 // a direct non-virtual base class and an inherited virtual base
4558 // class, the mem-initializer is ill-formed.
4559 if (DirectBaseSpec && VirtualBaseSpec)
4560 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4561 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4562
4563 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4564 if (!BaseSpec)
4565 BaseSpec = VirtualBaseSpec;
4566
4567 // Initialize the base.
4568 bool InitList = true;
4569 MultiExprArg Args = Init;
4570 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4571 InitList = false;
4572 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4573 }
4574
4575 InitializedEntity BaseEntity =
4576 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4577 InitializationKind Kind =
4578 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4579 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4580 InitRange.getEnd());
4581 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4582 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4583 if (!BaseInit.isInvalid()) {
4584 // C++11 [class.base.init]p7:
4585 // The initialization of each base and member constitutes a
4586 // full-expression.
4587 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4588 /*DiscardedValue*/ false);
4589 }
4590
4591 if (BaseInit.isInvalid()) {
4592 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4593 Args, BaseType);
4594 if (BaseInit.isInvalid())
4595 return true;
4596 } else {
4597 // If we are in a dependent context, template instantiation will
4598 // perform this type-checking again. Just save the arguments that we
4599 // received in a ParenListExpr.
4600 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4601 // of the information that we have about the base
4602 // initializer. However, deconstructing the ASTs is a dicey process,
4603 // and this approach is far more likely to get the corner cases right.
4604 if (CurContext->isDependentContext())
4605 BaseInit = Init;
4606 }
4607
4608 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4609 BaseSpec->isVirtual(),
4610 InitRange.getBegin(),
4611 BaseInit.getAs<Expr>(),
4612 InitRange.getEnd(), EllipsisLoc);
4613}
4614
4615// Create a static_cast\<T&&>(expr).
4616static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4617 if (T.isNull()) T = E->getType();
4618 QualType TargetType = SemaRef.BuildReferenceType(
4619 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4620 SourceLocation ExprLoc = E->getBeginLoc();
4621 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4622 TargetType, ExprLoc);
4623
4624 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4625 SourceRange(ExprLoc, ExprLoc),
4626 E->getSourceRange()).get();
4627}
4628
4629/// ImplicitInitializerKind - How an implicit base or member initializer should
4630/// initialize its base or member.
4631enum ImplicitInitializerKind {
4632 IIK_Default,
4633 IIK_Copy,
4634 IIK_Move,
4635 IIK_Inherit
4636};
4637
4638static bool
4639BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4640 ImplicitInitializerKind ImplicitInitKind,
4641 CXXBaseSpecifier *BaseSpec,
4642 bool IsInheritedVirtualBase,
4643 CXXCtorInitializer *&CXXBaseInit) {
4644 InitializedEntity InitEntity
4645 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4646 IsInheritedVirtualBase);
4647
4648 ExprResult BaseInit;
4649
4650 switch (ImplicitInitKind) {
4651 case IIK_Inherit:
4652 case IIK_Default: {
4653 InitializationKind InitKind
4654 = InitializationKind::CreateDefault(Constructor->getLocation());
4655 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4656 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4657 break;
4658 }
4659
4660 case IIK_Move:
4661 case IIK_Copy: {
4662 bool Moving = ImplicitInitKind == IIK_Move;
4663 ParmVarDecl *Param = Constructor->getParamDecl(0);
4664 QualType ParamType = Param->getType().getNonReferenceType();
4665
4666 Expr *CopyCtorArg =
4667 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4668 SourceLocation(), Param, false,
4669 Constructor->getLocation(), ParamType,
4670 VK_LValue, nullptr);
4671
4672 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4673
4674 // Cast to the base class to avoid ambiguities.
4675 QualType ArgTy =
4676 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4677 ParamType.getQualifiers());
4678
4679 if (Moving) {
4680 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4681 }
4682
4683 CXXCastPath BasePath;
4684 BasePath.push_back(BaseSpec);
4685 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4686 CK_UncheckedDerivedToBase,
4687 Moving ? VK_XValue : VK_LValue,
4688 &BasePath).get();
4689
4690 InitializationKind InitKind
4691 = InitializationKind::CreateDirect(Constructor->getLocation(),
4692 SourceLocation(), SourceLocation());
4693 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4694 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4695 break;
4696 }
4697 }
4698
4699 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4700 if (BaseInit.isInvalid())
4701 return true;
4702
4703 CXXBaseInit =
4704 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4705 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4706 SourceLocation()),
4707 BaseSpec->isVirtual(),
4708 SourceLocation(),
4709 BaseInit.getAs<Expr>(),
4710 SourceLocation(),
4711 SourceLocation());
4712
4713 return false;
4714}
4715
4716static bool RefersToRValueRef(Expr *MemRef) {
4717 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4718 return Referenced->getType()->isRValueReferenceType();
4719}
4720
4721static bool
4722BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4723 ImplicitInitializerKind ImplicitInitKind,
4724 FieldDecl *Field, IndirectFieldDecl *Indirect,
4725 CXXCtorInitializer *&CXXMemberInit) {
4726 if (Field->isInvalidDecl())
4727 return true;
4728
4729 SourceLocation Loc = Constructor->getLocation();
4730
4731 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4732 bool Moving = ImplicitInitKind == IIK_Move;
4733 ParmVarDecl *Param = Constructor->getParamDecl(0);
4734 QualType ParamType = Param->getType().getNonReferenceType();
4735
4736 // Suppress copying zero-width bitfields.
4737 if (Field->isZeroLengthBitField(SemaRef.Context))
4738 return false;
4739
4740 Expr *MemberExprBase =
4741 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4742 SourceLocation(), Param, false,
4743 Loc, ParamType, VK_LValue, nullptr);
4744
4745 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4746
4747 if (Moving) {
4748 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4749 }
4750
4751 // Build a reference to this field within the parameter.
4752 CXXScopeSpec SS;
4753 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4754 Sema::LookupMemberName);
4755 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4756 : cast<ValueDecl>(Field), AS_public);
4757 MemberLookup.resolveKind();
4758 ExprResult CtorArg
4759 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4760 ParamType, Loc,
4761 /*IsArrow=*/false,
4762 SS,
4763 /*TemplateKWLoc=*/SourceLocation(),
4764 /*FirstQualifierInScope=*/nullptr,
4765 MemberLookup,
4766 /*TemplateArgs=*/nullptr,
4767 /*S*/nullptr);
4768 if (CtorArg.isInvalid())
4769 return true;
4770
4771 // C++11 [class.copy]p15:
4772 // - if a member m has rvalue reference type T&&, it is direct-initialized
4773 // with static_cast<T&&>(x.m);
4774 if (RefersToRValueRef(CtorArg.get())) {
4775 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4776 }
4777
4778 InitializedEntity Entity =
4779 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4780 /*Implicit*/ true)
4781 : InitializedEntity::InitializeMember(Field, nullptr,
4782 /*Implicit*/ true);
4783
4784 // Direct-initialize to use the copy constructor.
4785 InitializationKind InitKind =
4786 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4787
4788 Expr *CtorArgE = CtorArg.getAs<Expr>();
4789 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4790 ExprResult MemberInit =
4791 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4792 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4793 if (MemberInit.isInvalid())
4794 return true;
4795
4796 if (Indirect)
4797 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4798 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4799 else
4800 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4801 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4802 return false;
4803 }
4804
4805 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&(static_cast<void> (0))
4806 "Unhandled implicit init kind!")(static_cast<void> (0));
4807
4808 QualType FieldBaseElementType =
4809 SemaRef.Context.getBaseElementType(Field->getType());
4810
4811 if (FieldBaseElementType->isRecordType()) {
4812 InitializedEntity InitEntity =
4813 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4814 /*Implicit*/ true)
4815 : InitializedEntity::InitializeMember(Field, nullptr,
4816 /*Implicit*/ true);
4817 InitializationKind InitKind =
4818 InitializationKind::CreateDefault(Loc);
4819
4820 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4821 ExprResult MemberInit =
4822 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4823
4824 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4825 if (MemberInit.isInvalid())
4826 return true;
4827
4828 if (Indirect)
4829 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4830 Indirect, Loc,
4831 Loc,
4832 MemberInit.get(),
4833 Loc);
4834 else
4835 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4836 Field, Loc, Loc,
4837 MemberInit.get(),
4838 Loc);
4839 return false;
4840 }
4841
4842 if (!Field->getParent()->isUnion()) {
4843 if (FieldBaseElementType->isReferenceType()) {
4844 SemaRef.Diag(Constructor->getLocation(),
4845 diag::err_uninitialized_member_in_ctor)
4846 << (int)Constructor->isImplicit()
4847 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4848 << 0 << Field->getDeclName();
4849 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4850 return true;
4851 }
4852
4853 if (FieldBaseElementType.isConstQualified()) {
4854 SemaRef.Diag(Constructor->getLocation(),
4855 diag::err_uninitialized_member_in_ctor)
4856 << (int)Constructor->isImplicit()
4857 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4858 << 1 << Field->getDeclName();
4859 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4860 return true;
4861 }
4862 }
4863
4864 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4865 // ARC and Weak:
4866 // Default-initialize Objective-C pointers to NULL.
4867 CXXMemberInit
4868 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4869 Loc, Loc,
4870 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4871 Loc);
4872 return false;
4873 }
4874
4875 // Nothing to initialize.
4876 CXXMemberInit = nullptr;
4877 return false;
4878}
4879
4880namespace {
4881struct BaseAndFieldInfo {
4882 Sema &S;
4883 CXXConstructorDecl *Ctor;
4884 bool AnyErrorsInInits;
4885 ImplicitInitializerKind IIK;
4886 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4887 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4888 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4889
4890 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4891 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4892 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4893 if (Ctor->getInheritedConstructor())
4894 IIK = IIK_Inherit;
4895 else if (Generated && Ctor->isCopyConstructor())
4896 IIK = IIK_Copy;
4897 else if (Generated && Ctor->isMoveConstructor())
4898 IIK = IIK_Move;
4899 else
4900 IIK = IIK_Default;
4901 }
4902
4903 bool isImplicitCopyOrMove() const {
4904 switch (IIK) {
4905 case IIK_Copy:
4906 case IIK_Move:
4907 return true;
4908
4909 case IIK_Default:
4910 case IIK_Inherit:
4911 return false;
4912 }
4913
4914 llvm_unreachable("Invalid ImplicitInitializerKind!")__builtin_unreachable();
4915 }
4916
4917 bool addFieldInitializer(CXXCtorInitializer *Init) {
4918 AllToInit.push_back(Init);
4919
4920 // Check whether this initializer makes the field "used".
4921 if (Init->getInit()->HasSideEffects(S.Context))
4922 S.UnusedPrivateFields.remove(Init->getAnyMember());
4923
4924 return false;
4925 }
4926
4927 bool isInactiveUnionMember(FieldDecl *Field) {
4928 RecordDecl *Record = Field->getParent();
4929 if (!Record->isUnion())
4930 return false;
4931
4932 if (FieldDecl *Active =
4933 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4934 return Active != Field->getCanonicalDecl();
4935
4936 // In an implicit copy or move constructor, ignore any in-class initializer.
4937 if (isImplicitCopyOrMove())
4938 return true;
4939
4940 // If there's no explicit initialization, the field is active only if it
4941 // has an in-class initializer...
4942 if (Field->hasInClassInitializer())
4943 return false;
4944 // ... or it's an anonymous struct or union whose class has an in-class
4945 // initializer.
4946 if (!Field->isAnonymousStructOrUnion())
4947 return true;
4948 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4949 return !FieldRD->hasInClassInitializer();
4950 }
4951
4952 /// Determine whether the given field is, or is within, a union member
4953 /// that is inactive (because there was an initializer given for a different
4954 /// member of the union, or because the union was not initialized at all).
4955 bool isWithinInactiveUnionMember(FieldDecl *Field,
4956 IndirectFieldDecl *Indirect) {
4957 if (!Indirect)
4958 return isInactiveUnionMember(Field);
4959
4960 for (auto *C : Indirect->chain()) {
4961 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4962 if (Field && isInactiveUnionMember(Field))
4963 return true;
4964 }
4965 return false;
4966 }
4967};
4968}
4969
4970/// Determine whether the given type is an incomplete or zero-lenfgth
4971/// array type.
4972static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4973 if (T->isIncompleteArrayType())
4974 return true;
4975
4976 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4977 if (!ArrayT->getSize())
4978 return true;
4979
4980 T = ArrayT->getElementType();
4981 }
4982
4983 return false;
4984}
4985
4986static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4987 FieldDecl *Field,
4988 IndirectFieldDecl *Indirect = nullptr) {
4989 if (Field->isInvalidDecl())
4990 return false;
4991
4992 // Overwhelmingly common case: we have a direct initializer for this field.
4993 if (CXXCtorInitializer *Init =
4994 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4995 return Info.addFieldInitializer(Init);
4996
4997 // C++11 [class.base.init]p8:
4998 // if the entity is a non-static data member that has a
4999 // brace-or-equal-initializer and either
5000 // -- the constructor's class is a union and no other variant member of that
5001 // union is designated by a mem-initializer-id or
5002 // -- the constructor's class is not a union, and, if the entity is a member
5003 // of an anonymous union, no other member of that union is designated by
5004 // a mem-initializer-id,
5005 // the entity is initialized as specified in [dcl.init].
5006 //
5007 // We also apply the same rules to handle anonymous structs within anonymous
5008 // unions.
5009 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5010 return false;
5011
5012 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5013 ExprResult DIE =
5014 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
5015 if (DIE.isInvalid())
5016 return true;
5017
5018 auto Entity = InitializedEntity::InitializeMember(Field, nullptr, true);
5019 SemaRef.checkInitializerLifetime(Entity, DIE.get());
5020
5021 CXXCtorInitializer *Init;
5022 if (Indirect)
5023 Init = new (SemaRef.Context)
5024 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5025 SourceLocation(), DIE.get(), SourceLocation());
5026 else
5027 Init = new (SemaRef.Context)
5028 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5029 SourceLocation(), DIE.get(), SourceLocation());
5030 return Info.addFieldInitializer(Init);
5031 }
5032
5033 // Don't initialize incomplete or zero-length arrays.
5034 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
5035 return false;
5036
5037 // Don't try to build an implicit initializer if there were semantic
5038 // errors in any of the initializers (and therefore we might be
5039 // missing some that the user actually wrote).
5040 if (Info.AnyErrorsInInits)
5041 return false;
5042
5043 CXXCtorInitializer *Init = nullptr;
5044 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
5045 Indirect, Init))
5046 return true;
5047
5048 if (!Init)
5049 return false;
5050
5051 return Info.addFieldInitializer(Init);
5052}
5053
5054bool
5055Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5056 CXXCtorInitializer *Initializer) {
5057 assert(Initializer->isDelegatingInitializer())(static_cast<void> (0));
5058 Constructor->setNumCtorInitializers(1);
5059 CXXCtorInitializer **initializer =
5060 new (Context) CXXCtorInitializer*[1];
5061 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
5062 Constructor->setCtorInitializers(initializer);
5063
5064 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
5065 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
5066 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
5067 }
5068
5069 DelegatingCtorDecls.push_back(Constructor);
5070
5071 DiagnoseUninitializedFields(*this, Constructor);
5072
5073 return false;
5074}
5075
5076bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5077 ArrayRef<CXXCtorInitializer *> Initializers) {
5078 if (Constructor->isDependentContext()) {
5079 // Just store the initializers as written, they will be checked during
5080 // instantiation.
5081 if (!Initializers.empty()) {
5082 Constructor->setNumCtorInitializers(Initializers.size());
5083 CXXCtorInitializer **baseOrMemberInitializers =
5084 new (Context) CXXCtorInitializer*[Initializers.size()];
5085 memcpy(baseOrMemberInitializers, Initializers.data(),
5086 Initializers.size() * sizeof(CXXCtorInitializer*));
5087 Constructor->setCtorInitializers(baseOrMemberInitializers);
5088 }
5089
5090 // Let template instantiation know whether we had errors.
5091 if (AnyErrors)
5092 Constructor->setInvalidDecl();
5093
5094 return false;
5095 }
5096
5097 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5098
5099 // We need to build the initializer AST according to order of construction
5100 // and not what user specified in the Initializers list.
5101 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5102 if (!ClassDecl)
5103 return true;
5104
5105 bool HadError = false;
5106
5107 for (unsigned i = 0; i < Initializers.size(); i++) {
5108 CXXCtorInitializer *Member = Initializers[i];
5109
5110 if (Member->isBaseInitializer())
5111 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
5112 else {
5113 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5114
5115 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5116 for (auto *C : F->chain()) {
5117 FieldDecl *FD = dyn_cast<FieldDecl>(C);
5118 if (FD && FD->getParent()->isUnion())
5119 Info.ActiveUnionMember.insert(std::make_pair(
5120 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5121 }
5122 } else if (FieldDecl *FD = Member->getMember()) {
5123 if (FD->getParent()->isUnion())
5124 Info.ActiveUnionMember.insert(std::make_pair(
5125 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
5126 }
5127 }
5128 }
5129
5130 // Keep track of the direct virtual bases.
5131 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5132 for (auto &I : ClassDecl->bases()) {
5133 if (I.isVirtual())
5134 DirectVBases.insert(&I);
5135 }
5136
5137 // Push virtual bases before others.
5138 for (auto &VBase : ClassDecl->vbases()) {
5139 if (CXXCtorInitializer *Value
5140 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
5141 // [class.base.init]p7, per DR257:
5142 // A mem-initializer where the mem-initializer-id names a virtual base
5143 // class is ignored during execution of a constructor of any class that
5144 // is not the most derived class.
5145 if (ClassDecl->isAbstract()) {
5146 // FIXME: Provide a fixit to remove the base specifier. This requires
5147 // tracking the location of the associated comma for a base specifier.
5148 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
5149 << VBase.getType() << ClassDecl;
5150 DiagnoseAbstractType(ClassDecl);
5151 }
5152
5153 Info.AllToInit.push_back(Value);
5154 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5155 // [class.base.init]p8, per DR257:
5156 // If a given [...] base class is not named by a mem-initializer-id
5157 // [...] and the entity is not a virtual base class of an abstract
5158 // class, then [...] the entity is default-initialized.
5159 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
5160 CXXCtorInitializer *CXXBaseInit;
5161 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5162 &VBase, IsInheritedVirtualBase,
5163 CXXBaseInit)) {
5164 HadError = true;
5165 continue;
5166 }
5167
5168 Info.AllToInit.push_back(CXXBaseInit);
5169 }
5170 }
5171
5172 // Non-virtual bases.
5173 for (auto &Base : ClassDecl->bases()) {
5174 // Virtuals are in the virtual base list and already constructed.
5175 if (Base.isVirtual())
5176 continue;
5177
5178 if (CXXCtorInitializer *Value
5179 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
5180 Info.AllToInit.push_back(Value);
5181 } else if (!AnyErrors) {
5182 CXXCtorInitializer *CXXBaseInit;
5183 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
5184 &Base, /*IsInheritedVirtualBase=*/false,
5185 CXXBaseInit)) {
5186 HadError = true;
5187 continue;
5188 }
5189
5190 Info.AllToInit.push_back(CXXBaseInit);
5191 }
5192 }
5193
5194 // Fields.
5195 for (auto *Mem : ClassDecl->decls()) {
5196 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
5197 // C++ [class.bit]p2:
5198 // A declaration for a bit-field that omits the identifier declares an
5199 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5200 // initialized.
5201 if (F->isUnnamedBitfield())
5202 continue;
5203
5204 // If we're not generating the implicit copy/move constructor, then we'll
5205 // handle anonymous struct/union fields based on their individual
5206 // indirect fields.
5207 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5208 continue;
5209
5210 if (CollectFieldInitializer(*this, Info, F))
5211 HadError = true;
5212 continue;
5213 }
5214
5215 // Beyond this point, we only consider default initialization.
5216 if (Info.isImplicitCopyOrMove())
5217 continue;
5218
5219 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
5220 if (F->getType()->isIncompleteArrayType()) {
5221 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast<void> (0))
5222 "Incomplete array type is not valid")(static_cast<void> (0));
5223 continue;
5224 }
5225
5226 // Initialize each field of an anonymous struct individually.
5227 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
5228 HadError = true;
5229
5230 continue;
5231 }
5232 }
5233
5234 unsigned NumInitializers = Info.AllToInit.size();
5235 if (NumInitializers > 0) {
5236 Constructor->setNumCtorInitializers(NumInitializers);
5237 CXXCtorInitializer **baseOrMemberInitializers =
5238 new (Context) CXXCtorInitializer*[NumInitializers];
5239 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
5240 NumInitializers * sizeof(CXXCtorInitializer*));
5241 Constructor->setCtorInitializers(baseOrMemberInitializers);
5242
5243 // Constructors implicitly reference the base and member
5244 // destructors.
5245 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
5246 Constructor->getParent());
5247 }
5248
5249 return HadError;
5250}
5251
5252static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5253 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
5254 const RecordDecl *RD = RT->getDecl();
5255 if (RD->isAnonymousStructOrUnion()) {
5256 for (auto *Field : RD->fields())
5257 PopulateKeysForFields(Field, IdealInits);
5258 return;
5259 }
5260 }
5261 IdealInits.push_back(Field->getCanonicalDecl());
5262}
5263
5264static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5265 return Context.getCanonicalType(BaseType).getTypePtr();
5266}
5267
5268static const void *GetKeyForMember(ASTContext &Context,
5269 CXXCtorInitializer *Member) {
5270 if (!Member->isAnyMemberInitializer())
5271 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
5272
5273 return Member->getAnyMember()->getCanonicalDecl();
5274}
5275
5276static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5277 const CXXCtorInitializer *Previous,
5278 const CXXCtorInitializer *Current) {
5279 if (Previous->isAnyMemberInitializer())
5280 Diag << 0 << Previous->getAnyMember();
5281 else
5282 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5283
5284 if (Current->isAnyMemberInitializer())
5285 Diag << 0 << Current->getAnyMember();
5286 else
5287 Diag << 1 << Current->getTypeSourceInfo()->getType();
5288}
5289
5290static void DiagnoseBaseOrMemInitializerOrder(
5291 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5292 ArrayRef<CXXCtorInitializer *> Inits) {
5293 if (Constructor->getDeclContext()->isDependentContext())
5294 return;
5295
5296 // Don't check initializers order unless the warning is enabled at the
5297 // location of at least one initializer.
5298 bool ShouldCheckOrder = false;
5299 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5300 CXXCtorInitializer *Init = Inits[InitIndex];
5301 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
5302 Init->getSourceLocation())) {
5303 ShouldCheckOrder = true;
5304 break;
5305 }
5306 }
5307 if (!ShouldCheckOrder)
5308 return;
5309
5310 // Build the list of bases and members in the order that they'll
5311 // actually be initialized. The explicit initializers should be in
5312 // this same order but may be missing things.
5313 SmallVector<const void*, 32> IdealInitKeys;
5314
5315 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5316
5317 // 1. Virtual bases.
5318 for (const auto &VBase : ClassDecl->vbases())
5319 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
5320
5321 // 2. Non-virtual bases.
5322 for (const auto &Base : ClassDecl->bases()) {
5323 if (Base.isVirtual())
5324 continue;
5325 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
5326 }
5327
5328 // 3. Direct fields.
5329 for (auto *Field : ClassDecl->fields()) {
5330 if (Field->isUnnamedBitfield())
5331 continue;
5332
5333 PopulateKeysForFields(Field, IdealInitKeys);
5334 }
5335
5336 unsigned NumIdealInits = IdealInitKeys.size();
5337 unsigned IdealIndex = 0;
5338
5339 // Track initializers that are in an incorrect order for either a warning or
5340 // note if multiple ones occur.
5341 SmallVector<unsigned> WarnIndexes;
5342 // Correlates the index of an initializer in the init-list to the index of
5343 // the field/base in the class.
5344 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5345
5346 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5347 const void *InitKey = GetKeyForMember(SemaRef.Context, Inits[InitIndex]);
5348
5349 // Scan forward to try to find this initializer in the idealized
5350 // initializers list.
5351 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5352 if (InitKey == IdealInitKeys[IdealIndex])
5353 break;
5354
5355 // If we didn't find this initializer, it must be because we
5356 // scanned past it on a previous iteration. That can only
5357 // happen if we're out of order; emit a warning.
5358 if (IdealIndex == NumIdealInits && InitIndex) {
5359 WarnIndexes.push_back(InitIndex);
5360
5361 // Move back to the initializer's location in the ideal list.
5362 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5363 if (InitKey == IdealInitKeys[IdealIndex])
5364 break;
5365
5366 assert(IdealIndex < NumIdealInits &&(static_cast<void> (0))
5367 "initializer not found in initializer list")(static_cast<void> (0));
5368 }
5369 CorrelatedInitOrder.emplace_back(IdealIndex, InitIndex);
5370 }
5371
5372 if (WarnIndexes.empty())
5373 return;
5374
5375 // Sort based on the ideal order, first in the pair.
5376 llvm::sort(CorrelatedInitOrder,
5377 [](auto &LHS, auto &RHS) { return LHS.first < RHS.first; });
5378
5379 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5380 // emit the diagnostic before we can try adding notes.
5381 {
5382 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5383 Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5384 WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5385 : diag::warn_some_initializers_out_of_order);
5386
5387 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5388 if (CorrelatedInitOrder[I].second == I)
5389 continue;
5390 // Ideally we would be using InsertFromRange here, but clang doesn't
5391 // appear to handle InsertFromRange correctly when the source range is
5392 // modified by another fix-it.
5393 D << FixItHint::CreateReplacement(
5394 Inits[I]->getSourceRange(),
5395 Lexer::getSourceText(
5396 CharSourceRange::getTokenRange(
5397 Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5398 SemaRef.getSourceManager(), SemaRef.getLangOpts()));
5399 }
5400
5401 // If there is only 1 item out of order, the warning expects the name and
5402 // type of each being added to it.
5403 if (WarnIndexes.size() == 1) {
5404 AddInitializerToDiag(D, Inits[WarnIndexes.front() - 1],
5405 Inits[WarnIndexes.front()]);
5406 return;
5407 }
5408 }
5409 // More than 1 item to warn, create notes letting the user know which ones
5410 // are bad.
5411 for (unsigned WarnIndex : WarnIndexes) {
5412 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5413 auto D = SemaRef.Diag(PrevInit->getSourceLocation(),
5414 diag::note_initializer_out_of_order);
5415 AddInitializerToDiag(D, PrevInit, Inits[WarnIndex]);
5416 D << PrevInit->getSourceRange();
5417 }
5418}
5419
5420namespace {
5421bool CheckRedundantInit(Sema &S,
5422 CXXCtorInitializer *Init,
5423 CXXCtorInitializer *&PrevInit) {
5424 if (!PrevInit) {
5425 PrevInit = Init;
5426 return false;
5427 }
5428
5429 if (FieldDecl *Field = Init->getAnyMember())
5430 S.Diag(Init->getSourceLocation(),
5431 diag::err_multiple_mem_initialization)
5432 << Field->getDeclName()
5433 << Init->getSourceRange();
5434 else {
5435 const Type *BaseClass = Init->getBaseClass();
5436 assert(BaseClass && "neither field nor base")(static_cast<void> (0));
5437 S.Diag(Init->getSourceLocation(),
5438 diag::err_multiple_base_initialization)
5439 << QualType(BaseClass, 0)
5440 << Init->getSourceRange();
5441 }
5442 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
5443 << 0 << PrevInit->getSourceRange();
5444
5445 return true;
5446}
5447
5448typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5449typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5450
5451bool CheckRedundantUnionInit(Sema &S,
5452 CXXCtorInitializer *Init,
5453 RedundantUnionMap &Unions) {
5454 FieldDecl *Field = Init->getAnyMember();
5455 RecordDecl *Parent = Field->getParent();
5456 NamedDecl *Child = Field;
5457
5458 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5459 if (Parent->isUnion()) {
5460 UnionEntry &En = Unions[Parent];
5461 if (En.first && En.first != Child) {
5462 S.Diag(Init->getSourceLocation(),
5463 diag::err_multiple_mem_union_initialization)
5464 << Field->getDeclName()
5465 << Init->getSourceRange();
5466 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
5467 << 0 << En.second->getSourceRange();
5468 return true;
5469 }
5470 if (!En.first) {
5471 En.first = Child;
5472 En.second = Init;
5473 }
5474 if (!Parent->isAnonymousStructOrUnion())
5475 return false;
5476 }
5477
5478 Child = Parent;
5479 Parent = cast<RecordDecl>(Parent->getDeclContext());
5480 }
5481
5482 return false;
5483}
5484} // namespace
5485
5486/// ActOnMemInitializers - Handle the member initializers for a constructor.
5487void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5488 SourceLocation ColonLoc,
5489 ArrayRef<CXXCtorInitializer*> MemInits,
5490 bool AnyErrors) {
5491 if (!ConstructorDecl)
5492 return;
5493
5494 AdjustDeclIfTemplate(ConstructorDecl);
5495
5496 CXXConstructorDecl *Constructor
5497 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5498
5499 if (!Constructor) {
5500 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5501 return;
5502 }
5503
5504 // Mapping for the duplicate initializers check.
5505 // For member initializers, this is keyed with a FieldDecl*.
5506 // For base initializers, this is keyed with a Type*.
5507 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5508
5509 // Mapping for the inconsistent anonymous-union initializers check.
5510 RedundantUnionMap MemberUnions;
5511
5512 bool HadError = false;
5513 for (unsigned i = 0; i < MemInits.size(); i++) {
5514 CXXCtorInitializer *Init = MemInits[i];
5515
5516 // Set the source order index.
5517 Init->setSourceOrder(i);
5518
5519 if (Init->isAnyMemberInitializer()) {
5520 const void *Key = GetKeyForMember(Context, Init);
5521 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5522 CheckRedundantUnionInit(*this, Init, MemberUnions))
5523 HadError = true;
5524 } else if (Init->isBaseInitializer()) {
5525 const void *Key = GetKeyForMember(Context, Init);
5526 if (CheckRedundantInit(*this, Init, Members[Key]))
5527 HadError = true;
5528 } else {
5529 assert(Init->isDelegatingInitializer())(static_cast<void> (0));
5530 // This must be the only initializer
5531 if (MemInits.size() != 1) {
5532 Diag(Init->getSourceLocation(),
5533 diag::err_delegating_initializer_alone)
5534 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5535 // We will treat this as being the only initializer.
5536 }
5537 SetDelegatingInitializer(Constructor, MemInits[i]);
5538 // Return immediately as the initializer is set.
5539 return;
5540 }
5541 }
5542
5543 if (HadError)
5544 return;
5545
5546 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5547
5548 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5549
5550 DiagnoseUninitializedFields(*this, Constructor);
5551}
5552
5553void
5554Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5555 CXXRecordDecl *ClassDecl) {
5556 // Ignore dependent contexts. Also ignore unions, since their members never
5557 // have destructors implicitly called.
5558 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5559 return;
5560
5561 // FIXME: all the access-control diagnostics are positioned on the
5562 // field/base declaration. That's probably good; that said, the
5563 // user might reasonably want to know why the destructor is being
5564 // emitted, and we currently don't say.
5565
5566 // Non-static data members.
5567 for (auto *Field : ClassDecl->fields()) {
5568 if (Field->isInvalidDecl())
5569 continue;
5570
5571 // Don't destroy incomplete or zero-length arrays.
5572 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5573 continue;
5574
5575 QualType FieldType = Context.getBaseElementType(Field->getType());
5576
5577 const RecordType* RT = FieldType->getAs<RecordType>();
5578 if (!RT)
5579 continue;
5580
5581 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5582 if (FieldClassDecl->isInvalidDecl())
5583 continue;
5584 if (FieldClassDecl->hasIrrelevantDestructor())
5585 continue;
5586 // The destructor for an implicit anonymous union member is never invoked.
5587 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5588 continue;
5589
5590 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5591 assert(Dtor && "No dtor found for FieldClassDecl!")(static_cast<void> (0));
5592 CheckDestructorAccess(Field->getLocation(), Dtor,
5593 PDiag(diag::err_access_dtor_field)
5594 << Field->getDeclName()
5595 << FieldType);
5596
5597 MarkFunctionReferenced(Location, Dtor);
5598 DiagnoseUseOfDecl(Dtor, Location);
5599 }
5600
5601 // We only potentially invoke the destructors of potentially constructed
5602 // subobjects.
5603 bool VisitVirtualBases = !ClassDecl->isAbstract();
5604
5605 // If the destructor exists and has already been marked used in the MS ABI,
5606 // then virtual base destructors have already been checked and marked used.
5607 // Skip checking them again to avoid duplicate diagnostics.
5608 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5609 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5610 if (Dtor && Dtor->isUsed())
5611 VisitVirtualBases = false;
5612 }
5613
5614 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5615
5616 // Bases.
5617 for (const auto &Base : ClassDecl->bases()) {
5618 const RecordType *RT = Base.getType()->getAs<RecordType>();
5619 if (!RT)
5620 continue;
5621
5622 // Remember direct virtual bases.
5623 if (Base.isVirtual()) {
5624 if (!VisitVirtualBases)
5625 continue;
5626 DirectVirtualBases.insert(RT);
5627 }
5628
5629 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5630 // If our base class is invalid, we probably can't get its dtor anyway.
5631 if (BaseClassDecl->isInvalidDecl())
5632 continue;
5633 if (BaseClassDecl->hasIrrelevantDestructor())
5634 continue;
5635
5636 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5637 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast<void> (0));
5638
5639 // FIXME: caret should be on the start of the class name
5640 CheckDestructorAccess(Base.getBeginLoc(), Dtor,
5641 PDiag(diag::err_access_dtor_base)
5642 << Base.getType() << Base.getSourceRange(),
5643 Context.getTypeDeclType(ClassDecl));
5644
5645 MarkFunctionReferenced(Location, Dtor);
5646 DiagnoseUseOfDecl(Dtor, Location);
5647 }
5648
5649 if (VisitVirtualBases)
5650 MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5651 &DirectVirtualBases);
5652}
5653
5654void Sema::MarkVirtualBaseDestructorsReferenced(
5655 SourceLocation Location, CXXRecordDecl *ClassDecl,
5656 llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases) {
5657 // Virtual bases.
5658 for (const auto &VBase : ClassDecl->vbases()) {
5659 // Bases are always records in a well-formed non-dependent class.
5660 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5661
5662 // Ignore already visited direct virtual bases.
5663 if (DirectVirtualBases && DirectVirtualBases->count(RT))
5664 continue;
5665
5666 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5667 // If our base class is invalid, we probably can't get its dtor anyway.
5668 if (BaseClassDecl->isInvalidDecl())
5669 continue;
5670 if (BaseClassDecl->hasIrrelevantDestructor())
5671 continue;
5672
5673 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5674 assert(Dtor && "No dtor found for BaseClassDecl!")(static_cast<void> (0));
5675 if (CheckDestructorAccess(
5676 ClassDecl->getLocation(), Dtor,
5677 PDiag(diag::err_access_dtor_vbase)
5678 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5679 Context.getTypeDeclType(ClassDecl)) ==
5680 AR_accessible) {
5681 CheckDerivedToBaseConversion(
5682 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5683 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5684 SourceRange(), DeclarationName(), nullptr);
5685 }
5686
5687 MarkFunctionReferenced(Location, Dtor);
5688 DiagnoseUseOfDecl(Dtor, Location);
5689 }
5690}
5691
5692void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5693 if (!CDtorDecl)
5694 return;
5695
5696 if (CXXConstructorDecl *Constructor
5697 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5698 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5699 DiagnoseUninitializedFields(*this, Constructor);
5700 }
5701}
5702
5703bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5704 if (!getLangOpts().CPlusPlus)
5705 return false;
5706
5707 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5708 if (!RD)
5709 return false;
5710
5711 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5712 // class template specialization here, but doing so breaks a lot of code.
5713
5714 // We can't answer whether something is abstract until it has a
5715 // definition. If it's currently being defined, we'll walk back
5716 // over all the declarations when we have a full definition.
5717 const CXXRecordDecl *Def = RD->getDefinition();
5718 if (!Def || Def->isBeingDefined())
5719 return false;
5720
5721 return RD->isAbstract();
5722}
5723
5724bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5725 TypeDiagnoser &Diagnoser) {
5726 if (!isAbstractType(Loc, T))
5727 return false;
5728
5729 T = Context.getBaseElementType(T);
5730 Diagnoser.diagnose(*this, Loc, T);
5731 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5732 return true;
5733}
5734
5735void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5736 // Check if we've already emitted the list of pure virtual functions
5737 // for this class.
5738 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5739 return;
5740
5741 // If the diagnostic is suppressed, don't emit the notes. We're only
5742 // going to emit them once, so try to attach them to a diagnostic we're
5743 // actually going to show.
5744 if (Diags.isLastDiagnosticIgnored())
5745 return;
5746
5747 CXXFinalOverriderMap FinalOverriders;
5748 RD->getFinalOverriders(FinalOverriders);
5749
5750 // Keep a set of seen pure methods so we won't diagnose the same method
5751 // more than once.
5752 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5753
5754 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5755 MEnd = FinalOverriders.end();
5756 M != MEnd;
5757 ++M) {
5758 for (OverridingMethods::iterator SO = M->second.begin(),
5759 SOEnd = M->second.end();
5760 SO != SOEnd; ++SO) {
5761 // C++ [class.abstract]p4:
5762 // A class is abstract if it contains or inherits at least one
5763 // pure virtual function for which the final overrider is pure
5764 // virtual.
5765
5766 //
5767 if (SO->second.size() != 1)
5768 continue;
5769
5770 if (!SO->second.front().Method->isPure())
5771 continue;
5772
5773 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5774 continue;
5775
5776 Diag(SO->second.front().Method->getLocation(),
5777 diag::note_pure_virtual_function)
5778 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5779 }
5780 }
5781
5782 if (!PureVirtualClassDiagSet)
5783 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5784 PureVirtualClassDiagSet->insert(RD);
5785}
5786
5787namespace {
5788struct AbstractUsageInfo {
5789 Sema &S;
5790 CXXRecordDecl *Record;
5791 CanQualType AbstractType;
5792 bool Invalid;
5793
5794 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5795 : S(S), Record(Record),
5796 AbstractType(S.Context.getCanonicalType(
5797 S.Context.getTypeDeclType(Record))),
5798 Invalid(false) {}
5799
5800 void DiagnoseAbstractType() {
5801 if (Invalid) return;
5802 S.DiagnoseAbstractType(Record);
5803 Invalid = true;
5804 }
5805
5806 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5807};
5808
5809struct CheckAbstractUsage {
5810 AbstractUsageInfo &Info;
5811 const NamedDecl *Ctx;
5812
5813 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5814 : Info(Info), Ctx(Ctx) {}
5815
5816 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5817 switch (TL.getTypeLocClass()) {
5818#define ABSTRACT_TYPELOC(CLASS, PARENT)
5819#define TYPELOC(CLASS, PARENT) \
5820 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5821#include "clang/AST/TypeLocNodes.def"
5822 }
5823 }
5824
5825 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5826 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5827 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5828 if (!TL.getParam(I))
5829 continue;
5830
5831 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5832 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5833 }
5834 }
5835
5836 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5837 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5838 }
5839
5840 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5841 // Visit the type parameters from a permissive context.
5842 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5843 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5844 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5845 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5846 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5847 // TODO: other template argument types?
5848 }
5849 }
5850
5851 // Visit pointee types from a permissive context.
5852#define CheckPolymorphic(Type)void Check(Type TL, Sema::AbstractDiagSelID Sel) { Visit(TL.getNextTypeLoc
(), Sema::AbstractNone); }
\
5853 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5854 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5855 }
5856 CheckPolymorphic(PointerTypeLoc)void Check(PointerTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5857 CheckPolymorphic(ReferenceTypeLoc)void Check(ReferenceTypeLoc TL, Sema::AbstractDiagSelID Sel) {
Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5858 CheckPolymorphic(MemberPointerTypeLoc)void Check(MemberPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5859 CheckPolymorphic(BlockPointerTypeLoc)void Check(BlockPointerTypeLoc TL, Sema::AbstractDiagSelID Sel
) { Visit(TL.getNextTypeLoc(), Sema::AbstractNone); }
5860 CheckPolymorphic(AtomicTypeLoc)void Check(AtomicTypeLoc TL, Sema::AbstractDiagSelID Sel) { Visit
(TL.getNextTypeLoc(), Sema::AbstractNone); }
5861
5862 /// Handle all the types we haven't given a more specific
5863 /// implementation for above.
5864 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5865 // Every other kind of type that we haven't called out already
5866 // that has an inner type is either (1) sugar or (2) contains that
5867 // inner type in some way as a subobject.
5868 if (TypeLoc Next = TL.getNextTypeLoc())
5869 return Visit(Next, Sel);
5870
5871 // If there's no inner type and we're in a permissive context,
5872 // don't diagnose.
5873 if (Sel == Sema::AbstractNone) return;
5874
5875 // Check whether the type matches the abstract type.
5876 QualType T = TL.getType();
5877 if (T->isArrayType()) {
5878 Sel = Sema::AbstractArrayType;
5879 T = Info.S.Context.getBaseElementType(T);
5880 }
5881 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5882 if (CT != Info.AbstractType) return;
5883
5884 // It matched; do some magic.
5885 if (Sel == Sema::AbstractArrayType) {
5886 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5887 << T << TL.getSourceRange();
5888 } else {
5889 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5890 << Sel << T << TL.getSourceRange();
5891 }
5892 Info.DiagnoseAbstractType();
5893 }
5894};
5895
5896void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5897 Sema::AbstractDiagSelID Sel) {
5898 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5899}
5900
5901}
5902
5903/// Check for invalid uses of an abstract type in a method declaration.
5904static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5905 CXXMethodDecl *MD) {
5906 // No need to do the check on definitions, which require that
5907 // the return/param types be complete.
5908 if (MD->doesThisDeclarationHaveABody())
5909 return;
5910
5911 // For safety's sake, just ignore it if we don't have type source
5912 // information. This should never happen for non-implicit methods,
5913 // but...
5914 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5915 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5916}
5917
5918/// Check for invalid uses of an abstract type within a class definition.
5919static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5920 CXXRecordDecl *RD) {
5921 for (auto *D : RD->decls()) {
5922 if (D->isImplicit()) continue;
5923
5924 // Methods and method templates.
5925 if (isa<CXXMethodDecl>(D)) {
5926 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5927 } else if (isa<FunctionTemplateDecl>(D)) {
5928 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5929 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5930
5931 // Fields and static variables.
5932 } else if (isa<FieldDecl>(D)) {
5933 FieldDecl *FD = cast<FieldDecl>(D);
5934 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5935 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5936 } else if (isa<VarDecl>(D)) {
5937 VarDecl *VD = cast<VarDecl>(D);
5938 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5939 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5940
5941 // Nested classes and class templates.
5942 } else if (isa<CXXRecordDecl>(D)) {
5943 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5944 } else if (isa<ClassTemplateDecl>(D)) {
5945 CheckAbstractClassUsage(Info,
5946 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5947 }
5948 }
5949}
5950
5951static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
5952 Attr *ClassAttr = getDLLAttr(Class);
5953 if (!ClassAttr)
5954 return;
5955
5956 assert(ClassAttr->getKind() == attr::DLLExport)(static_cast<void> (0));
5957
5958 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5959
5960 if (TSK == TSK_ExplicitInstantiationDeclaration)
5961 // Don't go any further if this is just an explicit instantiation
5962 // declaration.
5963 return;
5964
5965 // Add a context note to explain how we got to any diagnostics produced below.
5966 struct MarkingClassDllexported {
5967 Sema &S;
5968 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
5969 SourceLocation AttrLoc)
5970 : S(S) {
5971 Sema::CodeSynthesisContext Ctx;
5972 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
5973 Ctx.PointOfInstantiation = AttrLoc;
5974 Ctx.Entity = Class;
5975 S.pushCodeSynthesisContext(Ctx);
5976 }
5977 ~MarkingClassDllexported() {
5978 S.popCodeSynthesisContext();
5979 }
5980 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
5981
5982 if (S.Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
5983 S.MarkVTableUsed(Class->getLocation(), Class, true);
5984
5985 for (Decl *Member : Class->decls()) {
5986 // Skip members that were not marked exported.
5987 if (!Member->hasAttr<DLLExportAttr>())
5988 continue;
5989
5990 // Defined static variables that are members of an exported base
5991 // class must be marked export too.
5992 auto *VD = dyn_cast<VarDecl>(Member);
5993 if (VD && VD->getStorageClass() == SC_Static &&
5994 TSK == TSK_ImplicitInstantiation)
5995 S.MarkVariableReferenced(VD->getLocation(), VD);
5996
5997 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5998 if (!MD)
5999 continue;
6000
6001 if (MD->isUserProvided()) {
6002 // Instantiate non-default class member functions ...
6003
6004 // .. except for certain kinds of template specializations.
6005 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6006 continue;
6007
6008 // If this is an MS ABI dllexport default constructor, instantiate any
6009 // default arguments.
6010 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6011 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6012 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6013 S.InstantiateDefaultCtorDefaultArgs(CD);
6014 }
6015 }
6016
6017 S.MarkFunctionReferenced(Class->getLocation(), MD);
6018
6019 // The function will be passed to the consumer when its definition is
6020 // encountered.
6021 } else if (MD->isExplicitlyDefaulted()) {
6022 // Synthesize and instantiate explicitly defaulted methods.
6023 S.MarkFunctionReferenced(Class->getLocation(), MD);
6024
6025 if (TSK != TSK_ExplicitInstantiationDefinition) {
6026 // Except for explicit instantiation defs, we will not see the
6027 // definition again later, so pass it to the consumer now.
6028 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6029 }
6030 } else if (!MD->isTrivial() ||
6031 MD->isCopyAssignmentOperator() ||
6032 MD->isMoveAssignmentOperator()) {
6033 // Synthesize and instantiate non-trivial implicit methods, and the copy
6034 // and move assignment operators. The latter are exported even if they
6035 // are trivial, because the address of an operator can be taken and
6036 // should compare equal across libraries.
6037 S.MarkFunctionReferenced(Class->getLocation(), MD);
6038
6039 // There is no later point when we will see the definition of this
6040 // function, so pass it to the consumer now.
6041 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
6042 }
6043 }
6044}
6045
6046static void checkForMultipleExportedDefaultConstructors(Sema &S,
6047 CXXRecordDecl *Class) {
6048 // Only the MS ABI has default constructor closures, so we don't need to do
6049 // this semantic checking anywhere else.
6050 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6051 return;
6052
6053 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6054 for (Decl *Member : Class->decls()) {
6055 // Look for exported default constructors.
6056 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
6057 if (!CD || !CD->isDefaultConstructor())
6058 continue;
6059 auto *Attr = CD->getAttr<DLLExportAttr>();
6060 if (!Attr)
6061 continue;
6062
6063 // If the class is non-dependent, mark the default arguments as ODR-used so
6064 // that we can properly codegen the constructor closure.
6065 if (!Class->isDependentContext()) {
6066 for (ParmVarDecl *PD : CD->parameters()) {
6067 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
6068 S.DiscardCleanupsInEvaluationContext();
6069 }
6070 }
6071
6072 if (LastExportedDefaultCtor) {
6073 S.Diag(LastExportedDefaultCtor->getLocation(),
6074 diag::err_attribute_dll_ambiguous_default_ctor)
6075 << Class;
6076 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
6077 << CD->getDeclName();
6078 return;
6079 }
6080 LastExportedDefaultCtor = CD;
6081 }
6082}
6083
6084static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6085 CXXRecordDecl *Class) {
6086 bool ErrorReported = false;
6087 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6088 ClassTemplateDecl *TD) {
6089 if (ErrorReported)
6090 return;
6091 S.Diag(TD->getLocation(),
6092 diag::err_cuda_device_builtin_surftex_cls_template)
6093 << /*surface*/ 0 << TD;
6094 ErrorReported = true;
6095 };
6096
6097 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6098 if (!TD) {
6099 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6100 if (!SD) {
6101 S.Diag(Class->getLocation(),
6102 diag::err_cuda_device_builtin_surftex_ref_decl)
6103 << /*surface*/ 0 << Class;
6104 S.Diag(Class->getLocation(),
6105 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6106 << Class;
6107 return;
6108 }
6109 TD = SD->getSpecializedTemplate();
6110 }
6111
6112 TemplateParameterList *Params = TD->getTemplateParameters();
6113 unsigned N = Params->size();
6114
6115 if (N != 2) {
6116 reportIllegalClassTemplate(S, TD);
6117 S.Diag(TD->getLocation(),
6118 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6119 << TD << 2;
6120 }
6121 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6122 reportIllegalClassTemplate(S, TD);
6123 S.Diag(TD->getLocation(),
6124 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6125 << TD << /*1st*/ 0 << /*type*/ 0;
6126 }
6127 if (N > 1) {
6128 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6129 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6130 reportIllegalClassTemplate(S, TD);
6131 S.Diag(TD->getLocation(),
6132 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6133 << TD << /*2nd*/ 1 << /*integer*/ 1;
6134 }
6135 }
6136}
6137
6138static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6139 CXXRecordDecl *Class) {
6140 bool ErrorReported = false;
6141 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6142 ClassTemplateDecl *TD) {
6143 if (ErrorReported)
6144 return;
6145 S.Diag(TD->getLocation(),
6146 diag::err_cuda_device_builtin_surftex_cls_template)
6147 << /*texture*/ 1 << TD;
6148 ErrorReported = true;
6149 };
6150
6151 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6152 if (!TD) {
6153 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Class);
6154 if (!SD) {
6155 S.Diag(Class->getLocation(),
6156 diag::err_cuda_device_builtin_surftex_ref_decl)
6157 << /*texture*/ 1 << Class;
6158 S.Diag(Class->getLocation(),
6159 diag::note_cuda_device_builtin_surftex_should_be_template_class)
6160 << Class;
6161 return;
6162 }
6163 TD = SD->getSpecializedTemplate();
6164 }
6165
6166 TemplateParameterList *Params = TD->getTemplateParameters();
6167 unsigned N = Params->size();
6168
6169 if (N != 3) {
6170 reportIllegalClassTemplate(S, TD);
6171 S.Diag(TD->getLocation(),
6172 diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6173 << TD << 3;
6174 }
6175 if (N > 0 && !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
6176 reportIllegalClassTemplate(S, TD);
6177 S.Diag(TD->getLocation(),
6178 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6179 << TD << /*1st*/ 0 << /*type*/ 0;
6180 }
6181 if (N > 1) {
6182 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(1));
6183 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6184 reportIllegalClassTemplate(S, TD);
6185 S.Diag(TD->getLocation(),
6186 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6187 << TD << /*2nd*/ 1 << /*integer*/ 1;
6188 }
6189 }
6190 if (N > 2) {
6191 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Params->getParam(2));
6192 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6193 reportIllegalClassTemplate(S, TD);
6194 S.Diag(TD->getLocation(),
6195 diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6196 << TD << /*3rd*/ 2 << /*integer*/ 1;
6197 }
6198 }
6199}
6200
6201void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6202 // Mark any compiler-generated routines with the implicit code_seg attribute.
6203 for (auto *Method : Class->methods()) {
6204 if (Method->isUserProvided())
6205 continue;
6206 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
6207 Method->addAttr(A);
6208 }
6209}
6210
6211/// Check class-level dllimport/dllexport attribute.
6212void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6213 Attr *ClassAttr = getDLLAttr(Class);
6214
6215 // MSVC inherits DLL attributes to partial class template specializations.
6216 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6217 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
6218 if (Attr *TemplateAttr =
6219 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6220 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
6221 A->setInherited(true);
6222 ClassAttr = A;
6223 }
6224 }
6225 }
6226
6227 if (!ClassAttr)
6228 return;
6229
6230 if (!Class->isExternallyVisible()) {
6231 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
6232 << Class << ClassAttr;
6233 return;
6234 }
6235
6236 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6237 !ClassAttr->isInherited()) {
6238 // Diagnose dll attributes on members of class with dll attribute.
6239 for (Decl *Member : Class->decls()) {
6240 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
6241 continue;
6242 InheritableAttr *MemberAttr = getDLLAttr(Member);
6243 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6244 continue;
6245
6246 Diag(MemberAttr->getLocation(),
6247 diag::err_attribute_dll_member_of_dll_class)
6248 << MemberAttr << ClassAttr;
6249 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
6250 Member->setInvalidDecl();
6251 }
6252 }
6253
6254 if (Class->getDescribedClassTemplate())
6255 // Don't inherit dll attribute until the template is instantiated.
6256 return;
6257
6258 // The class is either imported or exported.
6259 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6260
6261 // Check if this was a dllimport attribute propagated from a derived class to
6262 // a base class template specialization. We don't apply these attributes to
6263 // static data members.
6264 const bool PropagatedImport =
6265 !ClassExported &&
6266 cast<DLLImportAttr>(ClassAttr)->wasPropagatedToBaseTemplate();
6267
6268 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6269
6270 // Ignore explicit dllexport on explicit class template instantiation
6271 // declarations, except in MinGW mode.
6272 if (ClassExported && !ClassAttr->isInherited() &&
6273 TSK == TSK_ExplicitInstantiationDeclaration &&
6274 !Context.getTargetInfo().getTriple().isWindowsGNUEnvironment()) {
6275 Class->dropAttr<DLLExportAttr>();
6276 return;
6277 }
6278
6279 // Force declaration of implicit members so they can inherit the attribute.
6280 ForceDeclarationOfImplicitMembers(Class);
6281
6282 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6283 // seem to be true in practice?
6284
6285 for (Decl *Member : Class->decls()) {
6286 VarDecl *VD = dyn_cast<VarDecl>(Member);
6287 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
6288
6289 // Only methods and static fields inherit the attributes.
6290 if (!VD && !MD)
6291 continue;
6292
6293 if (MD) {
6294 // Don't process deleted methods.
6295 if (MD->isDeleted())
6296 continue;
6297
6298 if (MD->isInlined()) {
6299 // MinGW does not import or export inline methods. But do it for
6300 // template instantiations.
6301 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6302 TSK != TSK_ExplicitInstantiationDeclaration &&
6303 TSK != TSK_ExplicitInstantiationDefinition)
6304 continue;
6305
6306 // MSVC versions before 2015 don't export the move assignment operators
6307 // and move constructor, so don't attempt to import/export them if
6308 // we have a definition.
6309 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
6310 if ((MD->isMoveAssignmentOperator() ||
6311 (Ctor && Ctor->isMoveConstructor())) &&
6312 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
6313 continue;
6314
6315 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6316 // operator is exported anyway.
6317 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6318 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
6319 continue;
6320 }
6321 }
6322
6323 // Don't apply dllimport attributes to static data members of class template
6324 // instantiations when the attribute is propagated from a derived class.
6325 if (VD && PropagatedImport)
6326 continue;
6327
6328 if (!cast<NamedDecl>(Member)->isExternallyVisible())
6329 continue;
6330
6331 if (!getDLLAttr(Member)) {
6332 InheritableAttr *NewAttr = nullptr;
6333
6334 // Do not export/import inline function when -fno-dllexport-inlines is
6335 // passed. But add attribute for later local static var check.
6336 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6337 TSK != TSK_ExplicitInstantiationDeclaration &&
6338 TSK != TSK_ExplicitInstantiationDefinition) {
6339 if (ClassExported) {
6340 NewAttr = ::new (getASTContext())
6341 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6342 } else {
6343 NewAttr = ::new (getASTContext())
6344 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6345 }
6346 } else {
6347 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6348 }
6349
6350 NewAttr->setInherited(true);
6351 Member->addAttr(NewAttr);
6352
6353 if (MD) {
6354 // Propagate DLLAttr to friend re-declarations of MD that have already
6355 // been constructed.
6356 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6357 FD = FD->getPreviousDecl()) {
6358 if (FD->getFriendObjectKind() == Decl::FOK_None)
6359 continue;
6360 assert(!getDLLAttr(FD) &&(static_cast<void> (0))
6361 "friend re-decl should not already have a DLLAttr")(static_cast<void> (0));
6362 NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6363 NewAttr->setInherited(true);
6364 FD->addAttr(NewAttr);
6365 }
6366 }
6367 }
6368 }
6369
6370 if (ClassExported)
6371 DelayedDllExportClasses.push_back(Class);
6372}
6373
6374/// Perform propagation of DLL attributes from a derived class to a
6375/// templated base class for MS compatibility.
6376void Sema::propagateDLLAttrToBaseClassTemplate(
6377 CXXRecordDecl *Class, Attr *ClassAttr,
6378 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6379 if (getDLLAttr(
6380 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6381 // If the base class template has a DLL attribute, don't try to change it.
6382 return;
6383 }
6384
6385 auto TSK = BaseTemplateSpec->getSpecializationKind();
6386 if (!getDLLAttr(BaseTemplateSpec) &&
6387 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6388 TSK == TSK_ImplicitInstantiation)) {
6389 // The template hasn't been instantiated yet (or it has, but only as an
6390 // explicit instantiation declaration or implicit instantiation, which means
6391 // we haven't codegenned any members yet), so propagate the attribute.
6392 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
6393 NewAttr->setInherited(true);
6394 BaseTemplateSpec->addAttr(NewAttr);
6395
6396 // If this was an import, mark that we propagated it from a derived class to
6397 // a base class template specialization.
6398 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(NewAttr))
6399 ImportAttr->setPropagatedToBaseTemplate();
6400
6401 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6402 // needs to be run again to work see the new attribute. Otherwise this will
6403 // get run whenever the template is instantiated.
6404 if (TSK != TSK_Undeclared)
6405 checkClassLevelDLLAttribute(BaseTemplateSpec);
6406
6407 return;
6408 }
6409
6410 if (getDLLAttr(BaseTemplateSpec)) {
6411 // The template has already been specialized or instantiated with an
6412 // attribute, explicitly or through propagation. We should not try to change
6413 // it.
6414 return;
6415 }
6416
6417 // The template was previously instantiated or explicitly specialized without
6418 // a dll attribute, It's too late for us to add an attribute, so warn that
6419 // this is unsupported.
6420 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
6421 << BaseTemplateSpec->isExplicitSpecialization();
6422 Diag(ClassAttr->getLocation(), diag::note_attribute);
6423 if (BaseTemplateSpec->isExplicitSpecialization()) {
6424 Diag(BaseTemplateSpec->getLocation(),
6425 diag::note_template_class_explicit_specialization_was_here)
6426 << BaseTemplateSpec;
6427 } else {
6428 Diag(BaseTemplateSpec->getPointOfInstantiation(),
6429 diag::note_template_class_instantiation_was_here)
6430 << BaseTemplateSpec;
6431 }
6432}
6433
6434/// Determine the kind of defaulting that would be done for a given function.
6435///
6436/// If the function is both a default constructor and a copy / move constructor
6437/// (due to having a default argument for the first parameter), this picks
6438/// CXXDefaultConstructor.
6439///
6440/// FIXME: Check that case is properly handled by all callers.
6441Sema::DefaultedFunctionKind
6442Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6443 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
6444 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
6445 if (Ctor->isDefaultConstructor())
6446 return Sema::CXXDefaultConstructor;
6447
6448 if (Ctor->isCopyConstructor())
6449 return Sema::CXXCopyConstructor;
6450
6451 if (Ctor->isMoveConstructor())
6452 return Sema::CXXMoveConstructor;
6453 }
6454
6455 if (MD->isCopyAssignmentOperator())
6456 return Sema::CXXCopyAssignment;
6457
6458 if (MD->isMoveAssignmentOperator())
6459 return Sema::CXXMoveAssignment;
6460
6461 if (isa<CXXDestructorDecl>(FD))
6462 return Sema::CXXDestructor;
6463 }
6464
6465 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6466 case OO_EqualEqual:
6467 return DefaultedComparisonKind::Equal;
6468
6469 case OO_ExclaimEqual:
6470 return DefaultedComparisonKind::NotEqual;
6471
6472 case OO_Spaceship:
6473 // No point allowing this if <=> doesn't exist in the current language mode.
6474 if (!getLangOpts().CPlusPlus20)
6475 break;
6476 return DefaultedComparisonKind::ThreeWay;
6477
6478 case OO_Less:
6479 case OO_LessEqual:
6480 case OO_Greater:
6481 case OO_GreaterEqual:
6482 // No point allowing this if <=> doesn't exist in the current language mode.
6483 if (!getLangOpts().CPlusPlus20)
6484 break;
6485 return DefaultedComparisonKind::Relational;
6486
6487 default:
6488 break;
6489 }
6490
6491 // Not defaultable.
6492 return DefaultedFunctionKind();
6493}
6494
6495static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6496 SourceLocation DefaultLoc) {
6497 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6498 if (DFK.isComparison())
6499 return S.DefineDefaultedComparison(DefaultLoc, FD, DFK.asComparison());
6500
6501 switch (DFK.asSpecialMember()) {
6502 case Sema::CXXDefaultConstructor:
6503 S.DefineImplicitDefaultConstructor(DefaultLoc,
6504 cast<CXXConstructorDecl>(FD));
6505 break;
6506 case Sema::CXXCopyConstructor:
6507 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6508 break;
6509 case Sema::CXXCopyAssignment:
6510 S.DefineImplicitCopyAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6511 break;
6512 case Sema::CXXDestructor:
6513 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(FD));
6514 break;
6515 case Sema::CXXMoveConstructor:
6516 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(FD));
6517 break;
6518 case Sema::CXXMoveAssignment:
6519 S.DefineImplicitMoveAssignment(DefaultLoc, cast<CXXMethodDecl>(FD));
6520 break;
6521 case Sema::CXXInvalid:
6522 llvm_unreachable("Invalid special member.")__builtin_unreachable();
6523 }
6524}
6525
6526/// Determine whether a type is permitted to be passed or returned in
6527/// registers, per C++ [class.temporary]p3.
6528static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6529 TargetInfo::CallingConvKind CCK) {
6530 if (D->isDependentType() || D->isInvalidDecl())
6531 return false;
6532
6533 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6534 // The PS4 platform ABI follows the behavior of Clang 3.2.
6535 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6536 return !D->hasNonTrivialDestructorForCall() &&
6537 !D->hasNonTrivialCopyConstructorForCall();
6538
6539 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6540 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6541 bool DtorIsTrivialForCall = false;
6542
6543 // If a class has at least one non-deleted, trivial copy constructor, it
6544 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6545 //
6546 // Note: This permits classes with non-trivial copy or move ctors to be
6547 // passed in registers, so long as they *also* have a trivial copy ctor,
6548 // which is non-conforming.
6549 if (D->needsImplicitCopyConstructor()) {
6550 if (!D->defaultedCopyConstructorIsDeleted()) {
6551 if (D->hasTrivialCopyConstructor())
6552 CopyCtorIsTrivial = true;
6553 if (D->hasTrivialCopyConstructorForCall())
6554 CopyCtorIsTrivialForCall = true;
6555 }
6556 } else {
6557 for (const CXXConstructorDecl *CD : D->ctors()) {
6558 if (CD->isCopyConstructor() && !CD->isDeleted()) {
6559 if (CD->isTrivial())
6560 CopyCtorIsTrivial = true;
6561 if (CD->isTrivialForCall())
6562 CopyCtorIsTrivialForCall = true;
6563 }
6564 }
6565 }
6566
6567 if (D->needsImplicitDestructor()) {
6568 if (!D->defaultedDestructorIsDeleted() &&
6569 D->hasTrivialDestructorForCall())
6570 DtorIsTrivialForCall = true;
6571 } else if (const auto *DD = D->getDestructor()) {
6572 if (!DD->isDeleted() && DD->isTrivialForCall())
6573 DtorIsTrivialForCall = true;
6574 }
6575
6576 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6577 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6578 return true;
6579
6580 // If a class has a destructor, we'd really like to pass it indirectly
6581 // because it allows us to elide copies. Unfortunately, MSVC makes that
6582 // impossible for small types, which it will pass in a single register or
6583 // stack slot. Most objects with dtors are large-ish, so handle that early.
6584 // We can't call out all large objects as being indirect because there are
6585 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6586 // how we pass large POD types.
6587
6588 // Note: This permits small classes with nontrivial destructors to be
6589 // passed in registers, which is non-conforming.
6590 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6591 uint64_t TypeSize = isAArch64 ? 128 : 64;
6592
6593 if (CopyCtorIsTrivial &&
6594 S.getASTContext().getTypeSize(D->getTypeForDecl()) <= TypeSize)
6595 return true;
6596 return false;
6597 }
6598
6599 // Per C++ [class.temporary]p3, the relevant condition is:
6600 // each copy constructor, move constructor, and destructor of X is
6601 // either trivial or deleted, and X has at least one non-deleted copy
6602 // or move constructor
6603 bool HasNonDeletedCopyOrMove = false;
6604
6605 if (D->needsImplicitCopyConstructor() &&
6606 !D->defaultedCopyConstructorIsDeleted()) {
6607 if (!D->hasTrivialCopyConstructorForCall())
6608 return false;
6609 HasNonDeletedCopyOrMove = true;
6610 }
6611
6612 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
6613 !D->defaultedMoveConstructorIsDeleted()) {
6614 if (!D->hasTrivialMoveConstructorForCall())
6615 return false;
6616 HasNonDeletedCopyOrMove = true;
6617 }
6618
6619 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
6620 !D->hasTrivialDestructorForCall())
6621 return false;
6622
6623 for (const CXXMethodDecl *MD : D->methods()) {
6624 if (MD->isDeleted())
6625 continue;
6626
6627 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
6628 if (CD && CD->isCopyOrMoveConstructor())
6629 HasNonDeletedCopyOrMove = true;
6630 else if (!isa<CXXDestructorDecl>(MD))
6631 continue;
6632
6633 if (!MD->isTrivialForCall())
6634 return false;
6635 }
6636
6637 return HasNonDeletedCopyOrMove;
6638}
6639
6640/// Report an error regarding overriding, along with any relevant
6641/// overridden methods.
6642///
6643/// \param DiagID the primary error to report.
6644/// \param MD the overriding method.
6645static bool
6646ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
6647 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
6648 bool IssuedDiagnostic = false;
6649 for (const CXXMethodDecl *O : MD->overridden_methods()) {
6650 if (Report(O)) {
6651 if (!IssuedDiagnostic) {
6652 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6653 IssuedDiagnostic = true;
6654 }
6655 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
6656 }
6657 }
6658 return IssuedDiagnostic;
6659}
6660
6661/// Perform semantic checks on a class definition that has been
6662/// completing, introducing implicitly-declared members, checking for
6663/// abstract types, etc.
6664///
6665/// \param S The scope in which the class was parsed. Null if we didn't just
6666/// parse a class definition.
6667/// \param Record The completed class.
6668void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
6669 if (!Record)
6670 return;
6671
6672 if (Record->isAbstract() && !Record->isInvalidDecl()) {
6673 AbstractUsageInfo Info(*this, Record);
6674 CheckAbstractClassUsage(Info, Record);
6675 }
6676
6677 // If this is not an aggregate type and has no user-declared constructor,
6678 // complain about any non-static data members of reference or const scalar
6679 // type, since they will never get initializers.
6680 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
6681 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
6682 !Record->isLambda()) {
6683 bool Complained = false;
6684 for (const auto *F : Record->fields()) {
6685 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
6686 continue;
6687
6688 if (F->getType()->isReferenceType() ||
6689 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
6690 if (!Complained) {
6691 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
6692 << Record->getTagKind() << Record;
6693 Complained = true;
6694 }
6695
6696 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
6697 << F->getType()->isReferenceType()
6698 << F->getDeclName();
6699 }
6700 }
6701 }
6702
6703 if (Record->getIdentifier()) {
6704 // C++ [class.mem]p13:
6705 // If T is the name of a class, then each of the following shall have a
6706 // name different from T:
6707 // - every member of every anonymous union that is a member of class T.
6708 //
6709 // C++ [class.mem]p14:
6710 // In addition, if class T has a user-declared constructor (12.1), every
6711 // non-static data member of class T shall have a name different from T.
6712 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
6713 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
6714 ++I) {
6715 NamedDecl *D = (*I)->getUnderlyingDecl();
6716 if (((isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D)) &&
6717 Record->hasUserDeclaredConstructor()) ||
6718 isa<IndirectFieldDecl>(D)) {
6719 Diag((*I)->getLocation(), diag::err_member_name_of_class)
6720 << D->getDeclName();
6721 break;
6722 }
6723 }
6724 }
6725
6726 // Warn if the class has virtual methods but non-virtual public destructor.
6727 if (Record->isPolymorphic() && !Record->isDependentType()) {
6728 CXXDestructorDecl *dtor = Record->getDestructor();
6729 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
6730 !Record->hasAttr<FinalAttr>())
6731 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
6732 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
6733 }
6734
6735 if (Record->isAbstract()) {
6736 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
6737 Diag(Record->getLocation(), diag::warn_abstract_final_class)
6738 << FA->isSpelledAsSealed();
6739 DiagnoseAbstractType(Record);
6740 }
6741 }
6742
6743 // Warn if the class has a final destructor but is not itself marked final.
6744 if (!Record->hasAttr<FinalAttr>()) {
6745 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
6746 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
6747 Diag(FA->getLocation(), diag::warn_final_dtor_non_final_class)
6748 << FA->isSpelledAsSealed()
6749 << FixItHint::CreateInsertion(
6750 getLocForEndOfToken(Record->getLocation()),
6751 (FA->isSpelledAsSealed() ? " sealed" : " final"));
6752 Diag(Record->getLocation(),
6753 diag::note_final_dtor_non_final_class_silence)
6754 << Context.getRecordType(Record) << FA->isSpelledAsSealed();
6755 }
6756 }
6757 }
6758
6759 // See if trivial_abi has to be dropped.
6760 if (Record->hasAttr<TrivialABIAttr>())
6761 checkIllFormedTrivialABIStruct(*Record);
6762
6763 // Set HasTrivialSpecialMemberForCall if the record has attribute
6764 // "trivial_abi".
6765 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
6766
6767 if (HasTrivialABI)
6768 Record->setHasTrivialSpecialMemberForCall();
6769
6770 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
6771 // We check these last because they can depend on the properties of the
6772 // primary comparison functions (==, <=>).
6773 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
6774
6775 // Perform checks that can't be done until we know all the properties of a
6776 // member function (whether it's defaulted, deleted, virtual, overriding,
6777 // ...).
6778 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
6779 // A static function cannot override anything.
6780 if (MD->getStorageClass() == SC_Static) {
6781 if (ReportOverrides(*this, diag::err_static_overrides_virtual, MD,
6782 [](const CXXMethodDecl *) { return true; }))
6783 return;
6784 }
6785
6786 // A deleted function cannot override a non-deleted function and vice
6787 // versa.
6788 if (ReportOverrides(*this,
6789 MD->isDeleted() ? diag::err_deleted_override
6790 : diag::err_non_deleted_override,
6791 MD, [&](const CXXMethodDecl *V) {
6792 return MD->isDeleted() != V->isDeleted();
6793 })) {
6794 if (MD->isDefaulted() && MD->isDeleted())
6795 // Explain why this defaulted function was deleted.
6796 DiagnoseDeletedDefaultedFunction(MD);
6797 return;
6798 }
6799
6800 // A consteval function cannot override a non-consteval function and vice
6801 // versa.
6802 if (ReportOverrides(*this,
6803 MD->isConsteval() ? diag::err_consteval_override
6804 : diag::err_non_consteval_override,
6805 MD, [&](const CXXMethodDecl *V) {
6806 return MD->isConsteval() != V->isConsteval();
6807 })) {
6808 if (MD->isDefaulted() && MD->isDeleted())
6809 // Explain why this defaulted function was deleted.
6810 DiagnoseDeletedDefaultedFunction(MD);
6811 return;
6812 }
6813 };
6814
6815 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
6816 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
6817 return false;
6818
6819 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
6820 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
6821 DFK.asComparison() == DefaultedComparisonKind::Relational) {
6822 DefaultedSecondaryComparisons.push_back(FD);
6823 return true;
6824 }
6825
6826 CheckExplicitlyDefaultedFunction(S, FD);
6827 return false;
6828 };
6829
6830 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
6831 // Check whether the explicitly-defaulted members are valid.
6832 bool Incomplete = CheckForDefaultedFunction(M);
6833
6834 // Skip the rest of the checks for a member of a dependent class.
6835 if (Record->isDependentType())
6836 return;
6837
6838 // For an explicitly defaulted or deleted special member, we defer
6839 // determining triviality until the class is complete. That time is now!
6840 CXXSpecialMember CSM = getSpecialMember(M);
6841 if (!M->isImplicit() && !M->isUserProvided()) {
6842 if (CSM != CXXInvalid) {
6843 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
6844 // Inform the class that we've finished declaring this member.
6845 Record->finishedDefaultedOrDeletedMember(M);
6846 M->setTrivialForCall(
6847 HasTrivialABI ||
6848 SpecialMemberIsTrivial(M, CSM, TAH_ConsiderTrivialABI));
6849 Record->setTrivialForCallFlags(M);
6850 }
6851 }
6852
6853 // Set triviality for the purpose of calls if this is a user-provided
6854 // copy/move constructor or destructor.
6855 if ((CSM == CXXCopyConstructor || CSM == CXXMoveConstructor ||
6856 CSM == CXXDestructor) && M->isUserProvided()) {
6857 M->setTrivialForCall(HasTrivialABI);
6858 Record->setTrivialForCallFlags(M);
6859 }
6860
6861 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
6862 M->hasAttr<DLLExportAttr>()) {
6863 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
6864 M->isTrivial() &&
6865 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
6866 CSM == CXXDestructor))
6867 M->dropAttr<DLLExportAttr>();
6868
6869 if (M->hasAttr<DLLExportAttr>()) {
6870 // Define after any fields with in-class initializers have been parsed.
6871 DelayedDllExportMemberFunctions.push_back(M);
6872 }
6873 }
6874
6875 // Define defaulted constexpr virtual functions that override a base class
6876 // function right away.
6877 // FIXME: We can defer doing this until the vtable is marked as used.
6878 if (M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods())
6879 DefineDefaultedFunction(*this, M, M->getLocation());
6880
6881 if (!Incomplete)
6882 CheckCompletedMemberFunction(M);
6883 };
6884
6885 // Check the destructor before any other member function. We need to
6886 // determine whether it's trivial in order to determine whether the claas
6887 // type is a literal type, which is a prerequisite for determining whether
6888 // other special member functions are valid and whether they're implicitly
6889 // 'constexpr'.
6890 if (CXXDestructorDecl *Dtor = Record->getDestructor())
6891 CompleteMemberFunction(Dtor);
6892
6893 bool HasMethodWithOverrideControl = false,
6894 HasOverridingMethodWithoutOverrideControl = false;
6895 for (auto *D : Record->decls()) {
6896 if (auto *M = dyn_cast<CXXMethodDecl>(D)) {
6897 // FIXME: We could do this check for dependent types with non-dependent
6898 // bases.
6899 if (!Record->isDependentType()) {
6900 // See if a method overloads virtual methods in a base
6901 // class without overriding any.
6902 if (!M->isStatic())
6903 DiagnoseHiddenVirtualMethods(M);
6904 if (M->hasAttr<OverrideAttr>())
6905 HasMethodWithOverrideControl = true;
6906 else if (M->size_overridden_methods() > 0)
6907 HasOverridingMethodWithoutOverrideControl = true;
6908 }
6909
6910 if (!isa<CXXDestructorDecl>(M))
6911 CompleteMemberFunction(M);
6912 } else if (auto *F = dyn_cast<FriendDecl>(D)) {
6913 CheckForDefaultedFunction(
6914 dyn_cast_or_null<FunctionDecl>(F->getFriendDecl()));
6915 }
6916 }
6917
6918 if (HasOverridingMethodWithoutOverrideControl) {
6919 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
6920 for (auto *M : Record->methods())
6921 DiagnoseAbsenceOfOverrideControl(M, HasInconsistentOverrideControl);
6922 }
6923
6924 // Check the defaulted secondary comparisons after any other member functions.
6925 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
6926 CheckExplicitlyDefaultedFunction(S, FD);
6927
6928 // If this is a member function, we deferred checking it until now.
6929 if (auto *MD = dyn_cast<CXXMethodDecl>(FD))
6930 CheckCompletedMemberFunction(MD);
6931 }
6932
6933 // ms_struct is a request to use the same ABI rules as MSVC. Check
6934 // whether this class uses any C++ features that are implemented
6935 // completely differently in MSVC, and if so, emit a diagnostic.
6936 // That diagnostic defaults to an error, but we allow projects to
6937 // map it down to a warning (or ignore it). It's a fairly common
6938 // practice among users of the ms_struct pragma to mass-annotate
6939 // headers, sweeping up a bunch of types that the project doesn't
6940 // really rely on MSVC-compatible layout for. We must therefore
6941 // support "ms_struct except for C++ stuff" as a secondary ABI.
6942 // Don't emit this diagnostic if the feature was enabled as a
6943 // language option (as opposed to via a pragma or attribute), as
6944 // the option -mms-bitfields otherwise essentially makes it impossible
6945 // to build C++ code, unless this diagnostic is turned off.
6946 if (Record->isMsStruct(Context) && !Context.getLangOpts().MSBitfields &&
6947 (Record->isPolymorphic() || Record->getNumBases())) {
6948 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
6949 }
6950
6951 checkClassLevelDLLAttribute(Record);
6952 checkClassLevelCodeSegAttribute(Record);
6953
6954 bool ClangABICompat4 =
6955 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
6956 TargetInfo::CallingConvKind CCK =
6957 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
6958 bool CanPass = canPassInRegisters(*this, Record, CCK);
6959
6960 // Do not change ArgPassingRestrictions if it has already been set to
6961 // APK_CanNeverPassInRegs.
6962 if (Record->getArgPassingRestrictions() != RecordDecl::APK_CanNeverPassInRegs)
6963 Record->setArgPassingRestrictions(CanPass
6964 ? RecordDecl::APK_CanPassInRegs
6965 : RecordDecl::APK_CannotPassInRegs);
6966
6967 // If canPassInRegisters returns true despite the record having a non-trivial
6968 // destructor, the record is destructed in the callee. This happens only when
6969 // the record or one of its subobjects has a field annotated with trivial_abi
6970 // or a field qualified with ObjC __strong/__weak.
6971 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
6972 Record->setParamDestroyedInCallee(true);
6973 else if (Record->hasNonTrivialDestructor())
6974 Record->setParamDestroyedInCallee(CanPass);
6975
6976 if (getLangOpts().ForceEmitVTables) {
6977 // If we want to emit all the vtables, we need to mark it as used. This
6978 // is especially required for cases like vtable assumption loads.
6979 MarkVTableUsed(Record->getInnerLocStart(), Record);
6980 }
6981
6982 if (getLangOpts().CUDA) {
6983 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
6984 checkCUDADeviceBuiltinSurfaceClassTemplate(*this, Record);
6985 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
6986 checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
6987 }
6988}
6989
6990/// Look up the special member function that would be called by a special
6991/// member function for a subobject of class type.
6992///
6993/// \param Class The class type of the subobject.
6994/// \param CSM The kind of special member function.
6995/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
6996/// \param ConstRHS True if this is a copy operation with a const object
6997/// on its RHS, that is, if the argument to the outer special member
6998/// function is 'const' and this is not a field marked 'mutable'.
6999static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
7000 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
7001 unsigned FieldQuals, bool ConstRHS) {
7002 unsigned LHSQuals = 0;
7003 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
7004 LHSQuals = FieldQuals;
7005
7006 unsigned RHSQuals = FieldQuals;
7007 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
7008 RHSQuals = 0;
7009 else if (ConstRHS)
7010 RHSQuals |= Qualifiers::Const;
7011
7012 return S.LookupSpecialMember(Class, CSM,
7013 RHSQuals & Qualifiers::Const,
7014 RHSQuals & Qualifiers::Volatile,
7015 false,
7016 LHSQuals & Qualifiers::Const,
7017 LHSQuals & Qualifiers::Volatile);
7018}
7019
7020class Sema::InheritedConstructorInfo {
7021 Sema &S;
7022 SourceLocation UseLoc;
7023
7024 /// A mapping from the base classes through which the constructor was
7025 /// inherited to the using shadow declaration in that base class (or a null
7026 /// pointer if the constructor was declared in that base class).
7027 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7028 InheritedFromBases;
7029
7030public:
7031 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7032 ConstructorUsingShadowDecl *Shadow)
7033 : S(S), UseLoc(UseLoc) {
7034 bool DiagnosedMultipleConstructedBases = false;
7035 CXXRecordDecl *ConstructedBase = nullptr;
7036 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7037
7038 // Find the set of such base class subobjects and check that there's a
7039 // unique constructed subobject.
7040 for (auto *D : Shadow->redecls()) {
7041 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
7042 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7043 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7044
7045 InheritedFromBases.insert(
7046 std::make_pair(DNominatedBase->getCanonicalDecl(),
7047 DShadow->getNominatedBaseClassShadowDecl()));
7048 if (DShadow->constructsVirtualBase())
7049 InheritedFromBases.insert(
7050 std::make_pair(DConstructedBase->getCanonicalDecl(),
7051 DShadow->getConstructedBaseClassShadowDecl()));
7052 else
7053 assert(DNominatedBase == DConstructedBase)(static_cast<void> (0));
7054
7055 // [class.inhctor.init]p2:
7056 // If the constructor was inherited from multiple base class subobjects
7057 // of type B, the program is ill-formed.
7058 if (!ConstructedBase) {
7059 ConstructedBase = DConstructedBase;
7060 ConstructedBaseIntroducer = D->getIntroducer();
7061 } else if (ConstructedBase != DConstructedBase &&
7062 !Shadow->isInvalidDecl()) {
7063 if (!DiagnosedMultipleConstructedBases) {
7064 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
7065 << Shadow->getTargetDecl();
7066 S.Diag(ConstructedBaseIntroducer->getLocation(),
7067 diag::note_ambiguous_inherited_constructor_using)
7068 << ConstructedBase;
7069 DiagnosedMultipleConstructedBases = true;
7070 }
7071 S.Diag(D->getIntroducer()->getLocation(),
7072 diag::note_ambiguous_inherited_constructor_using)
7073 << DConstructedBase;
7074 }
7075 }
7076
7077 if (DiagnosedMultipleConstructedBases)
7078 Shadow->setInvalidDecl();
7079 }
7080
7081 /// Find the constructor to use for inherited construction of a base class,
7082 /// and whether that base class constructor inherits the constructor from a
7083 /// virtual base class (in which case it won't actually invoke it).
7084 std::pair<CXXConstructorDecl *, bool>
7085 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7086 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
7087 if (It == InheritedFromBases.end())
7088 return std::make_pair(nullptr, false);
7089
7090 // This is an intermediary class.
7091 if (It->second)
7092 return std::make_pair(
7093 S.findInheritingConstructor(UseLoc, Ctor, It->second),
7094 It->second->constructsVirtualBase());
7095
7096 // This is the base class from which the constructor was inherited.
7097 return std::make_pair(Ctor, false);
7098 }
7099};
7100
7101/// Is the special member function which would be selected to perform the
7102/// specified operation on the specified class type a constexpr constructor?
7103static bool
7104specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
7105 Sema::CXXSpecialMember CSM, unsigned Quals,
7106 bool ConstRHS,
7107 CXXConstructorDecl *InheritedCtor = nullptr,
7108 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7109 // If we're inheriting a constructor, see if we need to call it for this base
7110 // class.
7111 if (InheritedCtor) {
7112 assert(CSM == Sema::CXXDefaultConstructor)(static_cast<void> (0));
7113 auto BaseCtor =
7114 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
7115 if (BaseCtor)
7116 return BaseCtor->isConstexpr();
7117 }
7118
7119 if (CSM == Sema::CXXDefaultConstructor)
7120 return ClassDecl->hasConstexprDefaultConstructor();
7121 if (CSM == Sema::CXXDestructor)
7122 return ClassDecl->hasConstexprDestructor();
7123
7124 Sema::SpecialMemberOverloadResult SMOR =
7125 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
7126 if (!SMOR.getMethod())
7127 // A constructor we wouldn't select can't be "involved in initializing"
7128 // anything.
7129 return true;
7130 return SMOR.getMethod()->isConstexpr();
7131}
7132
7133/// Determine whether the specified special member function would be constexpr
7134/// if it were implicitly defined.
7135static bool defaultedSpecialMemberIsConstexpr(
7136 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
7137 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
7138 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7139 if (!S.getLangOpts().CPlusPlus11)
7140 return false;
7141
7142 // C++11 [dcl.constexpr]p4:
7143 // In the definition of a constexpr constructor [...]
7144 bool Ctor = true;
7145 switch (CSM) {
7146 case Sema::CXXDefaultConstructor:
7147 if (Inherited)
7148 break;
7149 // Since default constructor lookup is essentially trivial (and cannot
7150 // involve, for instance, template instantiation), we compute whether a
7151 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7152 //
7153 // This is important for performance; we need to know whether the default
7154 // constructor is constexpr to determine whether the type is a literal type.
7155 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7156
7157 case Sema::CXXCopyConstructor:
7158 case Sema::CXXMoveConstructor:
7159 // For copy or move constructors, we need to perform overload resolution.
7160 break;
7161
7162 case Sema::CXXCopyAssignment:
7163 case Sema::CXXMoveAssignment:
7164 if (!S.getLangOpts().CPlusPlus14)
7165 return false;
7166 // In C++1y, we need to perform overload resolution.
7167 Ctor = false;
7168 break;
7169
7170 case Sema::CXXDestructor:
7171 return ClassDecl->defaultedDestructorIsConstexpr();
7172
7173 case Sema::CXXInvalid:
7174 return false;
7175 }
7176
7177 // -- if the class is a non-empty union, or for each non-empty anonymous
7178 // union member of a non-union class, exactly one non-static data member
7179 // shall be initialized; [DR1359]
7180 //
7181 // If we squint, this is guaranteed, since exactly one non-static data member
7182 // will be initialized (if the constructor isn't deleted), we just don't know
7183 // which one.
7184 if (Ctor && ClassDecl->isUnion())
7185 return CSM == Sema::CXXDefaultConstructor
7186 ? ClassDecl->hasInClassInitializer() ||
7187 !ClassDecl->hasVariantMembers()
7188 : true;
7189
7190 // -- the class shall not have any virtual base classes;
7191 if (Ctor && ClassDecl->getNumVBases())
7192 return false;
7193
7194 // C++1y [class.copy]p26:
7195 // -- [the class] is a literal type, and
7196 if (!Ctor && !ClassDecl->isLiteral())
7197 return false;
7198
7199 // -- every constructor involved in initializing [...] base class
7200 // sub-objects shall be a constexpr constructor;
7201 // -- the assignment operator selected to copy/move each direct base
7202 // class is a constexpr function, and
7203 for (const auto &B : ClassDecl->bases()) {
7204 const RecordType *BaseType = B.getType()->getAs<RecordType>();
7205 if (!BaseType) continue;
7206
7207 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
7208 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
7209 InheritedCtor, Inherited))
7210 return false;
7211 }
7212
7213 // -- every constructor involved in initializing non-static data members
7214 // [...] shall be a constexpr constructor;
7215 // -- every non-static data member and base class sub-object shall be
7216 // initialized
7217 // -- for each non-static data member of X that is of class type (or array
7218 // thereof), the assignment operator selected to copy/move that member is
7219 // a constexpr function
7220 for (const auto *F : ClassDecl->fields()) {
7221 if (F->isInvalidDecl())
7222 continue;
7223 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
7224 continue;
7225 QualType BaseType = S.Context.getBaseElementType(F->getType());
7226 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
7227 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
7228 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
7229 BaseType.getCVRQualifiers(),
7230 ConstArg && !F->isMutable()))
7231 return false;
7232 } else if (CSM == Sema::CXXDefaultConstructor) {
7233 return false;
7234 }
7235 }
7236
7237 // All OK, it's constexpr!
7238 return true;
7239}
7240
7241namespace {
7242/// RAII object to register a defaulted function as having its exception
7243/// specification computed.
7244struct ComputingExceptionSpec {
7245 Sema &S;
7246
7247 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7248 : S(S) {
7249 Sema::CodeSynthesisContext Ctx;
7250 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7251 Ctx.PointOfInstantiation = Loc;
7252 Ctx.Entity = FD;
7253 S.pushCodeSynthesisContext(Ctx);
7254 }
7255 ~ComputingExceptionSpec() {
7256 S.popCodeSynthesisContext();
7257 }
7258};
7259}
7260
7261static Sema::ImplicitExceptionSpecification
7262ComputeDefaultedSpecialMemberExceptionSpec(
7263 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
7264 Sema::InheritedConstructorInfo *ICI);
7265
7266static Sema::ImplicitExceptionSpecification
7267ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7268 FunctionDecl *FD,
7269 Sema::DefaultedComparisonKind DCK);
7270
7271static Sema::ImplicitExceptionSpecification
7272computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7273 auto DFK = S.getDefaultedFunctionKind(FD);
7274 if (DFK.isSpecialMember())
7275 return ComputeDefaultedSpecialMemberExceptionSpec(
7276 S, Loc, cast<CXXMethodDecl>(FD), DFK.asSpecialMember(), nullptr);
7277 if (DFK.isComparison())
7278 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7279 DFK.asComparison());
7280
7281 auto *CD = cast<CXXConstructorDecl>(FD);
7282 assert(CD->getInheritedConstructor() &&(static_cast<void> (0))
7283 "only defaulted functions and inherited constructors have implicit "(static_cast<void> (0))
7284 "exception specs")(static_cast<void> (0));
7285 Sema::InheritedConstructorInfo ICI(
7286 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7287 return ComputeDefaultedSpecialMemberExceptionSpec(
7288 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
7289}
7290
7291static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7292 CXXMethodDecl *MD) {
7293 FunctionProtoType::ExtProtoInfo EPI;
7294
7295 // Build an exception specification pointing back at this member.
7296 EPI.ExceptionSpec.Type = EST_Unevaluated;
7297 EPI.ExceptionSpec.SourceDecl = MD;
7298
7299 // Set the calling convention to the default for C++ instance methods.
7300 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7301 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7302 /*IsCXXMethod=*/true));
7303 return EPI;
7304}
7305
7306void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7307 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7308 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7309 return;
7310
7311 // Evaluate the exception specification.
7312 auto IES = computeImplicitExceptionSpec(*this, Loc, FD);
7313 auto ESI = IES.getExceptionSpec();
7314
7315 // Update the type of the special member to use it.
7316 UpdateExceptionSpec(FD, ESI);
7317}
7318
7319void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7320 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted")(static_cast<void> (0));
7321
7322 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7323 if (!DefKind) {
7324 assert(FD->getDeclContext()->isDependentContext())(static_cast<void> (0));
7325 return;
7326 }
7327
7328 if (DefKind.isComparison())
7329 UnusedPrivateFields.clear();
7330
7331 if (DefKind.isSpecialMember()
7332 ? CheckExplicitlyDefaultedSpecialMember(cast<CXXMethodDecl>(FD),
7333 DefKind.asSpecialMember())
7334 : CheckExplicitlyDefaultedComparison(S, FD, DefKind.asComparison()))
7335 FD->setInvalidDecl();
7336}
7337
7338bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7339 CXXSpecialMember CSM) {
7340 CXXRecordDecl *RD = MD->getParent();
7341
7342 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&(static_cast<void> (0))
7343 "not an explicitly-defaulted special member")(static_cast<void> (0));
7344
7345 // Defer all checking for special members of a dependent type.
7346 if (RD->isDependentType())
7347 return false;
7348
7349 // Whether this was the first-declared instance of the constructor.
7350 // This affects whether we implicitly add an exception spec and constexpr.
7351 bool First = MD == MD->getCanonicalDecl();
7352
7353 bool HadError = false;
7354
7355 // C++11 [dcl.fct.def.default]p1:
7356 // A function that is explicitly defaulted shall
7357 // -- be a special member function [...] (checked elsewhere),
7358 // -- have the same type (except for ref-qualifiers, and except that a
7359 // copy operation can take a non-const reference) as an implicit
7360 // declaration, and
7361 // -- not have default arguments.
7362 // C++2a changes the second bullet to instead delete the function if it's
7363 // defaulted on its first declaration, unless it's "an assignment operator,
7364 // and its return type differs or its parameter type is not a reference".
7365 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7366 bool ShouldDeleteForTypeMismatch = false;
7367 unsigned ExpectedParams = 1;
7368 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
7369 ExpectedParams = 0;
7370 if (MD->getNumParams() != ExpectedParams) {
7371 // This checks for default arguments: a copy or move constructor with a
7372 // default argument is classified as a default constructor, and assignment
7373 // operations and destructors can't have default arguments.
7374 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
7375 << CSM << MD->getSourceRange();
7376 HadError = true;
7377 } else if (MD->isVariadic()) {
7378 if (DeleteOnTypeMismatch)
7379 ShouldDeleteForTypeMismatch = true;
7380 else {
7381 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
7382 << CSM << MD->getSourceRange();
7383 HadError = true;
7384 }
7385 }
7386
7387 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
7388
7389 bool CanHaveConstParam = false;
7390 if (CSM == CXXCopyConstructor)
7391 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7392 else if (CSM == CXXCopyAssignment)
7393 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7394
7395 QualType ReturnType = Context.VoidTy;
7396 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
7397 // Check for return type matching.
7398 ReturnType = Type->getReturnType();
7399
7400 QualType DeclType = Context.getTypeDeclType(RD);
7401 DeclType = Context.getAddrSpaceQualType(DeclType, MD->getMethodQualifiers().getAddressSpace());
7402 QualType ExpectedReturnType = Context.getLValueReferenceType(DeclType);
7403
7404 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
7405 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
7406 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
7407 HadError = true;
7408 }
7409
7410 // A defaulted special member cannot have cv-qualifiers.
7411 if (Type->getMethodQuals().hasConst() || Type->getMethodQuals().hasVolatile()) {
7412 if (DeleteOnTypeMismatch)
7413 ShouldDeleteForTypeMismatch = true;
7414 else {
7415 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
7416 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
7417 HadError = true;
7418 }
7419 }
7420 }
7421
7422 // Check for parameter type matching.
7423 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
7424 bool HasConstParam = false;
7425 if (ExpectedParams && ArgType->isReferenceType()) {
7426 // Argument must be reference to possibly-const T.
7427 QualType ReferentType = ArgType->getPointeeType();
7428 HasConstParam = ReferentType.isConstQualified();
7429
7430 if (ReferentType.isVolatileQualified()) {
7431 if (DeleteOnTypeMismatch)
7432 ShouldDeleteForTypeMismatch = true;
7433 else {
7434 Diag(MD->getLocation(),
7435 diag::err_defaulted_special_member_volatile_param) << CSM;
7436 HadError = true;
7437 }
7438 }
7439
7440 if (HasConstParam && !CanHaveConstParam) {
7441 if (DeleteOnTypeMismatch)
7442 ShouldDeleteForTypeMismatch = true;
7443 else if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
7444 Diag(MD->getLocation(),
7445 diag::err_defaulted_special_member_copy_const_param)
7446 << (CSM == CXXCopyAssignment);
7447 // FIXME: Explain why this special member can't be const.
7448 HadError = true;
7449 } else {
7450 Diag(MD->getLocation(),
7451 diag::err_defaulted_special_member_move_const_param)
7452 << (CSM == CXXMoveAssignment);
7453 HadError = true;
7454 }
7455 }
7456 } else if (ExpectedParams) {
7457 // A copy assignment operator can take its argument by value, but a
7458 // defaulted one cannot.
7459 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument")(static_cast<void> (0));
7460 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
7461 HadError = true;
7462 }
7463
7464 // C++11 [dcl.fct.def.default]p2:
7465 // An explicitly-defaulted function may be declared constexpr only if it
7466 // would have been implicitly declared as constexpr,
7467 // Do not apply this rule to members of class templates, since core issue 1358
7468 // makes such functions always instantiate to constexpr functions. For
7469 // functions which cannot be constexpr (for non-constructors in C++11 and for
7470 // destructors in C++14 and C++17), this is checked elsewhere.
7471 //
7472 // FIXME: This should not apply if the member is deleted.
7473 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
7474 HasConstParam);
7475 if ((getLangOpts().CPlusPlus20 ||
7476 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
7477 : isa<CXXConstructorDecl>(MD))) &&
7478 MD->isConstexpr() && !Constexpr &&
7479 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
7480 Diag(MD->getBeginLoc(), MD->isConsteval()
7481 ? diag::err_incorrect_defaulted_consteval
7482 : diag::err_incorrect_defaulted_constexpr)
7483 << CSM;
7484 // FIXME: Explain why the special member can't be constexpr.
7485 HadError = true;
7486 }
7487
7488 if (First) {
7489 // C++2a [dcl.fct.def.default]p3:
7490 // If a function is explicitly defaulted on its first declaration, it is
7491 // implicitly considered to be constexpr if the implicit declaration
7492 // would be.
7493 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
7494 ? ConstexprSpecKind::Consteval
7495 : ConstexprSpecKind::Constexpr)
7496 : ConstexprSpecKind::Unspecified);
7497
7498 if (!Type->hasExceptionSpec()) {
7499 // C++2a [except.spec]p3:
7500 // If a declaration of a function does not have a noexcept-specifier
7501 // [and] is defaulted on its first declaration, [...] the exception
7502 // specification is as specified below
7503 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
7504 EPI.ExceptionSpec.Type = EST_Unevaluated;
7505 EPI.ExceptionSpec.SourceDecl = MD;
7506 MD->setType(Context.getFunctionType(ReturnType,
7507 llvm::makeArrayRef(&ArgType,
7508 ExpectedParams),
7509 EPI));
7510 }
7511 }
7512
7513 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
7514 if (First) {
7515 SetDeclDeleted(MD, MD->getLocation());
7516 if (!inTemplateInstantiation() && !HadError) {
7517 Diag(MD->getLocation(), diag::warn_defaulted_method_deleted) << CSM;
7518 if (ShouldDeleteForTypeMismatch) {
7519 Diag(MD->getLocation(), diag::note_deleted_type_mismatch) << CSM;
7520 } else {
7521 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7522 }
7523 }
7524 if (ShouldDeleteForTypeMismatch && !HadError) {
7525 Diag(MD->getLocation(),
7526 diag::warn_cxx17_compat_defaulted_method_type_mismatch) << CSM;
7527 }
7528 } else {
7529 // C++11 [dcl.fct.def.default]p4:
7530 // [For a] user-provided explicitly-defaulted function [...] if such a
7531 // function is implicitly defined as deleted, the program is ill-formed.
7532 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
7533 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl")(static_cast<void> (0));
7534 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
7535 HadError = true;
7536 }
7537 }
7538
7539 return HadError;
7540}
7541
7542namespace {
7543/// Helper class for building and checking a defaulted comparison.
7544///
7545/// Defaulted functions are built in two phases:
7546///
7547/// * First, the set of operations that the function will perform are
7548/// identified, and some of them are checked. If any of the checked
7549/// operations is invalid in certain ways, the comparison function is
7550/// defined as deleted and no body is built.
7551/// * Then, if the function is not defined as deleted, the body is built.
7552///
7553/// This is accomplished by performing two visitation steps over the eventual
7554/// body of the function.
7555template<typename Derived, typename ResultList, typename Result,
7556 typename Subobject>
7557class DefaultedComparisonVisitor {
7558public:
7559 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
7560
7561 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7562 DefaultedComparisonKind DCK)
7563 : S(S), RD(RD), FD(FD), DCK(DCK) {
7564 if (auto *Info = FD->getDefaultedFunctionInfo()) {
7565 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
7566 // UnresolvedSet to avoid this copy.
7567 Fns.assign(Info->getUnqualifiedLookups().begin(),
7568 Info->getUnqualifiedLookups().end());
7569 }
7570 }
7571
7572 ResultList visit() {
7573 // The type of an lvalue naming a parameter of this function.
7574 QualType ParamLvalType =
7575 FD->getParamDecl(0)->getType().getNonReferenceType();
7576
7577 ResultList Results;
7578
7579 switch (DCK) {
7580 case DefaultedComparisonKind::None:
7581 llvm_unreachable("not a defaulted comparison")__builtin_unreachable();
7582
7583 case DefaultedComparisonKind::Equal:
7584 case DefaultedComparisonKind::ThreeWay:
7585 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
7586 return Results;
7587
7588 case DefaultedComparisonKind::NotEqual:
7589 case DefaultedComparisonKind::Relational:
7590 Results.add(getDerived().visitExpandedSubobject(
7591 ParamLvalType, getDerived().getCompleteObject()));
7592 return Results;
7593 }
7594 llvm_unreachable("")__builtin_unreachable();
7595 }
7596
7597protected:
7598 Derived &getDerived() { return static_cast<Derived&>(*this); }
7599
7600 /// Visit the expanded list of subobjects of the given type, as specified in
7601 /// C++2a [class.compare.default].
7602 ///
7603 /// \return \c true if the ResultList object said we're done, \c false if not.
7604 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
7605 Qualifiers Quals) {
7606 // C++2a [class.compare.default]p4:
7607 // The direct base class subobjects of C
7608 for (CXXBaseSpecifier &Base : Record->bases())
7609 if (Results.add(getDerived().visitSubobject(
7610 S.Context.getQualifiedType(Base.getType(), Quals),
7611 getDerived().getBase(&Base))))
7612 return true;
7613
7614 // followed by the non-static data members of C
7615 for (FieldDecl *Field : Record->fields()) {
7616 // Recursively expand anonymous structs.
7617 if (Field->isAnonymousStructOrUnion()) {
7618 if (visitSubobjects(Results, Field->getType()->getAsCXXRecordDecl(),
7619 Quals))
7620 return true;
7621 continue;
7622 }
7623
7624 // Figure out the type of an lvalue denoting this field.
7625 Qualifiers FieldQuals = Quals;
7626 if (Field->isMutable())
7627 FieldQuals.removeConst();
7628 QualType FieldType =
7629 S.Context.getQualifiedType(Field->getType(), FieldQuals);
7630
7631 if (Results.add(getDerived().visitSubobject(
7632 FieldType, getDerived().getField(Field))))
7633 return true;
7634 }
7635
7636 // form a list of subobjects.
7637 return false;
7638 }
7639
7640 Result visitSubobject(QualType Type, Subobject Subobj) {
7641 // In that list, any subobject of array type is recursively expanded
7642 const ArrayType *AT = S.Context.getAsArrayType(Type);
7643 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(AT))
7644 return getDerived().visitSubobjectArray(CAT->getElementType(),
7645 CAT->getSize(), Subobj);
7646 return getDerived().visitExpandedSubobject(Type, Subobj);
7647 }
7648
7649 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
7650 Subobject Subobj) {
7651 return getDerived().visitSubobject(Type, Subobj);
7652 }
7653
7654protected:
7655 Sema &S;
7656 CXXRecordDecl *RD;
7657 FunctionDecl *FD;
7658 DefaultedComparisonKind DCK;
7659 UnresolvedSet<16> Fns;
7660};
7661
7662/// Information about a defaulted comparison, as determined by
7663/// DefaultedComparisonAnalyzer.
7664struct DefaultedComparisonInfo {
7665 bool Deleted = false;
7666 bool Constexpr = true;
7667 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
7668
7669 static DefaultedComparisonInfo deleted() {
7670 DefaultedComparisonInfo Deleted;
7671 Deleted.Deleted = true;
7672 return Deleted;
7673 }
7674
7675 bool add(const DefaultedComparisonInfo &R) {
7676 Deleted |= R.Deleted;
7677 Constexpr &= R.Constexpr;
7678 Category = commonComparisonType(Category, R.Category);
7679 return Deleted;
7680 }
7681};
7682
7683/// An element in the expanded list of subobjects of a defaulted comparison, as
7684/// specified in C++2a [class.compare.default]p4.
7685struct DefaultedComparisonSubobject {
7686 enum { CompleteObject, Member, Base } Kind;
7687 NamedDecl *Decl;
7688 SourceLocation Loc;
7689};
7690
7691/// A visitor over the notional body of a defaulted comparison that determines
7692/// whether that body would be deleted or constexpr.
7693class DefaultedComparisonAnalyzer
7694 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
7695 DefaultedComparisonInfo,
7696 DefaultedComparisonInfo,
7697 DefaultedComparisonSubobject> {
7698public:
7699 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
7700
7701private:
7702 DiagnosticKind Diagnose;
7703
7704public:
7705 using Base = DefaultedComparisonVisitor;
7706 using Result = DefaultedComparisonInfo;
7707 using Subobject = DefaultedComparisonSubobject;
7708
7709 friend Base;
7710
7711 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
7712 DefaultedComparisonKind DCK,
7713 DiagnosticKind Diagnose = NoDiagnostics)
7714 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
7715
7716 Result visit() {
7717 if ((DCK == DefaultedComparisonKind::Equal ||
7718 DCK == DefaultedComparisonKind::ThreeWay) &&
7719 RD->hasVariantMembers()) {
7720 // C++2a [class.compare.default]p2 [P2002R0]:
7721 // A defaulted comparison operator function for class C is defined as
7722 // deleted if [...] C has variant members.
7723 if (Diagnose == ExplainDeleted) {
7724 S.Diag(FD->getLocation(), diag::note_defaulted_comparison_union)
7725 << FD << RD->isUnion() << RD;
7726 }
7727 return Result::deleted();
7728 }
7729
7730 return Base::visit();
7731 }
7732
7733private:
7734 Subobject getCompleteObject() {
7735 return Subobject{Subobject::CompleteObject, RD, FD->getLocation()};
7736 }
7737
7738 Subobject getBase(CXXBaseSpecifier *Base) {
7739 return Subobject{Subobject::Base, Base->getType()->getAsCXXRecordDecl(),
7740 Base->getBaseTypeLoc()};
7741 }
7742
7743 Subobject getField(FieldDecl *Field) {
7744 return Subobject{Subobject::Member, Field, Field->getLocation()};
7745 }
7746
7747 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
7748 // C++2a [class.compare.default]p2 [P2002R0]:
7749 // A defaulted <=> or == operator function for class C is defined as
7750 // deleted if any non-static data member of C is of reference type
7751 if (Type->isReferenceType()) {
7752 if (Diagnose == ExplainDeleted) {
7753 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_reference_member)
7754 << FD << RD;
7755 }
7756 return Result::deleted();
7757 }
7758
7759 // [...] Let xi be an lvalue denoting the ith element [...]
7760 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
7761 Expr *Args[] = {&Xi, &Xi};
7762
7763 // All operators start by trying to apply that same operator recursively.
7764 OverloadedOperatorKind OO = FD->getOverloadedOperator();
7765 assert(OO != OO_None && "not an overloaded operator!")(static_cast<void> (0));
7766 return visitBinaryOperator(OO, Args, Subobj);
7767 }
7768
7769 Result
7770 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
7771 Subobject Subobj,
7772 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
7773 // Note that there is no need to consider rewritten candidates here if
7774 // we've already found there is no viable 'operator<=>' candidate (and are
7775 // considering synthesizing a '<=>' from '==' and '<').
7776 OverloadCandidateSet CandidateSet(
7777 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
7778 OverloadCandidateSet::OperatorRewriteInfo(
7779 OO, /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
7780
7781 /// C++2a [class.compare.default]p1 [P2002R0]:
7782 /// [...] the defaulted function itself is never a candidate for overload
7783 /// resolution [...]
7784 CandidateSet.exclude(FD);
7785
7786 if (Args[0]->getType()->isOverloadableType())
7787 S.LookupOverloadedBinOp(CandidateSet, OO, Fns, Args);
7788 else
7789 // FIXME: We determine whether this is a valid expression by checking to
7790 // see if there's a viable builtin operator candidate for it. That isn't
7791 // really what the rules ask us to do, but should give the right results.
7792 S.AddBuiltinOperatorCandidates(OO, FD->getLocation(), Args, CandidateSet);
7793
7794 Result R;
7795
7796 OverloadCandidateSet::iterator Best;
7797 switch (CandidateSet.BestViableFunction(S, FD->getLocation(), Best)) {
7798 case OR_Success: {
7799 // C++2a [class.compare.secondary]p2 [P2002R0]:
7800 // The operator function [...] is defined as deleted if [...] the
7801 // candidate selected by overload resolution is not a rewritten
7802 // candidate.
7803 if ((DCK == DefaultedComparisonKind::NotEqual ||
7804 DCK == DefaultedComparisonKind::Relational) &&
7805 !Best->RewriteKind) {
7806 if (Diagnose == ExplainDeleted) {
7807 S.Diag(Best->Function->getLocation(),
7808 diag::note_defaulted_comparison_not_rewritten_callee)
7809 << FD;
7810 }
7811 return Result::deleted();
7812 }
7813
7814 // Throughout C++2a [class.compare]: if overload resolution does not
7815 // result in a usable function, the candidate function is defined as
7816 // deleted. This requires that we selected an accessible function.
7817 //
7818 // Note that this only considers the access of the function when named
7819 // within the type of the subobject, and not the access path for any
7820 // derived-to-base conversion.
7821 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
7822 if (ArgClass && Best->FoundDecl.getDecl() &&
7823 Best->FoundDecl.getDecl()->isCXXClassMember()) {
7824 QualType ObjectType = Subobj.Kind == Subobject::Member
7825 ? Args[0]->getType()
7826 : S.Context.getRecordType(RD);
7827 if (!S.isMemberAccessibleForDeletion(
7828 ArgClass, Best->FoundDecl, ObjectType, Subobj.Loc,
7829 Diagnose == ExplainDeleted
7830 ? S.PDiag(diag::note_defaulted_comparison_inaccessible)
7831 << FD << Subobj.Kind << Subobj.Decl
7832 : S.PDiag()))
7833 return Result::deleted();
7834 }
7835
7836 bool NeedsDeducing =
7837 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
7838
7839 if (FunctionDecl *BestFD = Best->Function) {
7840 // C++2a [class.compare.default]p3 [P2002R0]:
7841 // A defaulted comparison function is constexpr-compatible if
7842 // [...] no overlod resolution performed [...] results in a
7843 // non-constexpr function.
7844 assert(!BestFD->isDeleted() && "wrong overload resolution result")(static_cast<void> (0));
7845 // If it's not constexpr, explain why not.
7846 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
7847 if (Subobj.Kind != Subobject::CompleteObject)
7848 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_not_constexpr)
7849 << Subobj.Kind << Subobj.Decl;
7850 S.Diag(BestFD->getLocation(),
7851 diag::note_defaulted_comparison_not_constexpr_here);
7852 // Bail out after explaining; we don't want any more notes.
7853 return Result::deleted();
7854 }
7855 R.Constexpr &= BestFD->isConstexpr();
7856
7857 if (NeedsDeducing) {
7858 // If any callee has an undeduced return type, deduce it now.
7859 // FIXME: It's not clear how a failure here should be handled. For
7860 // now, we produce an eager diagnostic, because that is forward
7861 // compatible with most (all?) other reasonable options.
7862 if (BestFD->getReturnType()->isUndeducedType() &&
7863 S.DeduceReturnType(BestFD, FD->getLocation(),
7864 /*Diagnose=*/false)) {
7865 // Don't produce a duplicate error when asked to explain why the
7866 // comparison is deleted: we diagnosed that when initially checking
7867 // the defaulted operator.
7868 if (Diagnose == NoDiagnostics) {
7869 S.Diag(
7870 FD->getLocation(),
7871 diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
7872 << Subobj.Kind << Subobj.Decl;
7873 S.Diag(
7874 Subobj.Loc,
7875 diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
7876 << Subobj.Kind << Subobj.Decl;
7877 S.Diag(BestFD->getLocation(),
7878 diag::note_defaulted_comparison_cannot_deduce_callee)
7879 << Subobj.Kind << Subobj.Decl;
7880 }
7881 return Result::deleted();
7882 }
7883 auto *Info = S.Context.CompCategories.lookupInfoForType(
7884 BestFD->getCallResultType());
7885 if (!Info) {
7886 if (Diagnose == ExplainDeleted) {
7887 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_cannot_deduce)
7888 << Subobj.Kind << Subobj.Decl
7889 << BestFD->getCallResultType().withoutLocalFastQualifiers();
7890 S.Diag(BestFD->getLocation(),
7891 diag::note_defaulted_comparison_cannot_deduce_callee)
7892 << Subobj.Kind << Subobj.Decl;
7893 }
7894 return Result::deleted();
7895 }
7896 R.Category = Info->Kind;
7897 }
7898 } else {
7899 QualType T = Best->BuiltinParamTypes[0];
7900 assert(T == Best->BuiltinParamTypes[1] &&(static_cast<void> (0))
7901 "builtin comparison for different types?")(static_cast<void> (0));
7902 assert(Best->BuiltinParamTypes[2].isNull() &&(static_cast<void> (0))
7903 "invalid builtin comparison")(static_cast<void> (0));
7904
7905 if (NeedsDeducing) {
7906 Optional<ComparisonCategoryType> Cat =
7907 getComparisonCategoryForBuiltinCmp(T);
7908 assert(Cat && "no category for builtin comparison?")(static_cast<void> (0));
7909 R.Category = *Cat;
7910 }
7911 }
7912
7913 // Note that we might be rewriting to a different operator. That call is
7914 // not considered until we come to actually build the comparison function.
7915 break;
7916 }
7917
7918 case OR_Ambiguous:
7919 if (Diagnose == ExplainDeleted) {
7920 unsigned Kind = 0;
7921 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
7922 Kind = OO == OO_EqualEqual ? 1 : 2;
7923 CandidateSet.NoteCandidates(
7924 PartialDiagnosticAt(
7925 Subobj.Loc, S.PDiag(diag::note_defaulted_comparison_ambiguous)
7926 << FD << Kind << Subobj.Kind << Subobj.Decl),
7927 S, OCD_AmbiguousCandidates, Args);
7928 }
7929 R = Result::deleted();
7930 break;
7931
7932 case OR_Deleted:
7933 if (Diagnose == ExplainDeleted) {
7934 if ((DCK == DefaultedComparisonKind::NotEqual ||
7935 DCK == DefaultedComparisonKind::Relational) &&
7936 !Best->RewriteKind) {
7937 S.Diag(Best->Function->getLocation(),
7938 diag::note_defaulted_comparison_not_rewritten_callee)
7939 << FD;
7940 } else {
7941 S.Diag(Subobj.Loc,
7942 diag::note_defaulted_comparison_calls_deleted)
7943 << FD << Subobj.Kind << Subobj.Decl;
7944 S.NoteDeletedFunction(Best->Function);
7945 }
7946 }
7947 R = Result::deleted();
7948 break;
7949
7950 case OR_No_Viable_Function:
7951 // If there's no usable candidate, we're done unless we can rewrite a
7952 // '<=>' in terms of '==' and '<'.
7953 if (OO == OO_Spaceship &&
7954 S.Context.CompCategories.lookupInfoForType(FD->getReturnType())) {
7955 // For any kind of comparison category return type, we need a usable
7956 // '==' and a usable '<'.
7957 if (!R.add(visitBinaryOperator(OO_EqualEqual, Args, Subobj,
7958 &CandidateSet)))
7959 R.add(visitBinaryOperator(OO_Less, Args, Subobj, &CandidateSet));
7960 break;
7961 }
7962
7963 if (Diagnose == ExplainDeleted) {
7964 S.Diag(Subobj.Loc, diag::note_defaulted_comparison_no_viable_function)
7965 << FD << Subobj.Kind << Subobj.Decl;
7966
7967 // For a three-way comparison, list both the candidates for the
7968 // original operator and the candidates for the synthesized operator.
7969 if (SpaceshipCandidates) {
7970 SpaceshipCandidates->NoteCandidates(
7971 S, Args,
7972 SpaceshipCandidates->CompleteCandidates(S, OCD_AllCandidates,
7973 Args, FD->getLocation()));
7974 S.Diag(Subobj.Loc,
7975 diag::note_defaulted_comparison_no_viable_function_synthesized)
7976 << (OO == OO_EqualEqual ? 0 : 1);
7977 }
7978
7979 CandidateSet.NoteCandidates(
7980 S, Args,
7981 CandidateSet.CompleteCandidates(S, OCD_AllCandidates, Args,
7982 FD->getLocation()));
7983 }
7984 R = Result::deleted();
7985 break;
7986 }
7987
7988 return R;
7989 }
7990};
7991
7992/// A list of statements.
7993struct StmtListResult {
7994 bool IsInvalid = false;
7995 llvm::SmallVector<Stmt*, 16> Stmts;
7996
7997 bool add(const StmtResult &S) {
7998 IsInvalid |= S.isInvalid();
7999 if (IsInvalid)
8000 return true;
8001 Stmts.push_back(S.get());
8002 return false;
8003 }
8004};
8005
8006/// A visitor over the notional body of a defaulted comparison that synthesizes
8007/// the actual body.
8008class DefaultedComparisonSynthesizer
8009 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8010 StmtListResult, StmtResult,
8011 std::pair<ExprResult, ExprResult>> {
8012 SourceLocation Loc;
8013 unsigned ArrayDepth = 0;
8014
8015public:
8016 using Base = DefaultedComparisonVisitor;
8017 using ExprPair = std::pair<ExprResult, ExprResult>;
8018
8019 friend Base;
8020
8021 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8022 DefaultedComparisonKind DCK,
8023 SourceLocation BodyLoc)
8024 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8025
8026 /// Build a suitable function body for this defaulted comparison operator.
8027 StmtResult build() {
8028 Sema::CompoundScopeRAII CompoundScope(S);
8029
8030 StmtListResult Stmts = visit();
8031 if (Stmts.IsInvalid)
8032 return StmtError();
8033
8034 ExprResult RetVal;
8035 switch (DCK) {
8036 case DefaultedComparisonKind::None:
8037 llvm_unreachable("not a defaulted comparison")__builtin_unreachable();
8038
8039 case DefaultedComparisonKind::Equal: {
8040 // C++2a [class.eq]p3:
8041 // [...] compar[e] the corresponding elements [...] until the first
8042 // index i where xi == yi yields [...] false. If no such index exists,
8043 // V is true. Otherwise, V is false.
8044 //
8045 // Join the comparisons with '&&'s and return the result. Use a right
8046 // fold (traversing the conditions right-to-left), because that
8047 // short-circuits more naturally.
8048 auto OldStmts = std::move(Stmts.Stmts);
8049 Stmts.Stmts.clear();
8050 ExprResult CmpSoFar;
8051 // Finish a particular comparison chain.
8052 auto FinishCmp = [&] {
8053 if (Expr *Prior = CmpSoFar.get()) {
8054 // Convert the last expression to 'return ...;'
8055 if (RetVal.isUnset() && Stmts.Stmts.empty())
8056 RetVal = CmpSoFar;
8057 // Convert any prior comparison to 'if (!(...)) return false;'
8058 else if (Stmts.add(buildIfNotCondReturnFalse(Prior)))
8059 return true;
8060 CmpSoFar = ExprResult();
8061 }
8062 return false;
8063 };
8064 for (Stmt *EAsStmt : llvm::reverse(OldStmts)) {
8065 Expr *E = dyn_cast<Expr>(EAsStmt);
8066 if (!E) {
8067 // Found an array comparison.
8068 if (FinishCmp() || Stmts.add(EAsStmt))
8069 return StmtError();
8070 continue;
8071 }
8072
8073 if (CmpSoFar.isUnset()) {
8074 CmpSoFar = E;
8075 continue;
8076 }
8077 CmpSoFar = S.CreateBuiltinBinOp(Loc, BO_LAnd, E, CmpSoFar.get());
8078 if (CmpSoFar.isInvalid())
8079 return StmtError();
8080 }
8081 if (FinishCmp())
8082 return StmtError();
8083 std::reverse(Stmts.Stmts.begin(), Stmts.Stmts.end());
8084 // If no such index exists, V is true.
8085 if (RetVal.isUnset())
8086 RetVal = S.ActOnCXXBoolLiteral(Loc, tok::kw_true);
8087 break;
8088 }
8089
8090 case DefaultedComparisonKind::ThreeWay: {
8091 // Per C++2a [class.spaceship]p3, as a fallback add:
8092 // return static_cast<R>(std::strong_ordering::equal);
8093 QualType StrongOrdering = S.CheckComparisonCategoryType(
8094 ComparisonCategoryType::StrongOrdering, Loc,
8095 Sema::ComparisonCategoryUsage::DefaultedOperator);
8096 if (StrongOrdering.isNull())
8097 return StmtError();
8098 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(StrongOrdering)
8099 .getValueInfo(ComparisonCategoryResult::Equal)
8100 ->VD;
8101 RetVal = getDecl(EqualVD);
8102 if (RetVal.isInvalid())
8103 return StmtError();
8104 RetVal = buildStaticCastToR(RetVal.get());
8105 break;
8106 }
8107
8108 case DefaultedComparisonKind::NotEqual:
8109 case DefaultedComparisonKind::Relational:
8110 RetVal = cast<Expr>(Stmts.Stmts.pop_back_val());
8111 break;
8112 }
8113
8114 // Build the final return statement.
8115 if (RetVal.isInvalid())
8116 return StmtError();
8117 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, RetVal.get());
8118 if (ReturnStmt.isInvalid())
8119 return StmtError();
8120 Stmts.Stmts.push_back(ReturnStmt.get());
8121
8122 return S.ActOnCompoundStmt(Loc, Loc, Stmts.Stmts, /*IsStmtExpr=*/false);
8123 }
8124
8125private:
8126 ExprResult getDecl(ValueDecl *VD) {
8127 return S.BuildDeclarationNameExpr(
8128 CXXScopeSpec(), DeclarationNameInfo(VD->getDeclName(), Loc), VD);
8129 }
8130
8131 ExprResult getParam(unsigned I) {
8132 ParmVarDecl *PD = FD->getParamDecl(I);
8133 return getDecl(PD);
8134 }
8135
8136 ExprPair getCompleteObject() {
8137 unsigned Param = 0;
8138 ExprResult LHS;
8139 if (isa<CXXMethodDecl>(FD)) {
8140 // LHS is '*this'.
8141 LHS = S.ActOnCXXThis(Loc);
8142 if (!LHS.isInvalid())
8143 LHS = S.CreateBuiltinUnaryOp(Loc, UO_Deref, LHS.get());
8144 } else {
8145 LHS = getParam(Param++);
8146 }
8147 ExprResult RHS = getParam(Param++);
8148 assert(Param == FD->getNumParams())(static_cast<void> (0));
8149 return {LHS, RHS};
8150 }
8151
8152 ExprPair getBase(CXXBaseSpecifier *Base) {
8153 ExprPair Obj = getCompleteObject();
8154 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8155 return {ExprError(), ExprError()};
8156 CXXCastPath Path = {Base};
8157 return {S.ImpCastExprToType(Obj.first.get(), Base->getType(),
8158 CK_DerivedToBase, VK_LValue, &Path),
8159 S.ImpCastExprToType(Obj.second.get(), Base->getType(),
8160 CK_DerivedToBase, VK_LValue, &Path)};
8161 }
8162
8163 ExprPair getField(FieldDecl *Field) {
8164 ExprPair Obj = getCompleteObject();
8165 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8166 return {ExprError(), ExprError()};
8167
8168 DeclAccessPair Found = DeclAccessPair::make(Field, Field->getAccess());
8169 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8170 return {S.BuildFieldReferenceExpr(Obj.first.get(), /*IsArrow=*/false, Loc,
8171 CXXScopeSpec(), Field, Found, NameInfo),
8172 S.BuildFieldReferenceExpr(Obj.second.get(), /*IsArrow=*/false, Loc,
8173 CXXScopeSpec(), Field, Found, NameInfo)};
8174 }
8175
8176 // FIXME: When expanding a subobject, register a note in the code synthesis
8177 // stack to say which subobject we're comparing.
8178
8179 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8180 if (Cond.isInvalid())
8181 return StmtError();
8182
8183 ExprResult NotCond = S.CreateBuiltinUnaryOp(Loc, UO_LNot, Cond.get());
8184 if (NotCond.isInvalid())
8185 return StmtError();
8186
8187 ExprResult False = S.ActOnCXXBoolLiteral(Loc, tok::kw_false);
8188 assert(!False.isInvalid() && "should never fail")(static_cast<void> (0));
8189 StmtResult ReturnFalse = S.BuildReturnStmt(Loc, False.get());
8190 if (ReturnFalse.isInvalid())
8191 return StmtError();
8192
8193 return S.ActOnIfStmt(Loc, false, Loc, nullptr,
8194 S.ActOnCondition(nullptr, Loc, NotCond.get(),
8195 Sema::ConditionKind::Boolean),
8196 Loc, ReturnFalse.get(), SourceLocation(), nullptr);
8197 }
8198
8199 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8200 ExprPair Subobj) {
8201 QualType SizeType = S.Context.getSizeType();
8202 Size = Size.zextOrTrunc(S.Context.getTypeSize(SizeType));
8203
8204 // Build 'size_t i$n = 0'.
8205 IdentifierInfo *IterationVarName = nullptr;
8206 {
8207 SmallString<8> Str;
8208 llvm::raw_svector_ostream OS(Str);
8209 OS << "i" << ArrayDepth;
8210 IterationVarName = &S.Context.Idents.get(OS.str());
8211 }
8212 VarDecl *IterationVar = VarDecl::Create(
8213 S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
8214 S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
8215 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
8216 IterationVar->setInit(
8217 IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
8218 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8219
8220 auto IterRef = [&] {
8221 ExprResult Ref = S.BuildDeclarationNameExpr(
8222 CXXScopeSpec(), DeclarationNameInfo(IterationVarName, Loc),
8223 IterationVar);
8224 assert(!Ref.isInvalid() && "can't reference our own variable?")(static_cast<void> (0));
8225 return Ref.get();
8226 };
8227
8228 // Build 'i$n != Size'.
8229 ExprResult Cond = S.CreateBuiltinBinOp(
8230 Loc, BO_NE, IterRef(),
8231 IntegerLiteral::Create(S.Context, Size, SizeType, Loc));
8232 assert(!Cond.isInvalid() && "should never fail")(static_cast<void> (0));
8233
8234 // Build '++i$n'.
8235 ExprResult Inc = S.CreateBuiltinUnaryOp(Loc, UO_PreInc, IterRef());
8236 assert(!Inc.isInvalid() && "should never fail")(static_cast<void> (0));
8237
8238 // Build 'a[i$n]' and 'b[i$n]'.
8239 auto Index = [&](ExprResult E) {
8240 if (E.isInvalid())
8241 return ExprError();
8242 return S.CreateBuiltinArraySubscriptExpr(E.get(), Loc, IterRef(), Loc);
8243 };
8244 Subobj.first = Index(Subobj.first);
8245 Subobj.second = Index(Subobj.second);
8246
8247 // Compare the array elements.
8248 ++ArrayDepth;
8249 StmtResult Substmt = visitSubobject(Type, Subobj);
8250 --ArrayDepth;
8251
8252 if (Substmt.isInvalid())
8253 return StmtError();
8254
8255 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8256 // For outer levels or for an 'operator<=>' we already have a suitable
8257 // statement that returns as necessary.
8258 if (Expr *ElemCmp = dyn_cast<Expr>(Substmt.get())) {
8259 assert(DCK == DefaultedComparisonKind::Equal &&(static_cast<void> (0))
8260 "should have non-expression statement")(static_cast<void> (0));
8261 Substmt = buildIfNotCondReturnFalse(ElemCmp);
8262 if (Substmt.isInvalid())
8263 return StmtError();
8264 }
8265
8266 // Build 'for (...) ...'
8267 return S.ActOnForStmt(Loc, Loc, Init,
8268 S.ActOnCondition(nullptr, Loc, Cond.get(),
8269 Sema::ConditionKind::Boolean),
8270 S.MakeFullDiscardedValueExpr(Inc.get()), Loc,
8271 Substmt.get());
8272 }
8273
8274 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8275 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8276 return StmtError();
8277
8278 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8279 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8280 ExprResult Op;
8281 if (Type->isOverloadableType())
8282 Op = S.CreateOverloadedBinOp(Loc, Opc, Fns, Obj.first.get(),
8283 Obj.second.get(), /*PerformADL=*/true,
8284 /*AllowRewrittenCandidates=*/true, FD);
8285 else
8286 Op = S.CreateBuiltinBinOp(Loc, Opc, Obj.first.get(), Obj.second.get());
8287 if (Op.isInvalid())
8288 return StmtError();
8289
8290 switch (DCK) {
8291 case DefaultedComparisonKind::None:
8292 llvm_unreachable("not a defaulted comparison")__builtin_unreachable();
8293
8294 case DefaultedComparisonKind::Equal:
8295 // Per C++2a [class.eq]p2, each comparison is individually contextually
8296 // converted to bool.
8297 Op = S.PerformContextuallyConvertToBool(Op.get());
8298 if (Op.isInvalid())
8299 return StmtError();
8300 return Op.get();
8301
8302 case DefaultedComparisonKind::ThreeWay: {
8303 // Per C++2a [class.spaceship]p3, form:
8304 // if (R cmp = static_cast<R>(op); cmp != 0)
8305 // return cmp;
8306 QualType R = FD->getReturnType();
8307 Op = buildStaticCastToR(Op.get());
8308 if (Op.isInvalid())
8309 return StmtError();
8310
8311 // R cmp = ...;
8312 IdentifierInfo *Name = &S.Context.Idents.get("cmp");
8313 VarDecl *VD =
8314 VarDecl::Create(S.Context, S.CurContext, Loc, Loc, Name, R,
8315 S.Context.getTrivialTypeSourceInfo(R, Loc), SC_None);
8316 S.AddInitializerToDecl(VD, Op.get(), /*DirectInit=*/false);
8317 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8318
8319 // cmp != 0
8320 ExprResult VDRef = getDecl(VD);
8321 if (VDRef.isInvalid())
8322 return StmtError();
8323 llvm::APInt ZeroVal(S.Context.getIntWidth(S.Context.IntTy), 0);
8324 Expr *Zero =
8325 IntegerLiteral::Create(S.Context, ZeroVal, S.Context.IntTy, Loc);
8326 ExprResult Comp;
8327 if (VDRef.get()->getType()->isOverloadableType())
8328 Comp = S.CreateOverloadedBinOp(Loc, BO_NE, Fns, VDRef.get(), Zero, true,
8329 true, FD);
8330 else
8331 Comp = S.CreateBuiltinBinOp(Loc, BO_NE, VDRef.get(), Zero);
8332 if (Comp.isInvalid())
8333 return StmtError();
8334 Sema::ConditionResult Cond = S.ActOnCondition(
8335 nullptr, Loc, Comp.get(), Sema::ConditionKind::Boolean);
8336 if (Cond.isInvalid())
8337 return StmtError();
8338
8339 // return cmp;
8340 VDRef = getDecl(VD);
8341 if (VDRef.isInvalid())
8342 return StmtError();
8343 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, VDRef.get());
8344 if (ReturnStmt.isInvalid())
8345 return StmtError();
8346
8347 // if (...)
8348 return S.ActOnIfStmt(Loc, /*IsConstexpr=*/false, Loc, InitStmt, Cond, Loc,
8349 ReturnStmt.get(),
8350 /*ElseLoc=*/SourceLocation(), /*Else=*/nullptr);
8351 }
8352
8353 case DefaultedComparisonKind::NotEqual:
8354 case DefaultedComparisonKind::Relational:
8355 // C++2a [class.compare.secondary]p2:
8356 // Otherwise, the operator function yields x @ y.
8357 return Op.get();
8358 }
8359 llvm_unreachable("")__builtin_unreachable();
8360 }
8361
8362 /// Build "static_cast<R>(E)".
8363 ExprResult buildStaticCastToR(Expr *E) {
8364 QualType R = FD->getReturnType();
8365 assert(!R->isUndeducedType() && "type should have been deduced already")(static_cast<void> (0));
8366
8367 // Don't bother forming a no-op cast in the common case.
8368 if (E->isPRValue() && S.Context.hasSameType(E->getType(), R))
8369 return E;
8370 return S.BuildCXXNamedCast(Loc, tok::kw_static_cast,
8371 S.Context.getTrivialTypeSourceInfo(R, Loc), E,
8372 SourceRange(Loc, Loc), SourceRange(Loc, Loc));
8373 }
8374};
8375}
8376
8377/// Perform the unqualified lookups that might be needed to form a defaulted
8378/// comparison function for the given operator.
8379static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8380 UnresolvedSetImpl &Operators,
8381 OverloadedOperatorKind Op) {
8382 auto Lookup = [&](OverloadedOperatorKind OO) {
8383 Self.LookupOverloadedOperatorName(OO, S, Operators);
8384 };
8385
8386 // Every defaulted operator looks up itself.
8387 Lookup(Op);
8388 // ... and the rewritten form of itself, if any.
8389 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Op))
8390 Lookup(ExtraOp);
8391
8392 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8393 // synthesize a three-way comparison from '<' and '=='. In a dependent
8394 // context, we also need to look up '==' in case we implicitly declare a
8395 // defaulted 'operator=='.
8396 if (Op == OO_Spaceship) {
8397 Lookup(OO_ExclaimEqual);
8398 Lookup(OO_Less);
8399 Lookup(OO_EqualEqual);
8400 }
8401}
8402
8403bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8404 DefaultedComparisonKind DCK) {
8405 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison")(static_cast<void> (0));
8406
8407 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(FD->getLexicalDeclContext());
8408 assert(RD && "defaulted comparison is not defaulted in a class")(static_cast<void> (0));
8409
8410 // Perform any unqualified lookups we're going to need to default this
8411 // function.
8412 if (S) {
8413 UnresolvedSet<32> Operators;
8414 lookupOperatorsForDefaultedComparison(*this, S, Operators,
8415 FD->getOverloadedOperator());
8416 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
8417 Context, Operators.pairs()));
8418 }
8419
8420 // C++2a [class.compare.default]p1:
8421 // A defaulted comparison operator function for some class C shall be a
8422 // non-template function declared in the member-specification of C that is
8423 // -- a non-static const member of C having one parameter of type
8424 // const C&, or
8425 // -- a friend of C having two parameters of type const C& or two
8426 // parameters of type C.
8427 QualType ExpectedParmType1 = Context.getRecordType(RD);
8428 QualType ExpectedParmType2 =
8429 Context.getLValueReferenceType(ExpectedParmType1.withConst());
8430 if (isa<CXXMethodDecl>(FD))
8431 ExpectedParmType1 = ExpectedParmType2;
8432 for (const ParmVarDecl *Param : FD->parameters()) {
8433 if (!Param->getType()->isDependentType() &&
8434 !Context.hasSameType(Param->getType(), ExpectedParmType1) &&
8435 !Context.hasSameType(Param->getType(), ExpectedParmType2)) {
8436 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8437 // corresponding defaulted 'operator<=>' already.
8438 if (!FD->isImplicit()) {
8439 Diag(FD->getLocation(), diag::err_defaulted_comparison_param)
8440 << (int)DCK << Param->getType() << ExpectedParmType1
8441 << !isa<CXXMethodDecl>(FD)
8442 << ExpectedParmType2 << Param->getSourceRange();
8443 }
8444 return true;
8445 }
8446 }
8447 if (FD->getNumParams() == 2 &&
8448 !Context.hasSameType(FD->getParamDecl(0)->getType(),
8449 FD->getParamDecl(1)->getType())) {
8450 if (!FD->isImplicit()) {
8451 Diag(FD->getLocation(), diag::err_defaulted_comparison_param_mismatch)
8452 << (int)DCK
8453 << FD->getParamDecl(0)->getType()
8454 << FD->getParamDecl(0)->getSourceRange()
8455 << FD->getParamDecl(1)->getType()
8456 << FD->getParamDecl(1)->getSourceRange();
8457 }
8458 return true;
8459 }
8460
8461 // ... non-static const member ...
8462 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
8463 assert(!MD->isStatic() && "comparison function cannot be a static member")(static_cast<void> (0));
8464 if (!MD->isConst()) {
8465 SourceLocation InsertLoc;
8466 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
8467 InsertLoc = getLocForEndOfToken(Loc.getRParenLoc());
8468 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
8469 // corresponding defaulted 'operator<=>' already.
8470 if (!MD->isImplicit()) {
8471 Diag(MD->getLocation(), diag::err_defaulted_comparison_non_const)
8472 << (int)DCK << FixItHint::CreateInsertion(InsertLoc, " const");
8473 }
8474
8475 // Add the 'const' to the type to recover.
8476 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
8477 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8478 EPI.TypeQuals.addConst();
8479 MD->setType(Context.getFunctionType(FPT->getReturnType(),
8480 FPT->getParamTypes(), EPI));
8481 }
8482 } else {
8483 // A non-member function declared in a class must be a friend.
8484 assert(FD->getFriendObjectKind() && "expected a friend declaration")(static_cast<void> (0));
8485 }
8486
8487 // C++2a [class.eq]p1, [class.rel]p1:
8488 // A [defaulted comparison other than <=>] shall have a declared return
8489 // type bool.
8490 if (DCK != DefaultedComparisonKind::ThreeWay &&
8491 !FD->getDeclaredReturnType()->isDependentType() &&
8492 !Context.hasSameType(FD->getDeclaredReturnType(), Context.BoolTy)) {
8493 Diag(FD->getLocation(), diag::err_defaulted_comparison_return_type_not_bool)
8494 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
8495 << FD->getReturnTypeSourceRange();
8496 return true;
8497 }
8498 // C++2a [class.spaceship]p2 [P2002R0]:
8499 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
8500 // R shall not contain a placeholder type.
8501 if (DCK == DefaultedComparisonKind::ThreeWay &&
8502 FD->getDeclaredReturnType()->getContainedDeducedType() &&
8503 !Context.hasSameType(FD->getDeclaredReturnType(),
8504 Context.getAutoDeductType())) {
8505 Diag(FD->getLocation(),
8506 diag::err_defaulted_comparison_deduced_return_type_not_auto)
8507 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
8508 << FD->getReturnTypeSourceRange();
8509 return true;
8510 }
8511
8512 // For a defaulted function in a dependent class, defer all remaining checks
8513 // until instantiation.
8514 if (RD->isDependentType())
8515 return false;
8516
8517 // Determine whether the function should be defined as deleted.
8518 DefaultedComparisonInfo Info =
8519 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
8520
8521 bool First = FD == FD->getCanonicalDecl();
8522
8523 // If we want to delete the function, then do so; there's nothing else to
8524 // check in that case.
8525 if (Info.Deleted) {
8526 if (!First) {
8527 // C++11 [dcl.fct.def.default]p4:
8528 // [For a] user-provided explicitly-defaulted function [...] if such a
8529 // function is implicitly defined as deleted, the program is ill-formed.
8530 //
8531 // This is really just a consequence of the general rule that you can
8532 // only delete a function on its first declaration.
8533 Diag(FD->getLocation(), diag::err_non_first_default_compare_deletes)
8534 << FD->isImplicit() << (int)DCK;
8535 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8536 DefaultedComparisonAnalyzer::ExplainDeleted)
8537 .visit();
8538 return true;
8539 }
8540
8541 SetDeclDeleted(FD, FD->getLocation());
8542 if (!inTemplateInstantiation() && !FD->isImplicit()) {
8543 Diag(FD->getLocation(), diag::warn_defaulted_comparison_deleted)
8544 << (int)DCK;
8545 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8546 DefaultedComparisonAnalyzer::ExplainDeleted)
8547 .visit();
8548 }
8549 return false;
8550 }
8551
8552 // C++2a [class.spaceship]p2:
8553 // The return type is deduced as the common comparison type of R0, R1, ...
8554 if (DCK == DefaultedComparisonKind::ThreeWay &&
8555 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
8556 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
8557 if (RetLoc.isInvalid())
8558 RetLoc = FD->getBeginLoc();
8559 // FIXME: Should we really care whether we have the complete type and the
8560 // 'enumerator' constants here? A forward declaration seems sufficient.
8561 QualType Cat = CheckComparisonCategoryType(
8562 Info.Category, RetLoc, ComparisonCategoryUsage::DefaultedOperator);
8563 if (Cat.isNull())
8564 return true;
8565 Context.adjustDeducedFunctionResultType(
8566 FD, SubstAutoType(FD->getDeclaredReturnType(), Cat));
8567 }
8568
8569 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8570 // An explicitly-defaulted function that is not defined as deleted may be
8571 // declared constexpr or consteval only if it is constexpr-compatible.
8572 // C++2a [class.compare.default]p3 [P2002R0]:
8573 // A defaulted comparison function is constexpr-compatible if it satisfies
8574 // the requirements for a constexpr function [...]
8575 // The only relevant requirements are that the parameter and return types are
8576 // literal types. The remaining conditions are checked by the analyzer.
8577 if (FD->isConstexpr()) {
8578 if (CheckConstexprReturnType(*this, FD, CheckConstexprKind::Diagnose) &&
8579 CheckConstexprParameterTypes(*this, FD, CheckConstexprKind::Diagnose) &&
8580 !Info.Constexpr) {
8581 Diag(FD->getBeginLoc(),
8582 diag::err_incorrect_defaulted_comparison_constexpr)
8583 << FD->isImplicit() << (int)DCK << FD->isConsteval();
8584 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
8585 DefaultedComparisonAnalyzer::ExplainConstexpr)
8586 .visit();
8587 }
8588 }
8589
8590 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
8591 // If a constexpr-compatible function is explicitly defaulted on its first
8592 // declaration, it is implicitly considered to be constexpr.
8593 // FIXME: Only applying this to the first declaration seems problematic, as
8594 // simple reorderings can affect the meaning of the program.
8595 if (First && !FD->isConstexpr() && Info.Constexpr)
8596 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
8597
8598 // C++2a [except.spec]p3:
8599 // If a declaration of a function does not have a noexcept-specifier
8600 // [and] is defaulted on its first declaration, [...] the exception
8601 // specification is as specified below
8602 if (FD->getExceptionSpecType() == EST_None) {
8603 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
8604 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8605 EPI.ExceptionSpec.Type = EST_Unevaluated;
8606 EPI.ExceptionSpec.SourceDecl = FD;
8607 FD->setType(Context.getFunctionType(FPT->getReturnType(),
8608 FPT->getParamTypes(), EPI));
8609 }
8610
8611 return false;
8612}
8613
8614void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
8615 FunctionDecl *Spaceship) {
8616 Sema::CodeSynthesisContext Ctx;
8617 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
8618 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
8619 Ctx.Entity = Spaceship;
8620 pushCodeSynthesisContext(Ctx);
8621
8622 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
8623 EqualEqual->setImplicit();
8624
8625 popCodeSynthesisContext();
8626}
8627
8628void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
8629 DefaultedComparisonKind DCK) {
8630 assert(FD->isDefaulted() && !FD->isDeleted() &&(static_cast<void> (0))
8631 !FD->doesThisDeclarationHaveABody())(static_cast<void> (0));
8632 if (FD->willHaveBody() || FD->isInvalidDecl())
8633 return;
8634
8635 SynthesizedFunctionScope Scope(*this, FD);
8636
8637 // Add a context note for diagnostics produced after this point.
8638 Scope.addContextNote(UseLoc);
8639
8640 {
8641 // Build and set up the function body.
8642 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8643 SourceLocation BodyLoc =
8644 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8645 StmtResult Body =
8646 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
8647 if (Body.isInvalid()) {
8648 FD->setInvalidDecl();
8649 return;
8650 }
8651 FD->setBody(Body.get());
8652 FD->markUsed(Context);
8653 }
8654
8655 // The exception specification is needed because we are defining the
8656 // function. Note that this will reuse the body we just built.
8657 ResolveExceptionSpec(UseLoc, FD->getType()->castAs<FunctionProtoType>());
8658
8659 if (ASTMutationListener *L = getASTMutationListener())
8660 L->CompletedImplicitDefinition(FD);
8661}
8662
8663static Sema::ImplicitExceptionSpecification
8664ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
8665 FunctionDecl *FD,
8666 Sema::DefaultedComparisonKind DCK) {
8667 ComputingExceptionSpec CES(S, FD, Loc);
8668 Sema::ImplicitExceptionSpecification ExceptSpec(S);
8669
8670 if (FD->isInvalidDecl())
8671 return ExceptSpec;
8672
8673 // The common case is that we just defined the comparison function. In that
8674 // case, just look at whether the body can throw.
8675 if (FD->hasBody()) {
8676 ExceptSpec.CalledStmt(FD->getBody());
8677 } else {
8678 // Otherwise, build a body so we can check it. This should ideally only
8679 // happen when we're not actually marking the function referenced. (This is
8680 // only really important for efficiency: we don't want to build and throw
8681 // away bodies for comparison functions more than we strictly need to.)
8682
8683 // Pretend to synthesize the function body in an unevaluated context.
8684 // Note that we can't actually just go ahead and define the function here:
8685 // we are not permitted to mark its callees as referenced.
8686 Sema::SynthesizedFunctionScope Scope(S, FD);
8687 EnterExpressionEvaluationContext Context(
8688 S, Sema::ExpressionEvaluationContext::Unevaluated);
8689
8690 CXXRecordDecl *RD = cast<CXXRecordDecl>(FD->getLexicalParent());
8691 SourceLocation BodyLoc =
8692 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
8693 StmtResult Body =
8694 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
8695 if (!Body.isInvalid())
8696 ExceptSpec.CalledStmt(Body.get());
8697
8698 // FIXME: Can we hold onto this body and just transform it to potentially
8699 // evaluated when we're asked to define the function rather than rebuilding
8700 // it? Either that, or we should only build the bits of the body that we
8701 // need (the expressions, not the statements).
8702 }
8703
8704 return ExceptSpec;
8705}
8706
8707void Sema::CheckDelayedMemberExceptionSpecs() {
8708 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
8709 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
8710
8711 std::swap(Overriding, DelayedOverridingExceptionSpecChecks);
8712 std::swap(Equivalent, DelayedEquivalentExceptionSpecChecks);
8713
8714 // Perform any deferred checking of exception specifications for virtual
8715 // destructors.
8716 for (auto &Check : Overriding)
8717 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
8718
8719 // Perform any deferred checking of exception specifications for befriended
8720 // special members.
8721 for (auto &Check : Equivalent)
8722 CheckEquivalentExceptionSpec(Check.second, Check.first);
8723}
8724
8725namespace {
8726/// CRTP base class for visiting operations performed by a special member
8727/// function (or inherited constructor).
8728template<typename Derived>
8729struct SpecialMemberVisitor {
8730 Sema &S;
8731 CXXMethodDecl *MD;
8732 Sema::CXXSpecialMember CSM;
8733 Sema::InheritedConstructorInfo *ICI;
8734
8735 // Properties of the special member, computed for convenience.
8736 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
8737
8738 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
8739 Sema::InheritedConstructorInfo *ICI)
8740 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
8741 switch (CSM) {
8742 case Sema::CXXDefaultConstructor:
8743 case Sema::CXXCopyConstructor:
8744 case Sema::CXXMoveConstructor:
8745 IsConstructor = true;
8746 break;
8747 case Sema::CXXCopyAssignment:
8748 case Sema::CXXMoveAssignment:
8749 IsAssignment = true;
8750 break;
8751 case Sema::CXXDestructor:
8752 break;
8753 case Sema::CXXInvalid:
8754 llvm_unreachable("invalid special member kind")__builtin_unreachable();
8755 }
8756
8757 if (MD->getNumParams()) {
8758 if (const ReferenceType *RT =
8759 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
8760 ConstArg = RT->getPointeeType().isConstQualified();
8761 }
8762 }
8763
8764 Derived &getDerived() { return static_cast<Derived&>(*this); }
8765
8766 /// Is this a "move" special member?
8767 bool isMove() const {
8768 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
8769 }
8770
8771 /// Look up the corresponding special member in the given class.
8772 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
8773 unsigned Quals, bool IsMutable) {
8774 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
8775 ConstArg && !IsMutable);
8776 }
8777
8778 /// Look up the constructor for the specified base class to see if it's
8779 /// overridden due to this being an inherited constructor.
8780 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
8781 if (!ICI)
8782 return {};
8783 assert(CSM == Sema::CXXDefaultConstructor)(static_cast<void> (0));
8784 auto *BaseCtor =
8785 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
8786 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
8787 return MD;
8788 return {};
8789 }
8790
8791 /// A base or member subobject.
8792 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
8793
8794 /// Get the location to use for a subobject in diagnostics.
8795 static SourceLocation getSubobjectLoc(Subobject Subobj) {
8796 // FIXME: For an indirect virtual base, the direct base leading to
8797 // the indirect virtual base would be a more useful choice.
8798 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
8799 return B->getBaseTypeLoc();
8800 else
8801 return Subobj.get<FieldDecl*>()->getLocation();
8802 }
8803
8804 enum BasesToVisit {
8805 /// Visit all non-virtual (direct) bases.
8806 VisitNonVirtualBases,
8807 /// Visit all direct bases, virtual or not.
8808 VisitDirectBases,
8809 /// Visit all non-virtual bases, and all virtual bases if the class
8810 /// is not abstract.
8811 VisitPotentiallyConstructedBases,
8812 /// Visit all direct or virtual bases.
8813 VisitAllBases
8814 };
8815
8816 // Visit the bases and members of the class.
8817 bool visit(BasesToVisit Bases) {
8818 CXXRecordDecl *RD = MD->getParent();
8819
8820 if (Bases == VisitPotentiallyConstructedBases)
8821 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
8822
8823 for (auto &B : RD->bases())
8824 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
8825 getDerived().visitBase(&B))
8826 return true;
8827
8828 if (Bases == VisitAllBases)
8829 for (auto &B : RD->vbases())
8830 if (getDerived().visitBase(&B))
8831 return true;
8832
8833 for (auto *F : RD->fields())
8834 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
8835 getDerived().visitField(F))
8836 return true;
8837
8838 return false;
8839 }
8840};
8841}
8842
8843namespace {
8844struct SpecialMemberDeletionInfo
8845 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
8846 bool Diagnose;
8847
8848 SourceLocation Loc;
8849
8850 bool AllFieldsAreConst;
8851
8852 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
8853 Sema::CXXSpecialMember CSM,
8854 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
8855 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
8856 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
8857
8858 bool inUnion() const { return MD->getParent()->isUnion(); }
8859
8860 Sema::CXXSpecialMember getEffectiveCSM() {
8861 return ICI ? Sema::CXXInvalid : CSM;
8862 }
8863
8864 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
8865
8866 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
8867 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
8868
8869 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
8870 bool shouldDeleteForField(FieldDecl *FD);
8871 bool shouldDeleteForAllConstMembers();
8872
8873 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
8874 unsigned Quals);
8875 bool shouldDeleteForSubobjectCall(Subobject Subobj,
8876 Sema::SpecialMemberOverloadResult SMOR,
8877 bool IsDtorCallInCtor);
8878
8879 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
8880};
8881}
8882
8883/// Is the given special member inaccessible when used on the given
8884/// sub-object.
8885bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
8886 CXXMethodDecl *target) {
8887 /// If we're operating on a base class, the object type is the
8888 /// type of this special member.
8889 QualType objectTy;
8890 AccessSpecifier access = target->getAccess();
8891 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
8892 objectTy = S.Context.getTypeDeclType(MD->getParent());
8893 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
8894
8895 // If we're operating on a field, the object type is the type of the field.
8896 } else {
8897 objectTy = S.Context.getTypeDeclType(target->getParent());
8898 }
8899
8900 return S.isMemberAccessibleForDeletion(
8901 target->getParent(), DeclAccessPair::make(target, access), objectTy);
8902}
8903
8904/// Check whether we should delete a special member due to the implicit
8905/// definition containing a call to a special member of a subobject.
8906bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
8907 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
8908 bool IsDtorCallInCtor) {
8909 CXXMethodDecl *Decl = SMOR.getMethod();
8910 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8911
8912 int DiagKind = -1;
8913
8914 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
8915 DiagKind = !Decl ? 0 : 1;
8916 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
8917 DiagKind = 2;
8918 else if (!isAccessible(Subobj, Decl))
8919 DiagKind = 3;
8920 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
8921 !Decl->isTrivial()) {
8922 // A member of a union must have a trivial corresponding special member.
8923 // As a weird special case, a destructor call from a union's constructor
8924 // must be accessible and non-deleted, but need not be trivial. Such a
8925 // destructor is never actually called, but is semantically checked as
8926 // if it were.
8927 DiagKind = 4;
8928 }
8929
8930 if (DiagKind == -1)
8931 return false;
8932
8933 if (Diagnose) {
8934 if (Field) {
8935 S.Diag(Field->getLocation(),
8936 diag::note_deleted_special_member_class_subobject)
8937 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
8938 << Field << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/false;
8939 } else {
8940 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
8941 S.Diag(Base->getBeginLoc(),
8942 diag::note_deleted_special_member_class_subobject)
8943 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
8944 << Base->getType() << DiagKind << IsDtorCallInCtor
8945 << /*IsObjCPtr*/false;
8946 }
8947
8948 if (DiagKind == 1)
8949 S.NoteDeletedFunction(Decl);
8950 // FIXME: Explain inaccessibility if DiagKind == 3.
8951 }
8952
8953 return true;
8954}
8955
8956/// Check whether we should delete a special member function due to having a
8957/// direct or virtual base class or non-static data member of class type M.
8958bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
8959 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
8960 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
8961 bool IsMutable = Field && Field->isMutable();
8962
8963 // C++11 [class.ctor]p5:
8964 // -- any direct or virtual base class, or non-static data member with no
8965 // brace-or-equal-initializer, has class type M (or array thereof) and
8966 // either M has no default constructor or overload resolution as applied
8967 // to M's default constructor results in an ambiguity or in a function
8968 // that is deleted or inaccessible
8969 // C++11 [class.copy]p11, C++11 [class.copy]p23:
8970 // -- a direct or virtual base class B that cannot be copied/moved because
8971 // overload resolution, as applied to B's corresponding special member,
8972 // results in an ambiguity or a function that is deleted or inaccessible
8973 // from the defaulted special member
8974 // C++11 [class.dtor]p5:
8975 // -- any direct or virtual base class [...] has a type with a destructor
8976 // that is deleted or inaccessible
8977 if (!(CSM == Sema::CXXDefaultConstructor &&
8978 Field && Field->hasInClassInitializer()) &&
8979 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
8980 false))
8981 return true;
8982
8983 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
8984 // -- any direct or virtual base class or non-static data member has a
8985 // type with a destructor that is deleted or inaccessible
8986 if (IsConstructor) {
8987 Sema::SpecialMemberOverloadResult SMOR =
8988 S.LookupSpecialMember(Class, Sema::CXXDestructor,
8989 false, false, false, false, false);
8990 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
8991 return true;
8992 }
8993
8994 return false;
8995}
8996
8997bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
8998 FieldDecl *FD, QualType FieldType) {
8999 // The defaulted special functions are defined as deleted if this is a variant
9000 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9001 // type under ARC.
9002 if (!FieldType.hasNonTrivialObjCLifetime())
9003 return false;
9004
9005 // Don't make the defaulted default constructor defined as deleted if the
9006 // member has an in-class initializer.
9007 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer())
9008 return false;
9009
9010 if (Diagnose) {
9011 auto *ParentClass = cast<CXXRecordDecl>(FD->getParent());
9012 S.Diag(FD->getLocation(),
9013 diag::note_deleted_special_member_class_subobject)
9014 << getEffectiveCSM() << ParentClass << /*IsField*/true
9015 << FD << 4 << /*IsDtorCallInCtor*/false << /*IsObjCPtr*/true;
9016 }
9017
9018 return true;
9019}
9020
9021/// Check whether we should delete a special member function due to the class
9022/// having a particular direct or virtual base class.
9023bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9024 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9025 // If program is correct, BaseClass cannot be null, but if it is, the error
9026 // must be reported elsewhere.
9027 if (!BaseClass)
9028 return false;
9029 // If we have an inheriting constructor, check whether we're calling an
9030 // inherited constructor instead of a default constructor.
9031 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
9032 if (auto *BaseCtor = SMOR.getMethod()) {
9033 // Note that we do not check access along this path; other than that,
9034 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9035 // FIXME: Check that the base has a usable destructor! Sink this into
9036 // shouldDeleteForClassSubobject.
9037 if (BaseCtor->isDeleted() && Diagnose) {
9038 S.Diag(Base->getBeginLoc(),
9039 diag::note_deleted_special_member_class_subobject)
9040 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9041 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9042 << /*IsObjCPtr*/false;
9043 S.NoteDeletedFunction(BaseCtor);
9044 }
9045 return BaseCtor->isDeleted();
9046 }
9047 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
9048}
9049
9050/// Check whether we should delete a special member function due to the class
9051/// having a particular non-static data member.
9052bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9053 QualType FieldType = S.Context.getBaseElementType(FD->getType());
9054 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9055
9056 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9057 return true;
9058
9059 if (CSM == Sema::CXXDefaultConstructor) {
9060 // For a default constructor, all references must be initialized in-class
9061 // and, if a union, it must have a non-const member.
9062 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9063 if (Diagnose)
9064 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9065 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9066 return true;
9067 }
9068 // C++11 [class.ctor]p5: any non-variant non-static data member of
9069 // const-qualified type (or array thereof) with no
9070 // brace-or-equal-initializer does not have a user-provided default
9071 // constructor.
9072 if (!inUnion() && FieldType.isConstQualified() &&
9073 !FD->hasInClassInitializer() &&
9074 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
9075 if (Diagnose)
9076 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
9077 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9078 return true;
9079 }
9080
9081 if (inUnion() && !FieldType.isConstQualified())
9082 AllFieldsAreConst = false;
9083 } else if (CSM == Sema::CXXCopyConstructor) {
9084 // For a copy constructor, data members must not be of rvalue reference
9085 // type.
9086 if (FieldType->isRValueReferenceType()) {
9087 if (Diagnose)
9088 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
9089 << MD->getParent() << FD << FieldType;
9090 return true;
9091 }
9092 } else if (IsAssignment) {
9093 // For an assignment operator, data members must not be of reference type.
9094 if (FieldType->isReferenceType()) {
9095 if (Diagnose)
9096 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9097 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9098 return true;
9099 }
9100 if (!FieldRecord && FieldType.isConstQualified()) {
9101 // C++11 [class.copy]p23:
9102 // -- a non-static data member of const non-class type (or array thereof)
9103 if (Diagnose)
9104 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
9105 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9106 return true;
9107 }
9108 }
9109
9110 if (FieldRecord) {
9111 // Some additional restrictions exist on the variant members.
9112 if (!inUnion() && FieldRecord->isUnion() &&
9113 FieldRecord->isAnonymousStructOrUnion()) {
9114 bool AllVariantFieldsAreConst = true;
9115
9116 // FIXME: Handle anonymous unions declared within anonymous unions.
9117 for (auto *UI : FieldRecord->fields()) {
9118 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
9119
9120 if (shouldDeleteForVariantObjCPtrMember(&*UI, UnionFieldType))
9121 return true;
9122
9123 if (!UnionFieldType.isConstQualified())
9124 AllVariantFieldsAreConst = false;
9125
9126 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9127 if (UnionFieldRecord &&
9128 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
9129 UnionFieldType.getCVRQualifiers()))
9130 return true;
9131 }
9132
9133 // At least one member in each anonymous union must be non-const
9134 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
9135 !FieldRecord->field_empty()) {
9136 if (Diagnose)
9137 S.Diag(FieldRecord->getLocation(),
9138 diag::note_deleted_default_ctor_all_const)
9139 << !!ICI << MD->getParent() << /*anonymous union*/1;
9140 return true;
9141 }
9142
9143 // Don't check the implicit member of the anonymous union type.
9144 // This is technically non-conformant, but sanity demands it.
9145 return false;
9146 }
9147
9148 if (shouldDeleteForClassSubobject(FieldRecord, FD,
9149 FieldType.getCVRQualifiers()))
9150 return true;
9151 }
9152
9153 return false;
9154}
9155
9156/// C++11 [class.ctor] p5:
9157/// A defaulted default constructor for a class X is defined as deleted if
9158/// X is a union and all of its variant members are of const-qualified type.
9159bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9160 // This is a silly definition, because it gives an empty union a deleted
9161 // default constructor. Don't do that.
9162 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
9163 bool AnyFields = false;
9164 for (auto *F : MD->getParent()->fields())
9165 if ((AnyFields = !F->isUnnamedBitfield()))
9166 break;
9167 if (!AnyFields)
9168 return false;
9169 if (Diagnose)
9170 S.Diag(MD->getParent()->getLocation(),
9171 diag::note_deleted_default_ctor_all_const)
9172 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9173 return true;
9174 }
9175 return false;
9176}
9177
9178/// Determine whether a defaulted special member function should be defined as
9179/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9180/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9181bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
9182 InheritedConstructorInfo *ICI,
9183 bool Diagnose) {
9184 if (MD->isInvalidDecl())
9185 return false;
9186 CXXRecordDecl *RD = MD->getParent();
9187 assert(!RD->isDependentType() && "do deletion after instantiation")(static_cast<void> (0));
9188 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
9189 return false;
9190
9191 // C++11 [expr.lambda.prim]p19:
9192 // The closure type associated with a lambda-expression has a
9193 // deleted (8.4.3) default constructor and a deleted copy
9194 // assignment operator.
9195 // C++2a adds back these operators if the lambda has no lambda-capture.
9196 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9197 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
9198 if (Diagnose)
9199 Diag(RD->getLocation(), diag::note_lambda_decl);
9200 return true;
9201 }
9202
9203 // For an anonymous struct or union, the copy and assignment special members
9204 // will never be used, so skip the check. For an anonymous union declared at
9205 // namespace scope, the constructor and destructor are used.
9206 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
9207 RD->isAnonymousStructOrUnion())
9208 return false;
9209
9210 // C++11 [class.copy]p7, p18:
9211 // If the class definition declares a move constructor or move assignment
9212 // operator, an implicitly declared copy constructor or copy assignment
9213 // operator is defined as deleted.
9214 if (MD->isImplicit() &&
9215 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
9216 CXXMethodDecl *UserDeclaredMove = nullptr;
9217
9218 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9219 // deletion of the corresponding copy operation, not both copy operations.
9220 // MSVC 2015 has adopted the standards conforming behavior.
9221 bool DeletesOnlyMatchingCopy =
9222 getLangOpts().MSVCCompat &&
9223 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
9224
9225 if (RD->hasUserDeclaredMoveConstructor() &&
9226 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
9227 if (!Diagnose) return true;
9228
9229 // Find any user-declared move constructor.
9230 for (auto *I : RD->ctors()) {
9231 if (I->isMoveConstructor()) {
9232 UserDeclaredMove = I;
9233 break;
9234 }
9235 }
9236 assert(UserDeclaredMove)(static_cast<void> (0));
9237 } else if (RD->hasUserDeclaredMoveAssignment() &&
9238 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
9239 if (!Diagnose) return true;
9240
9241 // Find any user-declared move assignment operator.
9242 for (auto *I : RD->methods()) {
9243 if (I->isMoveAssignmentOperator()) {
9244 UserDeclaredMove = I;
9245 break;
9246 }
9247 }
9248 assert(UserDeclaredMove)(static_cast<void> (0));
9249 }
9250
9251 if (UserDeclaredMove) {
9252 Diag(UserDeclaredMove->getLocation(),
9253 diag::note_deleted_copy_user_declared_move)
9254 << (CSM == CXXCopyAssignment) << RD
9255 << UserDeclaredMove->isMoveAssignmentOperator();
9256 return true;
9257 }
9258 }
9259
9260 // Do access control from the special member function
9261 ContextRAII MethodContext(*this, MD);
9262
9263 // C++11 [class.dtor]p5:
9264 // -- for a virtual destructor, lookup of the non-array deallocation function
9265 // results in an ambiguity or in a function that is deleted or inaccessible
9266 if (CSM == CXXDestructor && MD->isVirtual()) {
9267 FunctionDecl *OperatorDelete = nullptr;
9268 DeclarationName Name =
9269 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
9270 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
9271 OperatorDelete, /*Diagnose*/false)) {
9272 if (Diagnose)
9273 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
9274 return true;
9275 }
9276 }
9277
9278 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
9279
9280 // Per DR1611, do not consider virtual bases of constructors of abstract
9281 // classes, since we are not going to construct them.
9282 // Per DR1658, do not consider virtual bases of destructors of abstract
9283 // classes either.
9284 // Per DR2180, for assignment operators we only assign (and thus only
9285 // consider) direct bases.
9286 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
9287 : SMI.VisitPotentiallyConstructedBases))
9288 return true;
9289
9290 if (SMI.shouldDeleteForAllConstMembers())
9291 return true;
9292
9293 if (getLangOpts().CUDA) {
9294 // We should delete the special member in CUDA mode if target inference
9295 // failed.
9296 // For inherited constructors (non-null ICI), CSM may be passed so that MD
9297 // is treated as certain special member, which may not reflect what special
9298 // member MD really is. However inferCUDATargetForImplicitSpecialMember
9299 // expects CSM to match MD, therefore recalculate CSM.
9300 assert(ICI || CSM == getSpecialMember(MD))(static_cast<void> (0));
9301 auto RealCSM = CSM;
9302 if (ICI)
9303 RealCSM = getSpecialMember(MD);
9304
9305 return inferCUDATargetForImplicitSpecialMember(RD, RealCSM, MD,
9306 SMI.ConstArg, Diagnose);
9307 }
9308
9309 return false;
9310}
9311
9312void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
9313 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
9314 assert(DFK && "not a defaultable function")(static_cast<void> (0));
9315 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted")(static_cast<void> (0));
9316
9317 if (DFK.isSpecialMember()) {
9318 ShouldDeleteSpecialMember(cast<CXXMethodDecl>(FD), DFK.asSpecialMember(),
9319 nullptr, /*Diagnose=*/true);
9320 } else {
9321 DefaultedComparisonAnalyzer(
9322 *this, cast<CXXRecordDecl>(FD->getLexicalDeclContext()), FD,
9323 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
9324 .visit();
9325 }
9326}
9327
9328/// Perform lookup for a special member of the specified kind, and determine
9329/// whether it is trivial. If the triviality can be determined without the
9330/// lookup, skip it. This is intended for use when determining whether a
9331/// special member of a containing object is trivial, and thus does not ever
9332/// perform overload resolution for default constructors.
9333///
9334/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
9335/// member that was most likely to be intended to be trivial, if any.
9336///
9337/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
9338/// determine whether the special member is trivial.
9339static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
9340 Sema::CXXSpecialMember CSM, unsigned Quals,
9341 bool ConstRHS,
9342 Sema::TrivialABIHandling TAH,
9343 CXXMethodDecl **Selected) {
9344 if (Selected)
9345 *Selected = nullptr;
9346
9347 switch (CSM) {
9348 case Sema::CXXInvalid:
9349 llvm_unreachable("not a special member")__builtin_unreachable();
9350
9351 case Sema::CXXDefaultConstructor:
9352 // C++11 [class.ctor]p5:
9353 // A default constructor is trivial if:
9354 // - all the [direct subobjects] have trivial default constructors
9355 //
9356 // Note, no overload resolution is performed in this case.
9357 if (RD->hasTrivialDefaultConstructor())
9358 return true;
9359
9360 if (Selected) {
9361 // If there's a default constructor which could have been trivial, dig it
9362 // out. Otherwise, if there's any user-provided default constructor, point
9363 // to that as an example of why there's not a trivial one.
9364 CXXConstructorDecl *DefCtor = nullptr;
9365 if (RD->needsImplicitDefaultConstructor())
9366 S.DeclareImplicitDefaultConstructor(RD);
9367 for (auto *CI : RD->ctors()) {
9368 if (!CI->isDefaultConstructor())
9369 continue;
9370 DefCtor = CI;
9371 if (!DefCtor->isUserProvided())
9372 break;
9373 }
9374
9375 *Selected = DefCtor;
9376 }
9377
9378 return false;
9379
9380 case Sema::CXXDestructor:
9381 // C++11 [class.dtor]p5:
9382 // A destructor is trivial if:
9383 // - all the direct [subobjects] have trivial destructors
9384 if (RD->hasTrivialDestructor() ||
9385 (TAH == Sema::TAH_ConsiderTrivialABI &&
9386 RD->hasTrivialDestructorForCall()))
9387 return true;
9388
9389 if (Selected) {
9390 if (RD->needsImplicitDestructor())
9391 S.DeclareImplicitDestructor(RD);
9392 *Selected = RD->getDestructor();
9393 }
9394
9395 return false;
9396
9397 case Sema::CXXCopyConstructor:
9398 // C++11 [class.copy]p12:
9399 // A copy constructor is trivial if:
9400 // - the constructor selected to copy each direct [subobject] is trivial
9401 if (RD->hasTrivialCopyConstructor() ||
9402 (TAH == Sema::TAH_ConsiderTrivialABI &&
9403 RD->hasTrivialCopyConstructorForCall())) {
9404 if (Quals == Qualifiers::Const)
9405 // We must either select the trivial copy constructor or reach an
9406 // ambiguity; no need to actually perform overload resolution.
9407 return true;
9408 } else if (!Selected) {
9409 return false;
9410 }
9411 // In C++98, we are not supposed to perform overload resolution here, but we
9412 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
9413 // cases like B as having a non-trivial copy constructor:
9414 // struct A { template<typename T> A(T&); };
9415 // struct B { mutable A a; };
9416 goto NeedOverloadResolution;
9417
9418 case Sema::CXXCopyAssignment:
9419 // C++11 [class.copy]p25:
9420 // A copy assignment operator is trivial if:
9421 // - the assignment operator selected to copy each direct [subobject] is
9422 // trivial
9423 if (RD->hasTrivialCopyAssignment()) {
9424 if (Quals == Qualifiers::Const)
9425 return true;
9426 } else if (!Selected) {
9427 return false;
9428 }
9429 // In C++98, we are not supposed to perform overload resolution here, but we
9430 // treat that as a language defect.
9431 goto NeedOverloadResolution;
9432
9433 case Sema::CXXMoveConstructor:
9434 case Sema::CXXMoveAssignment:
9435 NeedOverloadResolution:
9436 Sema::SpecialMemberOverloadResult SMOR =
9437 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
9438
9439 // The standard doesn't describe how to behave if the lookup is ambiguous.
9440 // We treat it as not making the member non-trivial, just like the standard
9441 // mandates for the default constructor. This should rarely matter, because
9442 // the member will also be deleted.
9443 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9444 return true;
9445
9446 if (!SMOR.getMethod()) {
9447 assert(SMOR.getKind() ==(static_cast<void> (0))
9448 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)(static_cast<void> (0));
9449 return false;
9450 }
9451
9452 // We deliberately don't check if we found a deleted special member. We're
9453 // not supposed to!
9454 if (Selected)
9455 *Selected = SMOR.getMethod();
9456
9457 if (TAH == Sema::TAH_ConsiderTrivialABI &&
9458 (CSM == Sema::CXXCopyConstructor || CSM == Sema::CXXMoveConstructor))
9459 return SMOR.getMethod()->isTrivialForCall();
9460 return SMOR.getMethod()->isTrivial();
9461 }
9462
9463 llvm_unreachable("unknown special method kind")__builtin_unreachable();
9464}
9465
9466static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
9467 for (auto *CI : RD->ctors())
9468 if (!CI->isImplicit())
9469 return CI;
9470
9471 // Look for constructor templates.
9472 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
9473 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
9474 if (CXXConstructorDecl *CD =
9475 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
9476 return CD;
9477 }
9478
9479 return nullptr;
9480}
9481
9482/// The kind of subobject we are checking for triviality. The values of this
9483/// enumeration are used in diagnostics.
9484enum TrivialSubobjectKind {
9485 /// The subobject is a base class.
9486 TSK_BaseClass,
9487 /// The subobject is a non-static data member.
9488 TSK_Field,
9489 /// The object is actually the complete object.
9490 TSK_CompleteObject
9491};
9492
9493/// Check whether the special member selected for a given type would be trivial.
9494static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
9495 QualType SubType, bool ConstRHS,
9496 Sema::CXXSpecialMember CSM,
9497 TrivialSubobjectKind Kind,
9498 Sema::TrivialABIHandling TAH, bool Diagnose) {
9499 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
9500 if (!SubRD)
9501 return true;
9502
9503 CXXMethodDecl *Selected;
9504 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
9505 ConstRHS, TAH, Diagnose ? &Selected : nullptr))
9506 return true;
9507
9508 if (Diagnose) {
9509 if (ConstRHS)
9510 SubType.addConst();
9511
9512 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
9513 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
9514 << Kind << SubType.getUnqualifiedType();
9515 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
9516 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
9517 } else if (!Selected)
9518 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
9519 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
9520 else if (Selected->isUserProvided()) {
9521 if (Kind == TSK_CompleteObject)
9522 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
9523 << Kind << SubType.getUnqualifiedType() << CSM;
9524 else {
9525 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
9526 << Kind << SubType.getUnqualifiedType() << CSM;
9527 S.Diag(Selected->getLocation(), diag::note_declared_at);
9528 }
9529 } else {
9530 if (Kind != TSK_CompleteObject)
9531 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
9532 << Kind << SubType.getUnqualifiedType() << CSM;
9533
9534 // Explain why the defaulted or deleted special member isn't trivial.
9535 S.SpecialMemberIsTrivial(Selected, CSM, Sema::TAH_IgnoreTrivialABI,
9536 Diagnose);
9537 }
9538 }
9539
9540 return false;
9541}
9542
9543/// Check whether the members of a class type allow a special member to be
9544/// trivial.
9545static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
9546 Sema::CXXSpecialMember CSM,
9547 bool ConstArg,
9548 Sema::TrivialABIHandling TAH,
9549 bool Diagnose) {
9550 for (const auto *FI : RD->fields()) {
9551 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
9552 continue;
9553
9554 QualType FieldType = S.Context.getBaseElementType(FI->getType());
9555
9556 // Pretend anonymous struct or union members are members of this class.
9557 if (FI->isAnonymousStructOrUnion()) {
9558 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
9559 CSM, ConstArg, TAH, Diagnose))
9560 return false;
9561 continue;
9562 }
9563
9564 // C++11 [class.ctor]p5:
9565 // A default constructor is trivial if [...]
9566 // -- no non-static data member of its class has a
9567 // brace-or-equal-initializer
9568 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
9569 if (Diagnose)
9570 S.Diag(FI->getLocation(), diag::note_nontrivial_default_member_init)
9571 << FI;
9572 return false;
9573 }
9574
9575 // Objective C ARC 4.3.5:
9576 // [...] nontrivally ownership-qualified types are [...] not trivially
9577 // default constructible, copy constructible, move constructible, copy
9578 // assignable, move assignable, or destructible [...]
9579 if (FieldType.hasNonTrivialObjCLifetime()) {
9580 if (Diagnose)
9581 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
9582 << RD << FieldType.getObjCLifetime();
9583 return false;
9584 }
9585
9586 bool ConstRHS = ConstArg && !FI->isMutable();
9587 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
9588 CSM, TSK_Field, TAH, Diagnose))
9589 return false;
9590 }
9591
9592 return true;
9593}
9594
9595/// Diagnose why the specified class does not have a trivial special member of
9596/// the given kind.
9597void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
9598 QualType Ty = Context.getRecordType(RD);
9599
9600 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
9601 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
9602 TSK_CompleteObject, TAH_IgnoreTrivialABI,
9603 /*Diagnose*/true);
9604}
9605
9606/// Determine whether a defaulted or deleted special member function is trivial,
9607/// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
9608/// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
9609bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
9610 TrivialABIHandling TAH, bool Diagnose) {
9611 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough")(static_cast<void> (0));
9612
9613 CXXRecordDecl *RD = MD->getParent();
9614
9615 bool ConstArg = false;
9616
9617 // C++11 [class.copy]p12, p25: [DR1593]
9618 // A [special member] is trivial if [...] its parameter-type-list is
9619 // equivalent to the parameter-type-list of an implicit declaration [...]
9620 switch (CSM) {
9621 case CXXDefaultConstructor:
9622 case CXXDestructor:
9623 // Trivial default constructors and destructors cannot have parameters.
9624 break;
9625
9626 case CXXCopyConstructor:
9627 case CXXCopyAssignment: {
9628 // Trivial copy operations always have const, non-volatile parameter types.
9629 ConstArg = true;
9630 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9631 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
9632 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
9633 if (Diagnose)
9634 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9635 << Param0->getSourceRange() << Param0->getType()
9636 << Context.getLValueReferenceType(
9637 Context.getRecordType(RD).withConst());
9638 return false;
9639 }
9640 break;
9641 }
9642
9643 case CXXMoveConstructor:
9644 case CXXMoveAssignment: {
9645 // Trivial move operations always have non-cv-qualified parameters.
9646 const ParmVarDecl *Param0 = MD->getParamDecl(0);
9647 const RValueReferenceType *RT =
9648 Param0->getType()->getAs<RValueReferenceType>();
9649 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
9650 if (Diagnose)
9651 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
9652 << Param0->getSourceRange() << Param0->getType()
9653 << Context.getRValueReferenceType(Context.getRecordType(RD));
9654 return false;
9655 }
9656 break;
9657 }
9658
9659 case CXXInvalid:
9660 llvm_unreachable("not a special member")__builtin_unreachable();
9661 }
9662
9663 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
9664 if (Diagnose)
9665 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
9666 diag::note_nontrivial_default_arg)
9667 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
9668 return false;
9669 }
9670 if (MD->isVariadic()) {
9671 if (Diagnose)
9672 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
9673 return false;
9674 }
9675
9676 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9677 // A copy/move [constructor or assignment operator] is trivial if
9678 // -- the [member] selected to copy/move each direct base class subobject
9679 // is trivial
9680 //
9681 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9682 // A [default constructor or destructor] is trivial if
9683 // -- all the direct base classes have trivial [default constructors or
9684 // destructors]
9685 for (const auto &BI : RD->bases())
9686 if (!checkTrivialSubobjectCall(*this, BI.getBeginLoc(), BI.getType(),
9687 ConstArg, CSM, TSK_BaseClass, TAH, Diagnose))
9688 return false;
9689
9690 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
9691 // A copy/move [constructor or assignment operator] for a class X is
9692 // trivial if
9693 // -- for each non-static data member of X that is of class type (or array
9694 // thereof), the constructor selected to copy/move that member is
9695 // trivial
9696 //
9697 // C++11 [class.copy]p12, C++11 [class.copy]p25:
9698 // A [default constructor or destructor] is trivial if
9699 // -- for all of the non-static data members of its class that are of class
9700 // type (or array thereof), each such class has a trivial [default
9701 // constructor or destructor]
9702 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, TAH, Diagnose))
9703 return false;
9704
9705 // C++11 [class.dtor]p5:
9706 // A destructor is trivial if [...]
9707 // -- the destructor is not virtual
9708 if (CSM == CXXDestructor && MD->isVirtual()) {
9709 if (Diagnose)
9710 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
9711 return false;
9712 }
9713
9714 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
9715 // A [special member] for class X is trivial if [...]
9716 // -- class X has no virtual functions and no virtual base classes
9717 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
9718 if (!Diagnose)
9719 return false;
9720
9721 if (RD->getNumVBases()) {
9722 // Check for virtual bases. We already know that the corresponding
9723 // member in all bases is trivial, so vbases must all be direct.
9724 CXXBaseSpecifier &BS = *RD->vbases_begin();
9725 assert(BS.isVirtual())(static_cast<void> (0));
9726 Diag(BS.getBeginLoc(), diag::note_nontrivial_has_virtual) << RD << 1;
9727 return false;
9728 }
9729
9730 // Must have a virtual method.
9731 for (const auto *MI : RD->methods()) {
9732 if (MI->isVirtual()) {
9733 SourceLocation MLoc = MI->getBeginLoc();
9734 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
9735 return false;
9736 }
9737 }
9738
9739 llvm_unreachable("dynamic class with no vbases and no virtual functions")__builtin_unreachable();
9740 }
9741
9742 // Looks like it's trivial!
9743 return true;
9744}
9745
9746namespace {
9747struct FindHiddenVirtualMethod {
9748 Sema *S;
9749 CXXMethodDecl *Method;
9750 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
9751 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9752
9753private:
9754 /// Check whether any most overridden method from MD in Methods
9755 static bool CheckMostOverridenMethods(
9756 const CXXMethodDecl *MD,
9757 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
9758 if (MD->size_overridden_methods() == 0)
9759 return Methods.count(MD->getCanonicalDecl());
9760 for (const CXXMethodDecl *O : MD->overridden_methods())
9761 if (CheckMostOverridenMethods(O, Methods))
9762 return true;
9763 return false;
9764 }
9765
9766public:
9767 /// Member lookup function that determines whether a given C++
9768 /// method overloads virtual methods in a base class without overriding any,
9769 /// to be used with CXXRecordDecl::lookupInBases().
9770 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
9771 RecordDecl *BaseRecord =
9772 Specifier->getType()->castAs<RecordType>()->getDecl();
9773
9774 DeclarationName Name = Method->getDeclName();
9775 assert(Name.getNameKind() == DeclarationName::Identifier)(static_cast<void> (0));
9776
9777 bool foundSameNameMethod = false;
9778 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
9779 for (Path.Decls = BaseRecord->lookup(Name).begin();
9780 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
9781 NamedDecl *D = *Path.Decls;
9782 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
9783 MD = MD->getCanonicalDecl();
9784 foundSameNameMethod = true;
9785 // Interested only in hidden virtual methods.
9786 if (!MD->isVirtual())
9787 continue;
9788 // If the method we are checking overrides a method from its base
9789 // don't warn about the other overloaded methods. Clang deviates from
9790 // GCC by only diagnosing overloads of inherited virtual functions that
9791 // do not override any other virtual functions in the base. GCC's
9792 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
9793 // function from a base class. These cases may be better served by a
9794 // warning (not specific to virtual functions) on call sites when the
9795 // call would select a different function from the base class, were it
9796 // visible.
9797 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
9798 if (!S->IsOverload(Method, MD, false))
9799 return true;
9800 // Collect the overload only if its hidden.
9801 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
9802 overloadedMethods.push_back(MD);
9803 }
9804 }
9805
9806 if (foundSameNameMethod)
9807 OverloadedMethods.append(overloadedMethods.begin(),
9808 overloadedMethods.end());
9809 return foundSameNameMethod;
9810 }
9811};
9812} // end anonymous namespace
9813
9814/// Add the most overriden methods from MD to Methods
9815static void AddMostOverridenMethods(const CXXMethodDecl *MD,
9816 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
9817 if (MD->size_overridden_methods() == 0)
9818 Methods.insert(MD->getCanonicalDecl());
9819 else
9820 for (const CXXMethodDecl *O : MD->overridden_methods())
9821 AddMostOverridenMethods(O, Methods);
9822}
9823
9824/// Check if a method overloads virtual methods in a base class without
9825/// overriding any.
9826void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
9827 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9828 if (!MD->getDeclName().isIdentifier())
9829 return;
9830
9831 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
9832 /*bool RecordPaths=*/false,
9833 /*bool DetectVirtual=*/false);
9834 FindHiddenVirtualMethod FHVM;
9835 FHVM.Method = MD;
9836 FHVM.S = this;
9837
9838 // Keep the base methods that were overridden or introduced in the subclass
9839 // by 'using' in a set. A base method not in this set is hidden.
9840 CXXRecordDecl *DC = MD->getParent();
9841 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
9842 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
9843 NamedDecl *ND = *I;
9844 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
9845 ND = shad->getTargetDecl();
9846 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
9847 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
9848 }
9849
9850 if (DC->lookupInBases(FHVM, Paths))
9851 OverloadedMethods = FHVM.OverloadedMethods;
9852}
9853
9854void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
9855 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
9856 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
9857 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
9858 PartialDiagnostic PD = PDiag(
9859 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
9860 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
9861 Diag(overloadedMD->getLocation(), PD);
9862 }
9863}
9864
9865/// Diagnose methods which overload virtual methods in a base class
9866/// without overriding any.
9867void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
9868 if (MD->isInvalidDecl())
9869 return;
9870
9871 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
9872 return;
9873
9874 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
9875 FindHiddenVirtualMethods(MD, OverloadedMethods);
9876 if (!OverloadedMethods.empty()) {
9877 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
9878 << MD << (OverloadedMethods.size() > 1);
9879
9880 NoteHiddenVirtualMethods(MD, OverloadedMethods);
9881 }
9882}
9883
9884void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
9885 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
9886 // No diagnostics if this is a template instantiation.
9887 if (!isTemplateInstantiation(RD.getTemplateSpecializationKind())) {
9888 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9889 diag::ext_cannot_use_trivial_abi) << &RD;
9890 Diag(RD.getAttr<TrivialABIAttr>()->getLocation(),
9891 diag::note_cannot_use_trivial_abi_reason) << &RD << N;
9892 }
9893 RD.dropAttr<TrivialABIAttr>();
9894 };
9895
9896 // Ill-formed if the copy and move constructors are deleted.
9897 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
9898 // If the type is dependent, then assume it might have
9899 // implicit copy or move ctor because we won't know yet at this point.
9900 if (RD.isDependentType())
9901 return true;
9902 if (RD.needsImplicitCopyConstructor() &&
9903 !RD.defaultedCopyConstructorIsDeleted())
9904 return true;
9905 if (RD.needsImplicitMoveConstructor() &&
9906 !RD.defaultedMoveConstructorIsDeleted())
9907 return true;
9908 for (const CXXConstructorDecl *CD : RD.ctors())
9909 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
9910 return true;
9911 return false;
9912 };
9913
9914 if (!HasNonDeletedCopyOrMoveConstructor()) {
9915 PrintDiagAndRemoveAttr(0);
9916 return;
9917 }
9918
9919 // Ill-formed if the struct has virtual functions.
9920 if (RD.isPolymorphic()) {
9921 PrintDiagAndRemoveAttr(1);
9922 return;
9923 }
9924
9925 for (const auto &B : RD.bases()) {
9926 // Ill-formed if the base class is non-trivial for the purpose of calls or a
9927 // virtual base.
9928 if (!B.getType()->isDependentType() &&
9929 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
9930 PrintDiagAndRemoveAttr(2);
9931 return;
9932 }
9933
9934 if (B.isVirtual()) {
9935 PrintDiagAndRemoveAttr(3);
9936 return;
9937 }
9938 }
9939
9940 for (const auto *FD : RD.fields()) {
9941 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
9942 // non-trivial for the purpose of calls.
9943 QualType FT = FD->getType();
9944 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
9945 PrintDiagAndRemoveAttr(4);
9946 return;
9947 }
9948
9949 if (const auto *RT = FT->getBaseElementTypeUnsafe()->getAs<RecordType>())
9950 if (!RT->isDependentType() &&
9951 !cast<CXXRecordDecl>(RT->getDecl())->canPassInRegisters()) {
9952 PrintDiagAndRemoveAttr(5);
9953 return;
9954 }
9955 }
9956}
9957
9958void Sema::ActOnFinishCXXMemberSpecification(
9959 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
9960 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
9961 if (!TagDecl)
9962 return;
9963
9964 AdjustDeclIfTemplate(TagDecl);
9965
9966 for (const ParsedAttr &AL : AttrList) {
9967 if (AL.getKind() != ParsedAttr::AT_Visibility)
9968 continue;
9969 AL.setInvalid();
9970 Diag(AL.getLoc(), diag::warn_attribute_after_definition_ignored) << AL;
9971 }
9972
9973 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
9974 // strict aliasing violation!
9975 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
9976 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
9977
9978 CheckCompletedCXXClass(S, cast<CXXRecordDecl>(TagDecl));
9979}
9980
9981/// Find the equality comparison functions that should be implicitly declared
9982/// in a given class definition, per C++2a [class.compare.default]p3.
9983static void findImplicitlyDeclaredEqualityComparisons(
9984 ASTContext &Ctx, CXXRecordDecl *RD,
9985 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
9986 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(OO_EqualEqual);
9987 if (!RD->lookup(EqEq).empty())
9988 // Member operator== explicitly declared: no implicit operator==s.
9989 return;
9990
9991 // Traverse friends looking for an '==' or a '<=>'.
9992 for (FriendDecl *Friend : RD->friends()) {
9993 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Friend->getFriendDecl());
9994 if (!FD) continue;
9995
9996 if (FD->getOverloadedOperator() == OO_EqualEqual) {
9997 // Friend operator== explicitly declared: no implicit operator==s.
9998 Spaceships.clear();
9999 return;
10000 }
10001
10002 if (FD->getOverloadedOperator() == OO_Spaceship &&
10003 FD->isExplicitlyDefaulted())
10004 Spaceships.push_back(FD);
10005 }
10006
10007 // Look for members named 'operator<=>'.
10008 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(OO_Spaceship);
10009 for (NamedDecl *ND : RD->lookup(Cmp)) {
10010 // Note that we could find a non-function here (either a function template
10011 // or a using-declaration). Neither case results in an implicit
10012 // 'operator=='.
10013 if (auto *FD = dyn_cast<FunctionDecl>(ND))
10014 if (FD->isExplicitlyDefaulted())
10015 Spaceships.push_back(FD);
10016 }
10017}
10018
10019/// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
10020/// special functions, such as the default constructor, copy
10021/// constructor, or destructor, to the given C++ class (C++
10022/// [special]p1). This routine can only be executed just before the
10023/// definition of the class is complete.
10024void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10025 // Don't add implicit special members to templated classes.
10026 // FIXME: This means unqualified lookups for 'operator=' within a class
10027 // template don't work properly.
10028 if (!ClassDecl->isDependentType()) {
10029 if (ClassDecl->needsImplicitDefaultConstructor()) {
10030 ++getASTContext().NumImplicitDefaultConstructors;
10031
10032 if (ClassDecl->hasInheritedConstructor())
10033 DeclareImplicitDefaultConstructor(ClassDecl);
10034 }
10035
10036 if (ClassDecl->needsImplicitCopyConstructor()) {
10037 ++getASTContext().NumImplicitCopyConstructors;
10038
10039 // If the properties or semantics of the copy constructor couldn't be
10040 // determined while the class was being declared, force a declaration
10041 // of it now.
10042 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10043 ClassDecl->hasInheritedConstructor())
10044 DeclareImplicitCopyConstructor(ClassDecl);
10045 // For the MS ABI we need to know whether the copy ctor is deleted. A
10046 // prerequisite for deleting the implicit copy ctor is that the class has
10047 // a move ctor or move assignment that is either user-declared or whose
10048 // semantics are inherited from a subobject. FIXME: We should provide a
10049 // more direct way for CodeGen to ask whether the constructor was deleted.
10050 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10051 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10052 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10053 ClassDecl->hasUserDeclaredMoveAssignment() ||
10054 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10055 DeclareImplicitCopyConstructor(ClassDecl);
10056 }
10057
10058 if (getLangOpts().CPlusPlus11 &&
10059 ClassDecl->needsImplicitMoveConstructor()) {
10060 ++getASTContext().NumImplicitMoveConstructors;
10061
10062 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10063 ClassDecl->hasInheritedConstructor())
10064 DeclareImplicitMoveConstructor(ClassDecl);
10065 }
10066
10067 if (ClassDecl->needsImplicitCopyAssignment()) {
10068 ++getASTContext().NumImplicitCopyAssignmentOperators;
10069
10070 // If we have a dynamic class, then the copy assignment operator may be
10071 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10072 // it shows up in the right place in the vtable and that we diagnose
10073 // problems with the implicit exception specification.
10074 if (ClassDecl->isDynamicClass() ||
10075 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10076 ClassDecl->hasInheritedAssignment())
10077 DeclareImplicitCopyAssignment(ClassDecl);
10078 }
10079
10080 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10081 ++getASTContext().NumImplicitMoveAssignmentOperators;
10082
10083 // Likewise for the move assignment operator.
10084 if (ClassDecl->isDynamicClass() ||
10085 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10086 ClassDecl->hasInheritedAssignment())
10087 DeclareImplicitMoveAssignment(ClassDecl);
10088 }
10089
10090 if (ClassDecl->needsImplicitDestructor()) {
10091 ++getASTContext().NumImplicitDestructors;
10092
10093 // If we have a dynamic class, then the destructor may be virtual, so we
10094 // have to declare the destructor immediately. This ensures that, e.g., it
10095 // shows up in the right place in the vtable and that we diagnose problems
10096 // with the implicit exception specification.
10097 if (ClassDecl->isDynamicClass() ||
10098 ClassDecl->needsOverloadResolutionForDestructor())
10099 DeclareImplicitDestructor(ClassDecl);
10100 }
10101 }
10102
10103 // C++2a [class.compare.default]p3:
10104 // If the member-specification does not explicitly declare any member or
10105 // friend named operator==, an == operator function is declared implicitly
10106 // for each defaulted three-way comparison operator function defined in
10107 // the member-specification
10108 // FIXME: Consider doing this lazily.
10109 // We do this during the initial parse for a class template, not during
10110 // instantiation, so that we can handle unqualified lookups for 'operator=='
10111 // when parsing the template.
10112 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10113 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10114 findImplicitlyDeclaredEqualityComparisons(Context, ClassDecl,
10115 DefaultedSpaceships);
10116 for (auto *FD : DefaultedSpaceships)
10117 DeclareImplicitEqualityComparison(ClassDecl, FD);
10118 }
10119}
10120
10121unsigned
10122Sema::ActOnReenterTemplateScope(Decl *D,
10123 llvm::function_ref<Scope *()> EnterScope) {
10124 if (!D)
10125 return 0;
10126 AdjustDeclIfTemplate(D);
10127
10128 // In order to get name lookup right, reenter template scopes in order from
10129 // outermost to innermost.
10130 SmallVector<TemplateParameterList *, 4> ParameterLists;
10131 DeclContext *LookupDC = dyn_cast<DeclContext>(D);
10132
10133 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
10134 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10135 ParameterLists.push_back(DD->getTemplateParameterList(i));
10136
10137 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
10138 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10139 ParameterLists.push_back(FTD->getTemplateParameters());
10140 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
10141 LookupDC = VD->getDeclContext();
10142
10143 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10144 ParameterLists.push_back(VTD->getTemplateParameters());
10145 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(D))
10146 ParameterLists.push_back(PSD->getTemplateParameters());
10147 }
10148 } else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
10149 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10150 ParameterLists.push_back(TD->getTemplateParameterList(i));
10151
10152 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
10153 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10154 ParameterLists.push_back(CTD->getTemplateParameters());
10155 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
10156 ParameterLists.push_back(PSD->getTemplateParameters());
10157 }
10158 }
10159 // FIXME: Alias declarations and concepts.
10160
10161 unsigned Count = 0;
10162 Scope *InnermostTemplateScope = nullptr;
10163 for (TemplateParameterList *Params : ParameterLists) {
10164 // Ignore explicit specializations; they don't contribute to the template
10165 // depth.
10166 if (Params->size() == 0)
10167 continue;
10168
10169 InnermostTemplateScope = EnterScope();
10170 for (NamedDecl *Param : *Params) {
10171 if (Param->getDeclName()) {
10172 InnermostTemplateScope->AddDecl(Param);
10173 IdResolver.AddDecl(Param);
10174 }
10175 }
10176 ++Count;
10177 }
10178
10179 // Associate the new template scopes with the corresponding entities.
10180 if (InnermostTemplateScope) {
10181 assert(LookupDC && "no enclosing DeclContext for template lookup")(static_cast<void> (0));
10182 EnterTemplatedContext(InnermostTemplateScope, LookupDC);
10183 }
10184
10185 return Count;
10186}
10187
10188void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10189 if (!RecordD) return;
10190 AdjustDeclIfTemplate(RecordD);
10191 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
10192 PushDeclContext(S, Record);
10193}
10194
10195void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
10196 if (!RecordD) return;
10197 PopDeclContext();
10198}
10199
10200/// This is used to implement the constant expression evaluation part of the
10201/// attribute enable_if extension. There is nothing in standard C++ which would
10202/// require reentering parameters.
10203void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
10204 if (!Param)
10205 return;
10206
10207 S->AddDecl(Param);
10208 if (Param->getDeclName())
10209 IdResolver.AddDecl(Param);
10210}
10211
10212/// ActOnStartDelayedCXXMethodDeclaration - We have completed
10213/// parsing a top-level (non-nested) C++ class, and we are now
10214/// parsing those parts of the given Method declaration that could
10215/// not be parsed earlier (C++ [class.mem]p2), such as default
10216/// arguments. This action should enter the scope of the given
10217/// Method declaration as if we had just parsed the qualified method
10218/// name. However, it should not bring the parameters into scope;
10219/// that will be performed by ActOnDelayedCXXMethodParameter.
10220void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10221}
10222
10223/// ActOnDelayedCXXMethodParameter - We've already started a delayed
10224/// C++ method declaration. We're (re-)introducing the given
10225/// function parameter into scope for use in parsing later parts of
10226/// the method declaration. For example, we could see an
10227/// ActOnParamDefaultArgument event for this parameter.
10228void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
10229 if (!ParamD)
10230 return;
10231
10232 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
10233
10234 S->AddDecl(Param);
10235 if (Param->getDeclName())
10236 IdResolver.AddDecl(Param);
10237}
10238
10239/// ActOnFinishDelayedCXXMethodDeclaration - We have finished
10240/// processing the delayed method declaration for Method. The method
10241/// declaration is now considered finished. There may be a separate
10242/// ActOnStartOfFunctionDef action later (not necessarily
10243/// immediately!) for this method, if it was also defined inside the
10244/// class body.
10245void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
10246 if (!MethodD)
10247 return;
10248
10249 AdjustDeclIfTemplate(MethodD);
10250
10251 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
10252
10253 // Now that we have our default arguments, check the constructor
10254 // again. It could produce additional diagnostics or affect whether
10255 // the class has implicitly-declared destructors, among other
10256 // things.
10257 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
10258 CheckConstructor(Constructor);
10259
10260 // Check the default arguments, which we may have added.
10261 if (!Method->isInvalidDecl())
10262 CheckCXXDefaultArguments(Method);
10263}
10264
10265// Emit the given diagnostic for each non-address-space qualifier.
10266// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
10267static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
10268 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10269 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
10270 bool DiagOccured = false;
10271 FTI.MethodQualifiers->forEachQualifier(
10272 [DiagID, &S, &DiagOccured](DeclSpec::TQ, StringRef QualName,
10273 SourceLocation SL) {
10274 // This diagnostic should be emitted on any qualifier except an addr
10275 // space qualifier. However, forEachQualifier currently doesn't visit
10276 // addr space qualifiers, so there's no way to write this condition
10277 // right now; we just diagnose on everything.
10278 S.Diag(SL, DiagID) << QualName << SourceRange(SL);
10279 DiagOccured = true;
10280 });
10281 if (DiagOccured)
10282 D.setInvalidType();
10283 }
10284}
10285
10286/// CheckConstructorDeclarator - Called by ActOnDeclarator to check
10287/// the well-formedness of the constructor declarator @p D with type @p
10288/// R. If there are any errors in the declarator, this routine will
10289/// emit diagnostics and set the invalid bit to true. In any case, the type
10290/// will be updated to reflect a well-formed type for the constructor and
10291/// returned.
10292QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
10293 StorageClass &SC) {
10294 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
10295
10296 // C++ [class.ctor]p3:
10297 // A constructor shall not be virtual (10.3) or static (9.4). A
10298 // constructor can be invoked for a const, volatile or const
10299 // volatile object. A constructor shall not be declared const,
10300 // volatile, or const volatile (9.3.2).
10301 if (isVirtual) {
10302 if (!D.isInvalidType())
10303 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10304 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
10305 << SourceRange(D.getIdentifierLoc());
10306 D.setInvalidType();
10307 }
10308 if (SC == SC_Static) {
10309 if (!D.isInvalidType())
10310 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
10311 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10312 << SourceRange(D.getIdentifierLoc());
10313 D.setInvalidType();
10314 SC = SC_None;
10315 }
10316
10317 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10318 diagnoseIgnoredQualifiers(
10319 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
10320 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
10321 D.getDeclSpec().getRestrictSpecLoc(),
10322 D.getDeclSpec().getAtomicSpecLoc());
10323 D.setInvalidType();
10324 }
10325
10326 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_constructor);
10327
10328 // C++0x [class.ctor]p4:
10329 // A constructor shall not be declared with a ref-qualifier.
10330 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10331 if (FTI.hasRefQualifier()) {
10332 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
10333 << FTI.RefQualifierIsLValueRef
10334 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10335 D.setInvalidType();
10336 }
10337
10338 // Rebuild the function type "R" without any type qualifiers (in
10339 // case any of the errors above fired) and with "void" as the
10340 // return type, since constructors don't have return types.
10341 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10342 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
10343 return R;
10344
10345 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10346 EPI.TypeQuals = Qualifiers();
10347 EPI.RefQualifier = RQ_None;
10348
10349 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
10350}
10351
10352/// CheckConstructor - Checks a fully-formed constructor for
10353/// well-formedness, issuing any diagnostics required. Returns true if
10354/// the constructor declarator is invalid.
10355void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
10356 CXXRecordDecl *ClassDecl
10357 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
10358 if (!ClassDecl)
10359 return Constructor->setInvalidDecl();
10360
10361 // C++ [class.copy]p3:
10362 // A declaration of a constructor for a class X is ill-formed if
10363 // its first parameter is of type (optionally cv-qualified) X and
10364 // either there are no other parameters or else all other
10365 // parameters have default arguments.
10366 if (!Constructor->isInvalidDecl() &&
10367 Constructor->hasOneParamOrDefaultArgs() &&
10368 Constructor->getTemplateSpecializationKind() !=
10369 TSK_ImplicitInstantiation) {
10370 QualType ParamType = Constructor->getParamDecl(0)->getType();
10371 QualType ClassTy = Context.getTagDeclType(ClassDecl);
10372 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
10373 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
10374 const char *ConstRef
10375 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
10376 : " const &";
10377 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
10378 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
10379
10380 // FIXME: Rather that making the constructor invalid, we should endeavor
10381 // to fix the type.
10382 Constructor->setInvalidDecl();
10383 }
10384 }
10385}
10386
10387/// CheckDestructor - Checks a fully-formed destructor definition for
10388/// well-formedness, issuing any diagnostics required. Returns true
10389/// on error.
10390bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
10391 CXXRecordDecl *RD = Destructor->getParent();
10392
10393 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
10394 SourceLocation Loc;
10395
10396 if (!Destructor->isImplicit())
10397 Loc = Destructor->getLocation();
10398 else
10399 Loc = RD->getLocation();
10400
10401 // If we have a virtual destructor, look up the deallocation function
10402 if (FunctionDecl *OperatorDelete =
10403 FindDeallocationFunctionForDestructor(Loc, RD)) {
10404 Expr *ThisArg = nullptr;
10405
10406 // If the notional 'delete this' expression requires a non-trivial
10407 // conversion from 'this' to the type of a destroying operator delete's
10408 // first parameter, perform that conversion now.
10409 if (OperatorDelete->isDestroyingOperatorDelete()) {
10410 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
10411 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
10412 // C++ [class.dtor]p13:
10413 // ... as if for the expression 'delete this' appearing in a
10414 // non-virtual destructor of the destructor's class.
10415 ContextRAII SwitchContext(*this, Destructor);
10416 ExprResult This =
10417 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
10418 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?")(static_cast<void> (0));
10419 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
10420 if (This.isInvalid()) {
10421 // FIXME: Register this as a context note so that it comes out
10422 // in the right order.
10423 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
10424 return true;
10425 }
10426 ThisArg = This.get();
10427 }
10428 }
10429
10430 DiagnoseUseOfDecl(OperatorDelete, Loc);
10431 MarkFunctionReferenced(Loc, OperatorDelete);
10432 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
10433 }
10434 }
10435
10436 return false;
10437}
10438
10439/// CheckDestructorDeclarator - Called by ActOnDeclarator to check
10440/// the well-formednes of the destructor declarator @p D with type @p
10441/// R. If there are any errors in the declarator, this routine will
10442/// emit diagnostics and set the declarator to invalid. Even if this happens,
10443/// will be updated to reflect a well-formed type for the destructor and
10444/// returned.
10445QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
10446 StorageClass& SC) {
10447 // C++ [class.dtor]p1:
10448 // [...] A typedef-name that names a class is a class-name
10449 // (7.1.3); however, a typedef-name that names a class shall not
10450 // be used as the identifier in the declarator for a destructor
10451 // declaration.
10452 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
10453 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
10454 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10455 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
10456 else if (const TemplateSpecializationType *TST =
10457 DeclaratorType->getAs<TemplateSpecializationType>())
10458 if (TST->isTypeAlias())
10459 Diag(D.getIdentifierLoc(), diag::ext_destructor_typedef_name)
10460 << DeclaratorType << 1;
10461
10462 // C++ [class.dtor]p2:
10463 // A destructor is used to destroy objects of its class type. A
10464 // destructor takes no parameters, and no return type can be
10465 // specified for it (not even void). The address of a destructor
10466 // shall not be taken. A destructor shall not be static. A
10467 // destructor can be invoked for a const, volatile or const
10468 // volatile object. A destructor shall not be declared const,
10469 // volatile or const volatile (9.3.2).
10470 if (SC == SC_Static) {
10471 if (!D.isInvalidType())
10472 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
10473 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10474 << SourceRange(D.getIdentifierLoc())
10475 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
10476
10477 SC = SC_None;
10478 }
10479 if (!D.isInvalidType()) {
10480 // Destructors don't have return types, but the parser will
10481 // happily parse something like:
10482 //
10483 // class X {
10484 // float ~X();
10485 // };
10486 //
10487 // The return type will be eliminated later.
10488 if (D.getDeclSpec().hasTypeSpecifier())
10489 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
10490 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
10491 << SourceRange(D.getIdentifierLoc());
10492 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
10493 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
10494 SourceLocation(),
10495 D.getDeclSpec().getConstSpecLoc(),
10496 D.getDeclSpec().getVolatileSpecLoc(),
10497 D.getDeclSpec().getRestrictSpecLoc(),
10498 D.getDeclSpec().getAtomicSpecLoc());
10499 D.setInvalidType();
10500 }
10501 }
10502
10503 checkMethodTypeQualifiers(*this, D, diag::err_invalid_qualified_destructor);
10504
10505 // C++0x [class.dtor]p2:
10506 // A destructor shall not be declared with a ref-qualifier.
10507 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10508 if (FTI.hasRefQualifier()) {
10509 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
10510 << FTI.RefQualifierIsLValueRef
10511 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
10512 D.setInvalidType();
10513 }
10514
10515 // Make sure we don't have any parameters.
10516 if (FTIHasNonVoidParameters(FTI)) {
10517 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
10518
10519 // Delete the parameters.
10520 FTI.freeParams();
10521 D.setInvalidType();
10522 }
10523
10524 // Make sure the destructor isn't variadic.
10525 if (FTI.isVariadic) {
10526 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
10527 D.setInvalidType();
10528 }
10529
10530 // Rebuild the function type "R" without any type qualifiers or
10531 // parameters (in case any of the errors above fired) and with
10532 // "void" as the return type, since destructors don't have return
10533 // types.
10534 if (!D.isInvalidType())
10535 return R;
10536
10537 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
10538 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
10539 EPI.Variadic = false;
10540 EPI.TypeQuals = Qualifiers();
10541 EPI.RefQualifier = RQ_None;
10542 return Context.getFunctionType(Context.VoidTy, None, EPI);
10543}
10544
10545static void extendLeft(SourceRange &R, SourceRange Before) {
10546 if (Before.isInvalid())
10547 return;
10548 R.setBegin(Before.getBegin());
10549 if (R.getEnd().isInvalid())
10550 R.setEnd(Before.getEnd());
10551}
10552
10553static void extendRight(SourceRange &R, SourceRange After) {
10554 if (After.isInvalid())
10555 return;
10556 if (R.getBegin().isInvalid())
10557 R.setBegin(After.getBegin());
10558 R.setEnd(After.getEnd());
10559}
10560
10561/// CheckConversionDeclarator - Called by ActOnDeclarator to check the
10562/// well-formednes of the conversion function declarator @p D with
10563/// type @p R. If there are any errors in the declarator, this routine
10564/// will emit diagnostics and return true. Otherwise, it will return
10565/// false. Either way, the type @p R will be updated to reflect a
10566/// well-formed type for the conversion operator.
10567void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
10568 StorageClass& SC) {
10569 // C++ [class.conv.fct]p1:
10570 // Neither parameter types nor return type can be specified. The
10571 // type of a conversion function (8.3.5) is "function taking no
10572 // parameter returning conversion-type-id."
10573 if (SC == SC_Static) {
10574 if (!D.isInvalidType())
10575 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
10576 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
10577 << D.getName().getSourceRange();
10578 D.setInvalidType();
10579 SC = SC_None;
10580 }
10581
10582 TypeSourceInfo *ConvTSI = nullptr;
10583 QualType ConvType =
10584 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
10585
10586 const DeclSpec &DS = D.getDeclSpec();
10587 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
10588 // Conversion functions don't have return types, but the parser will
10589 // happily parse something like:
10590 //
10591 // class X {
10592 // float operator bool();
10593 // };
10594 //
10595 // The return type will be changed later anyway.
10596 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
10597 << SourceRange(DS.getTypeSpecTypeLoc())
10598 << SourceRange(D.getIdentifierLoc());
10599 D.setInvalidType();
10600 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
10601 // It's also plausible that the user writes type qualifiers in the wrong
10602 // place, such as:
10603 // struct S { const operator int(); };
10604 // FIXME: we could provide a fixit to move the qualifiers onto the
10605 // conversion type.
10606 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_complex_decl)
10607 << SourceRange(D.getIdentifierLoc()) << 0;
10608 D.setInvalidType();
10609 }
10610
10611 const auto *Proto = R->castAs<FunctionProtoType>();
10612
10613 // Make sure we don't have any parameters.
10614 if (Proto->getNumParams() > 0) {
10615 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
10616
10617 // Delete the parameters.
10618 D.getFunctionTypeInfo().freeParams();
10619 D.setInvalidType();
10620 } else if (Proto->isVariadic()) {
10621 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
10622 D.setInvalidType();
10623 }
10624
10625 // Diagnose "&operator bool()" and other such nonsense. This
10626 // is actually a gcc extension which we don't support.
10627 if (Proto->getReturnType() != ConvType) {
10628 bool NeedsTypedef = false;
10629 SourceRange Before, After;
10630
10631 // Walk the chunks and extract information on them for our diagnostic.
10632 bool PastFunctionChunk = false;
10633 for (auto &Chunk : D.type_objects()) {
10634 switch (Chunk.Kind) {
10635 case DeclaratorChunk::Function:
10636 if (!PastFunctionChunk) {
10637 if (Chunk.Fun.HasTrailingReturnType) {
10638 TypeSourceInfo *TRT = nullptr;
10639 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
10640 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
10641 }
10642 PastFunctionChunk = true;
10643 break;
10644 }
10645 LLVM_FALLTHROUGH[[gnu::fallthrough]];
10646 case DeclaratorChunk::Array:
10647 NeedsTypedef = true;
10648 extendRight(After, Chunk.getSourceRange());
10649 break;
10650
10651 case DeclaratorChunk::Pointer:
10652 case DeclaratorChunk::BlockPointer:
10653 case DeclaratorChunk::Reference:
10654 case DeclaratorChunk::MemberPointer:
10655 case DeclaratorChunk::Pipe:
10656 extendLeft(Before, Chunk.getSourceRange());
10657 break;
10658
10659 case DeclaratorChunk::Paren:
10660 extendLeft(Before, Chunk.Loc);
10661 extendRight(After, Chunk.EndLoc);
10662 break;
10663 }
10664 }
10665
10666 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
10667 After.isValid() ? After.getBegin() :
10668 D.getIdentifierLoc();
10669 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
10670 DB << Before << After;
10671
10672 if (!NeedsTypedef) {
10673 DB << /*don't need a typedef*/0;
10674
10675 // If we can provide a correct fix-it hint, do so.
10676 if (After.isInvalid() && ConvTSI) {
10677 SourceLocation InsertLoc =
10678 getLocForEndOfToken(ConvTSI->getTypeLoc().getEndLoc());
10679 DB << FixItHint::CreateInsertion(InsertLoc, " ")
10680 << FixItHint::CreateInsertionFromRange(
10681 InsertLoc, CharSourceRange::getTokenRange(Before))
10682 << FixItHint::CreateRemoval(Before);
10683 }
10684 } else if (!Proto->getReturnType()->isDependentType()) {
10685 DB << /*typedef*/1 << Proto->getReturnType();
10686 } else if (getLangOpts().CPlusPlus11) {
10687 DB << /*alias template*/2 << Proto->getReturnType();
10688 } else {
10689 DB << /*might not be fixable*/3;
10690 }
10691
10692 // Recover by incorporating the other type chunks into the result type.
10693 // Note, this does *not* change the name of the function. This is compatible
10694 // with the GCC extension:
10695 // struct S { &operator int(); } s;
10696 // int &r = s.operator int(); // ok in GCC
10697 // S::operator int&() {} // error in GCC, function name is 'operator int'.
10698 ConvType = Proto->getReturnType();
10699 }
10700
10701 // C++ [class.conv.fct]p4:
10702 // The conversion-type-id shall not represent a function type nor
10703 // an array type.
10704 if (ConvType->isArrayType()) {
10705 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
10706 ConvType = Context.getPointerType(ConvType);
10707 D.setInvalidType();
10708 } else if (ConvType->isFunctionType()) {
10709 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
10710 ConvType = Context.getPointerType(ConvType);
10711 D.setInvalidType();
10712 }
10713
10714 // Rebuild the function type "R" without any parameters (in case any
10715 // of the errors above fired) and with the conversion type as the
10716 // return type.
10717 if (D.isInvalidType())
10718 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
10719
10720 // C++0x explicit conversion operators.
10721 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
10722 Diag(DS.getExplicitSpecLoc(),
10723 getLangOpts().CPlusPlus11
10724 ? diag::warn_cxx98_compat_explicit_conversion_functions
10725 : diag::ext_explicit_conversion_functions)
10726 << SourceRange(DS.getExplicitSpecRange());
10727}
10728
10729/// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
10730/// the declaration of the given C++ conversion function. This routine
10731/// is responsible for recording the conversion function in the C++
10732/// class, if possible.
10733Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
10734 assert(Conversion && "Expected to receive a conversion function declaration")(static_cast<void> (0));
10735
10736 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
10737
10738 // Make sure we aren't redeclaring the conversion function.
10739 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
10740 // C++ [class.conv.fct]p1:
10741 // [...] A conversion function is never used to convert a
10742 // (possibly cv-qualified) object to the (possibly cv-qualified)
10743 // same object type (or a reference to it), to a (possibly
10744 // cv-qualified) base class of that type (or a reference to it),
10745 // or to (possibly cv-qualified) void.
10746 QualType ClassType
10747 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10748 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
10749 ConvType = ConvTypeRef->getPointeeType();
10750 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
10751 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
10752 /* Suppress diagnostics for instantiations. */;
10753 else if (Conversion->size_overridden_methods() != 0)
10754 /* Suppress diagnostics for overriding virtual function in a base class. */;
10755 else if (ConvType->isRecordType()) {
10756 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
10757 if (ConvType == ClassType)
10758 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
10759 << ClassType;
10760 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
10761 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
10762 << ClassType << ConvType;
10763 } else if (ConvType->isVoidType()) {
10764 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
10765 << ClassType << ConvType;
10766 }
10767
10768 if (FunctionTemplateDecl *ConversionTemplate
10769 = Conversion->getDescribedFunctionTemplate())
10770 return ConversionTemplate;
10771
10772 return Conversion;
10773}
10774
10775namespace {
10776/// Utility class to accumulate and print a diagnostic listing the invalid
10777/// specifier(s) on a declaration.
10778struct BadSpecifierDiagnoser {
10779 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
10780 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
10781 ~BadSpecifierDiagnoser() {
10782 Diagnostic << Specifiers;
10783 }
10784
10785 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
10786 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
10787 }
10788 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
10789 return check(SpecLoc,
10790 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
10791 }
10792 void check(SourceLocation SpecLoc, const char *Spec) {
10793 if (SpecLoc.isInvalid()) return;
10794 Diagnostic << SourceRange(SpecLoc, SpecLoc);
10795 if (!Specifiers.empty()) Specifiers += " ";
10796 Specifiers += Spec;
10797 }
10798
10799 Sema &S;
10800 Sema::SemaDiagnosticBuilder Diagnostic;
10801 std::string Specifiers;
10802};
10803}
10804
10805/// Check the validity of a declarator that we parsed for a deduction-guide.
10806/// These aren't actually declarators in the grammar, so we need to check that
10807/// the user didn't specify any pieces that are not part of the deduction-guide
10808/// grammar.
10809void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
10810 StorageClass &SC) {
10811 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
10812 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
10813 assert(GuidedTemplateDecl && "missing template decl for deduction guide")(static_cast<void> (0));
10814
10815 // C++ [temp.deduct.guide]p3:
10816 // A deduction-gide shall be declared in the same scope as the
10817 // corresponding class template.
10818 if (!CurContext->getRedeclContext()->Equals(
10819 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
10820 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
10821 << GuidedTemplateDecl;
10822 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
10823 }
10824
10825 auto &DS = D.getMutableDeclSpec();
10826 // We leave 'friend' and 'virtual' to be rejected in the normal way.
10827 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
10828 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
10829 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
10830 BadSpecifierDiagnoser Diagnoser(
10831 *this, D.getIdentifierLoc(),
10832 diag::err_deduction_guide_invalid_specifier);
10833
10834 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
10835 DS.ClearStorageClassSpecs();
10836 SC = SC_None;
10837
10838 // 'explicit' is permitted.
10839 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
10840 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
10841 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
10842 DS.ClearConstexprSpec();
10843
10844 Diagnoser.check(DS.getConstSpecLoc(), "const");
10845 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
10846 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
10847 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
10848 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
10849 DS.ClearTypeQualifiers();
10850
10851 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
10852 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
10853 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
10854 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
10855 DS.ClearTypeSpecType();
10856 }
10857
10858 if (D.isInvalidType())
10859 return;
10860
10861 // Check the declarator is simple enough.
10862 bool FoundFunction = false;
10863 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
10864 if (Chunk.Kind == DeclaratorChunk::Paren)
10865 continue;
10866 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
10867 Diag(D.getDeclSpec().getBeginLoc(),
10868 diag::err_deduction_guide_with_complex_decl)
10869 << D.getSourceRange();
10870 break;
10871 }
10872 if (!Chunk.Fun.hasTrailingReturnType()) {
10873 Diag(D.getName().getBeginLoc(),
10874 diag::err_deduction_guide_no_trailing_return_type);
10875 break;
10876 }
10877
10878 // Check that the return type is written as a specialization of
10879 // the template specified as the deduction-guide's name.
10880 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
10881 TypeSourceInfo *TSI = nullptr;
10882 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
10883 assert(TSI && "deduction guide has valid type but invalid return type?")(static_cast<void> (0));
10884 bool AcceptableReturnType = false;
10885 bool MightInstantiateToSpecialization = false;
10886 if (auto RetTST =
10887 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
10888 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
10889 bool TemplateMatches =
10890 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
10891 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
10892 AcceptableReturnType = true;
10893 else {
10894 // This could still instantiate to the right type, unless we know it
10895 // names the wrong class template.
10896 auto *TD = SpecifiedName.getAsTemplateDecl();
10897 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
10898 !TemplateMatches);
10899 }
10900 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
10901 MightInstantiateToSpecialization = true;
10902 }
10903
10904 if (!AcceptableReturnType) {
10905 Diag(TSI->getTypeLoc().getBeginLoc(),
10906 diag::err_deduction_guide_bad_trailing_return_type)
10907 << GuidedTemplate << TSI->getType()
10908 << MightInstantiateToSpecialization
10909 << TSI->getTypeLoc().getSourceRange();
10910 }
10911
10912 // Keep going to check that we don't have any inner declarator pieces (we
10913 // could still have a function returning a pointer to a function).
10914 FoundFunction = true;
10915 }
10916
10917 if (D.isFunctionDefinition())
10918 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
10919}
10920
10921//===----------------------------------------------------------------------===//
10922// Namespace Handling
10923//===----------------------------------------------------------------------===//
10924
10925/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
10926/// reopened.
10927static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
10928 SourceLocation Loc,
10929 IdentifierInfo *II, bool *IsInline,
10930 NamespaceDecl *PrevNS) {
10931 assert(*IsInline != PrevNS->isInline())(static_cast<void> (0));
10932
10933 if (PrevNS->isInline())
10934 // The user probably just forgot the 'inline', so suggest that it
10935 // be added back.
10936 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
10937 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
10938 else
10939 S.Diag(Loc, diag::err_inline_namespace_mismatch);
10940
10941 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
10942 *IsInline = PrevNS->isInline();
10943}
10944
10945/// ActOnStartNamespaceDef - This is called at the start of a namespace
10946/// definition.
10947Decl *Sema::ActOnStartNamespaceDef(
10948 Scope *NamespcScope, SourceLocation InlineLoc, SourceLocation NamespaceLoc,
10949 SourceLocation IdentLoc, IdentifierInfo *II, SourceLocation LBrace,
10950 const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UD) {
10951 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
10952 // For anonymous namespace, take the location of the left brace.
10953 SourceLocation Loc = II ? IdentLoc : LBrace;
10954 bool IsInline = InlineLoc.isValid();
10955 bool IsInvalid = false;
10956 bool IsStd = false;
10957 bool AddToKnown = false;
10958 Scope *DeclRegionScope = NamespcScope->getParent();
10959
10960 NamespaceDecl *PrevNS = nullptr;
10961 if (II) {
10962 // C++ [namespace.def]p2:
10963 // The identifier in an original-namespace-definition shall not
10964 // have been previously defined in the declarative region in
10965 // which the original-namespace-definition appears. The
10966 // identifier in an original-namespace-definition is the name of
10967 // the namespace. Subsequently in that declarative region, it is
10968 // treated as an original-namespace-name.
10969 //
10970 // Since namespace names are unique in their scope, and we don't
10971 // look through using directives, just look for any ordinary names
10972 // as if by qualified name lookup.
10973 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
10974 ForExternalRedeclaration);
10975 LookupQualifiedName(R, CurContext->getRedeclContext());
10976 NamedDecl *PrevDecl =
10977 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
10978 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
10979
10980 if (PrevNS) {
10981 // This is an extended namespace definition.
10982 if (IsInline != PrevNS->isInline())
10983 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
10984 &IsInline, PrevNS);
10985 } else if (PrevDecl) {
10986 // This is an invalid name redefinition.
10987 Diag(Loc, diag::err_redefinition_different_kind)
10988 << II;
10989 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10990 IsInvalid = true;
10991 // Continue on to push Namespc as current DeclContext and return it.
10992 } else if (II->isStr("std") &&
10993 CurContext->getRedeclContext()->isTranslationUnit()) {
10994 // This is the first "real" definition of the namespace "std", so update
10995 // our cache of the "std" namespace to point at this definition.
10996 PrevNS = getStdNamespace();
10997 IsStd = true;
10998 AddToKnown = !IsInline;
10999 } else {
11000 // We've seen this namespace for the first time.
11001 AddToKnown = !IsInline;
11002 }
11003 } else {
11004 // Anonymous namespaces.
11005
11006 // Determine whether the parent already has an anonymous namespace.
11007 DeclContext *Parent = CurContext->getRedeclContext();
11008 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11009 PrevNS = TU->getAnonymousNamespace();
11010 } else {
11011 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
11012 PrevNS = ND->getAnonymousNamespace();
11013 }
11014
11015 if (PrevNS && IsInline != PrevNS->isInline())
11016 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
11017 &IsInline, PrevNS);
11018 }
11019
11020 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
11021 StartLoc, Loc, II, PrevNS);
11022 if (IsInvalid)
11023 Namespc->setInvalidDecl();
11024
11025 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
11026 AddPragmaAttributes(DeclRegionScope, Namespc);
11027
11028 // FIXME: Should we be merging attributes?
11029 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
11030 PushNamespaceVisibilityAttr(Attr, Loc);
11031
11032 if (IsStd)
11033 StdNamespace = Namespc;
11034 if (AddToKnown)
11035 KnownNamespaces[Namespc] = false;
11036
11037 if (II) {
11038 PushOnScopeChains(Namespc, DeclRegionScope);
11039 } else {
11040 // Link the anonymous namespace into its parent.
11041 DeclContext *Parent = CurContext->getRedeclContext();
11042 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
11043 TU->setAnonymousNamespace(Namespc);
11044 } else {
11045 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
11046 }
11047
11048 CurContext->addDecl(Namespc);
11049
11050 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
11051 // behaves as if it were replaced by
11052 // namespace unique { /* empty body */ }
11053 // using namespace unique;
11054 // namespace unique { namespace-body }
11055 // where all occurrences of 'unique' in a translation unit are
11056 // replaced by the same identifier and this identifier differs
11057 // from all other identifiers in the entire program.
11058
11059 // We just create the namespace with an empty name and then add an
11060 // implicit using declaration, just like the standard suggests.
11061 //
11062 // CodeGen enforces the "universally unique" aspect by giving all
11063 // declarations semantically contained within an anonymous
11064 // namespace internal linkage.
11065
11066 if (!PrevNS) {
11067 UD = UsingDirectiveDecl::Create(Context, Parent,
11068 /* 'using' */ LBrace,
11069 /* 'namespace' */ SourceLocation(),
11070 /* qualifier */ NestedNameSpecifierLoc(),
11071 /* identifier */ SourceLocation(),
11072 Namespc,
11073 /* Ancestor */ Parent);
11074 UD->setImplicit();
11075 Parent->addDecl(UD);
11076 }
11077 }
11078
11079 ActOnDocumentableDecl(Namespc);
11080
11081 // Although we could have an invalid decl (i.e. the namespace name is a
11082 // redefinition), push it as current DeclContext and try to continue parsing.
11083 // FIXME: We should be able to push Namespc here, so that the each DeclContext
11084 // for the namespace has the declarations that showed up in that particular
11085 // namespace definition.
11086 PushDeclContext(NamespcScope, Namespc);
11087 return Namespc;
11088}
11089
11090/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
11091/// is a namespace alias, returns the namespace it points to.
11092static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
11093 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
11094 return AD->getNamespace();
11095 return dyn_cast_or_null<NamespaceDecl>(D);
11096}
11097
11098/// ActOnFinishNamespaceDef - This callback is called after a namespace is
11099/// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
11100void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
11101 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
11102 assert(Namespc && "Invalid parameter, expected NamespaceDecl")(static_cast<void> (0));
11103 Namespc->setRBraceLoc(RBrace);
11104 PopDeclContext();
11105 if (Namespc->hasAttr<VisibilityAttr>())
11106 PopPragmaVisibility(true, RBrace);
11107 // If this namespace contains an export-declaration, export it now.
11108 if (DeferredExportedNamespaces.erase(Namespc))
11109 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
11110}
11111
11112CXXRecordDecl *Sema::getStdBadAlloc() const {
11113 return cast_or_null<CXXRecordDecl>(
11114 StdBadAlloc.get(Context.getExternalSource()));
11115}
11116
11117EnumDecl *Sema::getStdAlignValT() const {
11118 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
11119}
11120
11121NamespaceDecl *Sema::getStdNamespace() const {
11122 return cast_or_null<NamespaceDecl>(
11123 StdNamespace.get(Context.getExternalSource()));
11124}
11125
11126NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
11127 if (!StdExperimentalNamespaceCache) {
11128 if (auto Std = getStdNamespace()) {
11129 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
11130 SourceLocation(), LookupNamespaceName);
11131 if (!LookupQualifiedName(Result, Std) ||
11132 !(StdExperimentalNamespaceCache =
11133 Result.getAsSingle<NamespaceDecl>()))
11134 Result.suppressDiagnostics();
11135 }
11136 }
11137 return StdExperimentalNamespaceCache;
11138}
11139
11140namespace {
11141
11142enum UnsupportedSTLSelect {
11143 USS_InvalidMember,
11144 USS_MissingMember,
11145 USS_NonTrivial,
11146 USS_Other
11147};
11148
11149struct InvalidSTLDiagnoser {
11150 Sema &S;
11151 SourceLocation Loc;
11152 QualType TyForDiags;
11153
11154 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
11155 const VarDecl *VD = nullptr) {
11156 {
11157 auto D = S.Diag(Loc, diag::err_std_compare_type_not_supported)
11158 << TyForDiags << ((int)Sel);
11159 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
11160 assert(!Name.empty())(static_cast<void> (0));
11161 D << Name;
11162 }
11163 }
11164 if (Sel == USS_InvalidMember) {
11165 S.Diag(VD->getLocation(), diag::note_var_declared_here)
11166 << VD << VD->getSourceRange();
11167 }
11168 return QualType();
11169 }
11170};
11171} // namespace
11172
11173QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
11174 SourceLocation Loc,
11175 ComparisonCategoryUsage Usage) {
11176 assert(getLangOpts().CPlusPlus &&(static_cast<void> (0))
11177 "Looking for comparison category type outside of C++.")(static_cast<void> (0));
11178
11179 // Use an elaborated type for diagnostics which has a name containing the
11180 // prepended 'std' namespace but not any inline namespace names.
11181 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
11182 auto *NNS =
11183 NestedNameSpecifier::Create(Context, nullptr, getStdNamespace());
11184 return Context.getElaboratedType(ETK_None, NNS, Info->getType());
11185 };
11186
11187 // Check if we've already successfully checked the comparison category type
11188 // before. If so, skip checking it again.
11189 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
11190 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
11191 // The only thing we need to check is that the type has a reachable
11192 // definition in the current context.
11193 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11194 return QualType();
11195
11196 return Info->getType();
11197 }
11198
11199 // If lookup failed
11200 if (!Info) {
11201 std::string NameForDiags = "std::";
11202 NameForDiags += ComparisonCategories::getCategoryString(Kind);
11203 Diag(Loc, diag::err_implied_comparison_category_type_not_found)
11204 << NameForDiags << (int)Usage;
11205 return QualType();
11206 }
11207
11208 assert(Info->Kind == Kind)(static_cast<void> (0));
11209 assert(Info->Record)(static_cast<void> (0));
11210
11211 // Update the Record decl in case we encountered a forward declaration on our
11212 // first pass. FIXME: This is a bit of a hack.
11213 if (Info->Record->hasDefinition())
11214 Info->Record = Info->Record->getDefinition();
11215
11216 if (RequireCompleteType(Loc, TyForDiags(Info), diag::err_incomplete_type))
11217 return QualType();
11218
11219 InvalidSTLDiagnoser UnsupportedSTLError{*this, Loc, TyForDiags(Info)};
11220
11221 if (!Info->Record->isTriviallyCopyable())
11222 return UnsupportedSTLError(USS_NonTrivial);
11223
11224 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
11225 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
11226 // Tolerate empty base classes.
11227 if (Base->isEmpty())
11228 continue;
11229 // Reject STL implementations which have at least one non-empty base.
11230 return UnsupportedSTLError();
11231 }
11232
11233 // Check that the STL has implemented the types using a single integer field.
11234 // This expectation allows better codegen for builtin operators. We require:
11235 // (1) The class has exactly one field.
11236 // (2) The field is an integral or enumeration type.
11237 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
11238 if (std::distance(FIt, FEnd) != 1 ||
11239 !FIt->getType()->isIntegralOrEnumerationType()) {
11240 return UnsupportedSTLError();
11241 }
11242
11243 // Build each of the require values and store them in Info.
11244 for (ComparisonCategoryResult CCR :
11245 ComparisonCategories::getPossibleResultsForType(Kind)) {
11246 StringRef MemName = ComparisonCategories::getResultString(CCR);
11247 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(CCR);
11248
11249 if (!ValInfo)
11250 return UnsupportedSTLError(USS_MissingMember, MemName);
11251
11252 VarDecl *VD = ValInfo->VD;
11253 assert(VD && "should not be null!")(static_cast<void> (0));
11254
11255 // Attempt to diagnose reasons why the STL definition of this type
11256 // might be foobar, including it failing to be a constant expression.
11257 // TODO Handle more ways the lookup or result can be invalid.
11258 if (!VD->isStaticDataMember() ||
11259 !VD->isUsableInConstantExpressions(Context))
11260 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
11261
11262 // Attempt to evaluate the var decl as a constant expression and extract
11263 // the value of its first field as a ICE. If this fails, the STL
11264 // implementation is not supported.
11265 if (!ValInfo->hasValidIntValue())
11266 return UnsupportedSTLError();
11267
11268 MarkVariableReferenced(Loc, VD);
11269 }
11270
11271 // We've successfully built the required types and expressions. Update
11272 // the cache and return the newly cached value.
11273 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
11274 return Info->getType();
11275}
11276
11277/// Retrieve the special "std" namespace, which may require us to
11278/// implicitly define the namespace.
11279NamespaceDecl *Sema::getOrCreateStdNamespace() {
11280 if (!StdNamespace) {
11281 // The "std" namespace has not yet been defined, so build one implicitly.
11282 StdNamespace = NamespaceDecl::Create(Context,
11283 Context.getTranslationUnitDecl(),
11284 /*Inline=*/false,
11285 SourceLocation(), SourceLocation(),
11286 &PP.getIdentifierTable().get("std"),
11287 /*PrevDecl=*/nullptr);
11288 getStdNamespace()->setImplicit(true);
11289 }
11290
11291 return getStdNamespace();
11292}
11293
11294bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
11295 assert(getLangOpts().CPlusPlus &&(static_cast<void> (0))
11296 "Looking for std::initializer_list outside of C++.")(static_cast<void> (0));
11297
11298 // We're looking for implicit instantiations of
11299 // template <typename E> class std::initializer_list.
11300
11301 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
11302 return false;
11303
11304 ClassTemplateDecl *Template = nullptr;
11305 const TemplateArgument *Arguments = nullptr;
11306
11307 if (const RecordType *RT = Ty->getAs<RecordType>()) {
11308
11309 ClassTemplateSpecializationDecl *Specialization =
11310 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
11311 if (!Specialization)
11312 return false;
11313
11314 Template = Specialization->getSpecializedTemplate();
11315 Arguments = Specialization->getTemplateArgs().data();
11316 } else if (const TemplateSpecializationType *TST =
11317 Ty->getAs<TemplateSpecializationType>()) {
11318 Template = dyn_cast_or_null<ClassTemplateDecl>(
11319 TST->getTemplateName().getAsTemplateDecl());
11320 Arguments = TST->getArgs();
11321 }
11322 if (!Template)
11323 return false;
11324
11325 if (!StdInitializerList) {
11326 // Haven't recognized std::initializer_list yet, maybe this is it.
11327 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
11328 if (TemplateClass->getIdentifier() !=
11329 &PP.getIdentifierTable().get("initializer_list") ||
11330 !getStdNamespace()->InEnclosingNamespaceSetOf(
11331 TemplateClass->getDeclContext()))
11332 return false;
11333 // This is a template called std::initializer_list, but is it the right
11334 // template?
11335 TemplateParameterList *Params = Template->getTemplateParameters();
11336 if (Params->getMinRequiredArguments() != 1)
11337 return false;
11338 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
11339 return false;
11340
11341 // It's the right template.
11342 StdInitializerList = Template;
11343 }
11344
11345 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
11346 return false;
11347
11348 // This is an instance of std::initializer_list. Find the argument type.
11349 if (Element)
11350 *Element = Arguments[0].getAsType();
11351 return true;
11352}
11353
11354static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
11355 NamespaceDecl *Std = S.getStdNamespace();
11356 if (!Std) {
11357 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11358 return nullptr;
11359 }
11360
11361 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
11362 Loc, Sema::LookupOrdinaryName);
11363 if (!S.LookupQualifiedName(Result, Std)) {
11364 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
11365 return nullptr;
11366 }
11367 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
11368 if (!Template) {
11369 Result.suppressDiagnostics();
11370 // We found something weird. Complain about the first thing we found.
11371 NamedDecl *Found = *Result.begin();
11372 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
11373 return nullptr;
11374 }
11375
11376 // We found some template called std::initializer_list. Now verify that it's
11377 // correct.
11378 TemplateParameterList *Params = Template->getTemplateParameters();
11379 if (Params->getMinRequiredArguments() != 1 ||
11380 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
11381 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
11382 return nullptr;
11383 }
11384
11385 return Template;
11386}
11387
11388QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
11389 if (!StdInitializerList) {
11390 StdInitializerList = LookupStdInitializerList(*this, Loc);
11391 if (!StdInitializerList)
11392 return QualType();
11393 }
11394
11395 TemplateArgumentListInfo Args(Loc, Loc);
11396 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
11397 Context.getTrivialTypeSourceInfo(Element,
11398 Loc)));
11399 return Context.getCanonicalType(
11400 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
11401}
11402
11403bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
11404 // C++ [dcl.init.list]p2:
11405 // A constructor is an initializer-list constructor if its first parameter
11406 // is of type std::initializer_list<E> or reference to possibly cv-qualified
11407 // std::initializer_list<E> for some type E, and either there are no other
11408 // parameters or else all other parameters have default arguments.
11409 if (!Ctor->hasOneParamOrDefaultArgs())
11410 return false;
11411
11412 QualType ArgType = Ctor->getParamDecl(0)->getType();
11413 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
11414 ArgType = RT->getPointeeType().getUnqualifiedType();
11415
11416 return isStdInitializerList(ArgType, nullptr);
11417}
11418
11419/// Determine whether a using statement is in a context where it will be
11420/// apply in all contexts.
11421static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
11422 switch (CurContext->getDeclKind()) {
11423 case Decl::TranslationUnit:
11424 return true;
11425 case Decl::LinkageSpec:
11426 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
11427 default:
11428 return false;
11429 }
11430}
11431
11432namespace {
11433
11434// Callback to only accept typo corrections that are namespaces.
11435class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
11436public:
11437 bool ValidateCandidate(const TypoCorrection &candidate) override {
11438 if (NamedDecl *ND = candidate.getCorrectionDecl())
11439 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
11440 return false;
11441 }
11442
11443 std::unique_ptr<CorrectionCandidateCallback> clone() override {
11444 return std::make_unique<NamespaceValidatorCCC>(*this);
11445 }
11446};
11447
11448}
11449
11450static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
11451 CXXScopeSpec &SS,
11452 SourceLocation IdentLoc,
11453 IdentifierInfo *Ident) {
11454 R.clear();
11455 NamespaceValidatorCCC CCC{};
11456 if (TypoCorrection Corrected =
11457 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS, CCC,
11458 Sema::CTK_ErrorRecovery)) {
11459 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
11460 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
11461 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
11462 Ident->getName().equals(CorrectedStr);
11463 S.diagnoseTypo(Corrected,
11464 S.PDiag(diag::err_using_directive_member_suggest)
11465 << Ident << DC << DroppedSpecifier << SS.getRange(),
11466 S.PDiag(diag::note_namespace_defined_here));
11467 } else {
11468 S.diagnoseTypo(Corrected,
11469 S.PDiag(diag::err_using_directive_suggest) << Ident,
11470 S.PDiag(diag::note_namespace_defined_here));
11471 }
11472 R.addDecl(Corrected.getFoundDecl());
11473 return true;
11474 }
11475 return false;
11476}
11477
11478Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
11479 SourceLocation NamespcLoc, CXXScopeSpec &SS,
11480 SourceLocation IdentLoc,
11481 IdentifierInfo *NamespcName,
11482 const ParsedAttributesView &AttrList) {
11483 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast<void> (0));
11484 assert(NamespcName && "Invalid NamespcName.")(static_cast<void> (0));
11485 assert(IdentLoc.isValid() && "Invalid NamespceName location.")(static_cast<void> (0));
11486
11487 // This can only happen along a recovery path.
11488 while (S->isTemplateParamScope())
11489 S = S->getParent();
11490 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast<void> (0));
11491
11492 UsingDirectiveDecl *UDir = nullptr;
11493 NestedNameSpecifier *Qualifier = nullptr;
11494 if (SS.isSet())
11495 Qualifier = SS.getScopeRep();
11496
11497 // Lookup namespace name.
11498 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
11499 LookupParsedName(R, S, &SS);
11500 if (R.isAmbiguous())
11501 return nullptr;
11502
11503 if (R.empty()) {
11504 R.clear();
11505 // Allow "using namespace std;" or "using namespace ::std;" even if
11506 // "std" hasn't been defined yet, for GCC compatibility.
11507 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
11508 NamespcName->isStr("std")) {
11509 Diag(IdentLoc, diag::ext_using_undefined_std);
11510 R.addDecl(getOrCreateStdNamespace());
11511 R.resolveKind();
11512 }
11513 // Otherwise, attempt typo correction.
11514 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
11515 }
11516
11517 if (!R.empty()) {
11518 NamedDecl *Named = R.getRepresentativeDecl();
11519 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
11520 assert(NS && "expected namespace decl")(static_cast<void> (0));
11521
11522 // The use of a nested name specifier may trigger deprecation warnings.
11523 DiagnoseUseOfDecl(Named, IdentLoc);
11524
11525 // C++ [namespace.udir]p1:
11526 // A using-directive specifies that the names in the nominated
11527 // namespace can be used in the scope in which the
11528 // using-directive appears after the using-directive. During
11529 // unqualified name lookup (3.4.1), the names appear as if they
11530 // were declared in the nearest enclosing namespace which
11531 // contains both the using-directive and the nominated
11532 // namespace. [Note: in this context, "contains" means "contains
11533 // directly or indirectly". ]
11534
11535 // Find enclosing context containing both using-directive and
11536 // nominated namespace.
11537 DeclContext *CommonAncestor = NS;
11538 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
11539 CommonAncestor = CommonAncestor->getParent();
11540
11541 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
11542 SS.getWithLocInContext(Context),
11543 IdentLoc, Named, CommonAncestor);
11544
11545 if (IsUsingDirectiveInToplevelContext(CurContext) &&
11546 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
11547 Diag(IdentLoc, diag::warn_using_directive_in_header);
11548 }
11549
11550 PushUsingDirective(S, UDir);
11551 } else {
11552 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
11553 }
11554
11555 if (UDir)
11556 ProcessDeclAttributeList(S, UDir, AttrList);
11557
11558 return UDir;
11559}
11560
11561void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
11562 // If the scope has an associated entity and the using directive is at
11563 // namespace or translation unit scope, add the UsingDirectiveDecl into
11564 // its lookup structure so qualified name lookup can find it.
11565 DeclContext *Ctx = S->getEntity();
11566 if (Ctx && !Ctx->isFunctionOrMethod())
11567 Ctx->addDecl(UDir);
11568 else
11569 // Otherwise, it is at block scope. The using-directives will affect lookup
11570 // only to the end of the scope.
11571 S->PushUsingDirective(UDir);
11572}
11573
11574Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
11575 SourceLocation UsingLoc,
11576 SourceLocation TypenameLoc, CXXScopeSpec &SS,
11577 UnqualifiedId &Name,
11578 SourceLocation EllipsisLoc,
11579 const ParsedAttributesView &AttrList) {
11580 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.")(static_cast<void> (0));
11581
11582 if (SS.isEmpty()) {
11583 Diag(Name.getBeginLoc(), diag::err_using_requires_qualname);
11584 return nullptr;
11585 }
11586
11587 switch (Name.getKind()) {
11588 case UnqualifiedIdKind::IK_ImplicitSelfParam:
11589 case UnqualifiedIdKind::IK_Identifier:
11590 case UnqualifiedIdKind::IK_OperatorFunctionId:
11591 case UnqualifiedIdKind::IK_LiteralOperatorId:
11592 case UnqualifiedIdKind::IK_ConversionFunctionId:
11593 break;
11594
11595 case UnqualifiedIdKind::IK_ConstructorName:
11596 case UnqualifiedIdKind::IK_ConstructorTemplateId:
11597 // C++11 inheriting constructors.
11598 Diag(Name.getBeginLoc(),
11599 getLangOpts().CPlusPlus11
11600 ? diag::warn_cxx98_compat_using_decl_constructor
11601 : diag::err_using_decl_constructor)
11602 << SS.getRange();
11603
11604 if (getLangOpts().CPlusPlus11) break;
11605
11606 return nullptr;
11607
11608 case UnqualifiedIdKind::IK_DestructorName:
11609 Diag(Name.getBeginLoc(), diag::err_using_decl_destructor) << SS.getRange();
11610 return nullptr;
11611
11612 case UnqualifiedIdKind::IK_TemplateId:
11613 Diag(Name.getBeginLoc(), diag::err_using_decl_template_id)
11614 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
11615 return nullptr;
11616
11617 case UnqualifiedIdKind::IK_DeductionGuideName:
11618 llvm_unreachable("cannot parse qualified deduction guide name")__builtin_unreachable();
11619 }
11620
11621 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
11622 DeclarationName TargetName = TargetNameInfo.getName();
11623 if (!TargetName)
11624 return nullptr;
11625
11626 // Warn about access declarations.
11627 if (UsingLoc.isInvalid()) {
11628 Diag(Name.getBeginLoc(), getLangOpts().CPlusPlus11
11629 ? diag::err_access_decl
11630 : diag::warn_access_decl_deprecated)
11631 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
11632 }
11633
11634 if (EllipsisLoc.isInvalid()) {
11635 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
11636 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
11637 return nullptr;
11638 } else {
11639 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
11640 !TargetNameInfo.containsUnexpandedParameterPack()) {
11641 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
11642 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
11643 EllipsisLoc = SourceLocation();
11644 }
11645 }
11646
11647 NamedDecl *UD =
11648 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
11649 SS, TargetNameInfo, EllipsisLoc, AttrList,
11650 /*IsInstantiation*/ false,
11651 AttrList.hasAttribute(ParsedAttr::AT_UsingIfExists));
11652 if (UD)
11653 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11654
11655 return UD;
11656}
11657
11658Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
11659 SourceLocation UsingLoc,
11660 SourceLocation EnumLoc,
11661 const DeclSpec &DS) {
11662 switch (DS.getTypeSpecType()) {
11663 case DeclSpec::TST_error:
11664 // This will already have been diagnosed
11665 return nullptr;
11666
11667 case DeclSpec::TST_enum:
11668 break;
11669
11670 case DeclSpec::TST_typename:
11671 Diag(DS.getTypeSpecTypeLoc(), diag::err_using_enum_is_dependent);
11672 return nullptr;
11673
11674 default:
11675 llvm_unreachable("unexpected DeclSpec type")__builtin_unreachable();
11676 }
11677
11678 // As with enum-decls, we ignore attributes for now.
11679 auto *Enum = cast<EnumDecl>(DS.getRepAsDecl());
11680 if (auto *Def = Enum->getDefinition())
11681 Enum = Def;
11682
11683 auto *UD = BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc,
11684 DS.getTypeSpecTypeNameLoc(), Enum);
11685 if (UD)
11686 PushOnScopeChains(UD, S, /*AddToContext*/ false);
11687
11688 return UD;
11689}
11690
11691/// Determine whether a using declaration considers the given
11692/// declarations as "equivalent", e.g., if they are redeclarations of
11693/// the same entity or are both typedefs of the same type.
11694static bool
11695IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
11696 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
11697 return true;
11698
11699 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
11700 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
11701 return Context.hasSameType(TD1->getUnderlyingType(),
11702 TD2->getUnderlyingType());
11703
11704 // Two using_if_exists using-declarations are equivalent if both are
11705 // unresolved.
11706 if (isa<UnresolvedUsingIfExistsDecl>(D1) &&
11707 isa<UnresolvedUsingIfExistsDecl>(D2))
11708 return true;
11709
11710 return false;
11711}
11712
11713
11714/// Determines whether to create a using shadow decl for a particular
11715/// decl, given the set of decls existing prior to this using lookup.
11716bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
11717 const LookupResult &Previous,
11718 UsingShadowDecl *&PrevShadow) {
11719 // Diagnose finding a decl which is not from a base class of the
11720 // current class. We do this now because there are cases where this
11721 // function will silently decide not to build a shadow decl, which
11722 // will pre-empt further diagnostics.
11723 //
11724 // We don't need to do this in C++11 because we do the check once on
11725 // the qualifier.
11726 //
11727 // FIXME: diagnose the following if we care enough:
11728 // struct A { int foo; };
11729 // struct B : A { using A::foo; };
11730 // template <class T> struct C : A {};
11731 // template <class T> struct D : C<T> { using B::foo; } // <---
11732 // This is invalid (during instantiation) in C++03 because B::foo
11733 // resolves to the using decl in B, which is not a base class of D<T>.
11734 // We can't diagnose it immediately because C<T> is an unknown
11735 // specialization. The UsingShadowDecl in D<T> then points directly
11736 // to A::foo, which will look well-formed when we instantiate.
11737 // The right solution is to not collapse the shadow-decl chain.
11738 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
11739 if (auto *Using = dyn_cast<UsingDecl>(BUD)) {
11740 DeclContext *OrigDC = Orig->getDeclContext();
11741
11742 // Handle enums and anonymous structs.
11743 if (isa<EnumDecl>(OrigDC))
11744 OrigDC = OrigDC->getParent();
11745 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
11746 while (OrigRec->isAnonymousStructOrUnion())
11747 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
11748
11749 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
11750 if (OrigDC == CurContext) {
11751 Diag(Using->getLocation(),
11752 diag::err_using_decl_nested_name_specifier_is_current_class)
11753 << Using->getQualifierLoc().getSourceRange();
11754 Diag(Orig->getLocation(), diag::note_using_decl_target);
11755 Using->setInvalidDecl();
11756 return true;
11757 }
11758
11759 Diag(Using->getQualifierLoc().getBeginLoc(),
11760 diag::err_using_decl_nested_name_specifier_is_not_base_class)
11761 << Using->getQualifier() << cast<CXXRecordDecl>(CurContext)
11762 << Using->getQualifierLoc().getSourceRange();
11763 Diag(Orig->getLocation(), diag::note_using_decl_target);
11764 Using->setInvalidDecl();
11765 return true;
11766 }
11767 }
11768
11769 if (Previous.empty()) return false;
11770
11771 NamedDecl *Target = Orig;
11772 if (isa<UsingShadowDecl>(Target))
11773 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11774
11775 // If the target happens to be one of the previous declarations, we
11776 // don't have a conflict.
11777 //
11778 // FIXME: but we might be increasing its access, in which case we
11779 // should redeclare it.
11780 NamedDecl *NonTag = nullptr, *Tag = nullptr;
11781 bool FoundEquivalentDecl = false;
11782 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
11783 I != E; ++I) {
11784 NamedDecl *D = (*I)->getUnderlyingDecl();
11785 // We can have UsingDecls in our Previous results because we use the same
11786 // LookupResult for checking whether the UsingDecl itself is a valid
11787 // redeclaration.
11788 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D) || isa<UsingEnumDecl>(D))
11789 continue;
11790
11791 if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
11792 // C++ [class.mem]p19:
11793 // If T is the name of a class, then [every named member other than
11794 // a non-static data member] shall have a name different from T
11795 if (RD->isInjectedClassName() && !isa<FieldDecl>(Target) &&
11796 !isa<IndirectFieldDecl>(Target) &&
11797 !isa<UnresolvedUsingValueDecl>(Target) &&
11798 DiagnoseClassNameShadow(
11799 CurContext,
11800 DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
11801 return true;
11802 }
11803
11804 if (IsEquivalentForUsingDecl(Context, D, Target)) {
11805 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
11806 PrevShadow = Shadow;
11807 FoundEquivalentDecl = true;
11808 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
11809 // We don't conflict with an existing using shadow decl of an equivalent
11810 // declaration, but we're not a redeclaration of it.
11811 FoundEquivalentDecl = true;
11812 }
11813
11814 if (isVisible(D))
11815 (isa<TagDecl>(D) ? Tag : NonTag) = D;
11816 }
11817
11818 if (FoundEquivalentDecl)
11819 return false;
11820
11821 // Always emit a diagnostic for a mismatch between an unresolved
11822 // using_if_exists and a resolved using declaration in either direction.
11823 if (isa<UnresolvedUsingIfExistsDecl>(Target) !=
11824 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(NonTag))) {
11825 if (!NonTag && !Tag)
11826 return false;
11827 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11828 Diag(Target->getLocation(), diag::note_using_decl_target);
11829 Diag((NonTag ? NonTag : Tag)->getLocation(),
11830 diag::note_using_decl_conflict);
11831 BUD->setInvalidDecl();
11832 return true;
11833 }
11834
11835 if (FunctionDecl *FD = Target->getAsFunction()) {
11836 NamedDecl *OldDecl = nullptr;
11837 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
11838 /*IsForUsingDecl*/ true)) {
11839 case Ovl_Overload:
11840 return false;
11841
11842 case Ovl_NonFunction:
11843 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11844 break;
11845
11846 // We found a decl with the exact signature.
11847 case Ovl_Match:
11848 // If we're in a record, we want to hide the target, so we
11849 // return true (without a diagnostic) to tell the caller not to
11850 // build a shadow decl.
11851 if (CurContext->isRecord())
11852 return true;
11853
11854 // If we're not in a record, this is an error.
11855 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11856 break;
11857 }
11858
11859 Diag(Target->getLocation(), diag::note_using_decl_target);
11860 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
11861 BUD->setInvalidDecl();
11862 return true;
11863 }
11864
11865 // Target is not a function.
11866
11867 if (isa<TagDecl>(Target)) {
11868 // No conflict between a tag and a non-tag.
11869 if (!Tag) return false;
11870
11871 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11872 Diag(Target->getLocation(), diag::note_using_decl_target);
11873 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
11874 BUD->setInvalidDecl();
11875 return true;
11876 }
11877
11878 // No conflict between a tag and a non-tag.
11879 if (!NonTag) return false;
11880
11881 Diag(BUD->getLocation(), diag::err_using_decl_conflict);
11882 Diag(Target->getLocation(), diag::note_using_decl_target);
11883 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
11884 BUD->setInvalidDecl();
11885 return true;
11886}
11887
11888/// Determine whether a direct base class is a virtual base class.
11889static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
11890 if (!Derived->getNumVBases())
11891 return false;
11892 for (auto &B : Derived->bases())
11893 if (B.getType()->getAsCXXRecordDecl() == Base)
11894 return B.isVirtual();
11895 llvm_unreachable("not a direct base class")__builtin_unreachable();
11896}
11897
11898/// Builds a shadow declaration corresponding to a 'using' declaration.
11899UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
11900 NamedDecl *Orig,
11901 UsingShadowDecl *PrevDecl) {
11902 // If we resolved to another shadow declaration, just coalesce them.
11903 NamedDecl *Target = Orig;
11904 if (isa<UsingShadowDecl>(Target)) {
11905 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
11906 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration")(static_cast<void> (0));
11907 }
11908
11909 NamedDecl *NonTemplateTarget = Target;
11910 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
11911 NonTemplateTarget = TargetTD->getTemplatedDecl();
11912
11913 UsingShadowDecl *Shadow;
11914 if (NonTemplateTarget && isa<CXXConstructorDecl>(NonTemplateTarget)) {
11915 UsingDecl *Using = cast<UsingDecl>(BUD);
11916 bool IsVirtualBase =
11917 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
11918 Using->getQualifier()->getAsRecordDecl());
11919 Shadow = ConstructorUsingShadowDecl::Create(
11920 Context, CurContext, Using->getLocation(), Using, Orig, IsVirtualBase);
11921 } else {
11922 Shadow = UsingShadowDecl::Create(Context, CurContext, BUD->getLocation(),
11923 Target->getDeclName(), BUD, Target);
11924 }
11925 BUD->addShadowDecl(Shadow);
11926
11927 Shadow->setAccess(BUD->getAccess());
11928 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
11929 Shadow->setInvalidDecl();
11930
11931 Shadow->setPreviousDecl(PrevDecl);
11932
11933 if (S)
11934 PushOnScopeChains(Shadow, S);
11935 else
11936 CurContext->addDecl(Shadow);
11937
11938
11939 return Shadow;
11940}
11941
11942/// Hides a using shadow declaration. This is required by the current
11943/// using-decl implementation when a resolvable using declaration in a
11944/// class is followed by a declaration which would hide or override
11945/// one or more of the using decl's targets; for example:
11946///
11947/// struct Base { void foo(int); };
11948/// struct Derived : Base {
11949/// using Base::foo;
11950/// void foo(int);
11951/// };
11952///
11953/// The governing language is C++03 [namespace.udecl]p12:
11954///
11955/// When a using-declaration brings names from a base class into a
11956/// derived class scope, member functions in the derived class
11957/// override and/or hide member functions with the same name and
11958/// parameter types in a base class (rather than conflicting).
11959///
11960/// There are two ways to implement this:
11961/// (1) optimistically create shadow decls when they're not hidden
11962/// by existing declarations, or
11963/// (2) don't create any shadow decls (or at least don't make them
11964/// visible) until we've fully parsed/instantiated the class.
11965/// The problem with (1) is that we might have to retroactively remove
11966/// a shadow decl, which requires several O(n) operations because the
11967/// decl structures are (very reasonably) not designed for removal.
11968/// (2) avoids this but is very fiddly and phase-dependent.
11969void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
11970 if (Shadow->getDeclName().getNameKind() ==
11971 DeclarationName::CXXConversionFunctionName)
11972 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
11973
11974 // Remove it from the DeclContext...
11975 Shadow->getDeclContext()->removeDecl(Shadow);
11976
11977 // ...and the scope, if applicable...
11978 if (S) {
11979 S->RemoveDecl(Shadow);
11980 IdResolver.RemoveDecl(Shadow);
11981 }
11982
11983 // ...and the using decl.
11984 Shadow->getIntroducer()->removeShadowDecl(Shadow);
11985
11986 // TODO: complain somehow if Shadow was used. It shouldn't
11987 // be possible for this to happen, because...?
11988}
11989
11990/// Find the base specifier for a base class with the given type.
11991static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
11992 QualType DesiredBase,
11993 bool &AnyDependentBases) {
11994 // Check whether the named type is a direct base class.
11995 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified()
11996 .getUnqualifiedType();
11997 for (auto &Base : Derived->bases()) {
11998 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
11999 if (CanonicalDesiredBase == BaseType)
12000 return &Base;
12001 if (BaseType->isDependentType())
12002 AnyDependentBases = true;
12003 }
12004 return nullptr;
12005}
12006
12007namespace {
12008class UsingValidatorCCC final : public CorrectionCandidateCallback {
12009public:
12010 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
12011 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
12012 : HasTypenameKeyword(HasTypenameKeyword),
12013 IsInstantiation(IsInstantiation), OldNNS(NNS),
12014 RequireMemberOf(RequireMemberOf) {}
12015
12016 bool ValidateCandidate(const TypoCorrection &Candidate) override {
12017 NamedDecl *ND = Candidate.getCorrectionDecl();
12018
12019 // Keywords are not valid here.
12020 if (!ND || isa<NamespaceDecl>(ND))
12021 return false;
12022
12023 // Completely unqualified names are invalid for a 'using' declaration.
12024 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
12025 return false;
12026
12027 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
12028 // reject.
12029
12030 if (RequireMemberOf) {
12031 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12032 if (FoundRecord && FoundRecord->isInjectedClassName()) {
12033 // No-one ever wants a using-declaration to name an injected-class-name
12034 // of a base class, unless they're declaring an inheriting constructor.
12035 ASTContext &Ctx = ND->getASTContext();
12036 if (!Ctx.getLangOpts().CPlusPlus11)
12037 return false;
12038 QualType FoundType = Ctx.getRecordType(FoundRecord);
12039
12040 // Check that the injected-class-name is named as a member of its own
12041 // type; we don't want to suggest 'using Derived::Base;', since that
12042 // means something else.
12043 NestedNameSpecifier *Specifier =
12044 Candidate.WillReplaceSpecifier()
12045 ? Candidate.getCorrectionSpecifier()
12046 : OldNNS;
12047 if (!Specifier->getAsType() ||
12048 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
12049 return false;
12050
12051 // Check that this inheriting constructor declaration actually names a
12052 // direct base class of the current class.
12053 bool AnyDependentBases = false;
12054 if (!findDirectBaseWithType(RequireMemberOf,
12055 Ctx.getRecordType(FoundRecord),
12056 AnyDependentBases) &&
12057 !AnyDependentBases)
12058 return false;
12059 } else {
12060 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
12061 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
12062 return false;
12063
12064 // FIXME: Check that the base class member is accessible?
12065 }
12066 } else {
12067 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
12068 if (FoundRecord && FoundRecord->isInjectedClassName())
12069 return false;
12070 }
12071
12072 if (isa<TypeDecl>(ND))
12073 return HasTypenameKeyword || !IsInstantiation;
12074
12075 return !HasTypenameKeyword;
12076 }
12077
12078 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12079 return std::make_unique<UsingValidatorCCC>(*this);
12080 }
12081
12082private:
12083 bool HasTypenameKeyword;
12084 bool IsInstantiation;
12085 NestedNameSpecifier *OldNNS;
12086 CXXRecordDecl *RequireMemberOf;
12087};
12088} // end anonymous namespace
12089
12090/// Remove decls we can't actually see from a lookup being used to declare
12091/// shadow using decls.
12092///
12093/// \param S - The scope of the potential shadow decl
12094/// \param Previous - The lookup of a potential shadow decl's name.
12095void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
12096 // It is really dumb that we have to do this.
12097 LookupResult::Filter F = Previous.makeFilter();
12098 while (F.hasNext()) {
12099 NamedDecl *D = F.next();
12100 if (!isDeclInScope(D, CurContext, S))
12101 F.erase();
12102 // If we found a local extern declaration that's not ordinarily visible,
12103 // and this declaration is being added to a non-block scope, ignore it.
12104 // We're only checking for scope conflicts here, not also for violations
12105 // of the linkage rules.
12106 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
12107 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
12108 F.erase();
12109 }
12110 F.done();
12111}
12112
12113/// Builds a using declaration.
12114///
12115/// \param IsInstantiation - Whether this call arises from an
12116/// instantiation of an unresolved using declaration. We treat
12117/// the lookup differently for these declarations.
12118NamedDecl *Sema::BuildUsingDeclaration(
12119 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
12120 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
12121 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
12122 const ParsedAttributesView &AttrList, bool IsInstantiation,
12123 bool IsUsingIfExists) {
12124 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.")(static_cast<void> (0));
12125 SourceLocation IdentLoc = NameInfo.getLoc();
12126 assert(IdentLoc.isValid() && "Invalid TargetName location.")(static_cast<void> (0));
12127
12128 // FIXME: We ignore attributes for now.
12129
12130 // For an inheriting constructor declaration, the name of the using
12131 // declaration is the name of a constructor in this class, not in the
12132 // base class.
12133 DeclarationNameInfo UsingName = NameInfo;
12134 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
12135 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
12136 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12137 Context.getCanonicalType(Context.getRecordType(RD))));
12138
12139 // Do the redeclaration lookup in the current scope.
12140 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
12141 ForVisibleRedeclaration);
12142 Previous.setHideTags(false);
12143 if (S) {
12144 LookupName(Previous, S);
12145
12146 FilterUsingLookup(S, Previous);
12147 } else {
12148 assert(IsInstantiation && "no scope in non-instantiation")(static_cast<void> (0));
12149 if (CurContext->isRecord())
12150 LookupQualifiedName(Previous, CurContext);
12151 else {
12152 // No redeclaration check is needed here; in non-member contexts we
12153 // diagnosed all possible conflicts with other using-declarations when
12154 // building the template:
12155 //
12156 // For a dependent non-type using declaration, the only valid case is
12157 // if we instantiate to a single enumerator. We check for conflicts
12158 // between shadow declarations we introduce, and we check in the template
12159 // definition for conflicts between a non-type using declaration and any
12160 // other declaration, which together covers all cases.
12161 //
12162 // A dependent typename using declaration will never successfully
12163 // instantiate, since it will always name a class member, so we reject
12164 // that in the template definition.
12165 }
12166 }
12167
12168 // Check for invalid redeclarations.
12169 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
12170 SS, IdentLoc, Previous))
12171 return nullptr;
12172
12173 // 'using_if_exists' doesn't make sense on an inherited constructor.
12174 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
12175 DeclarationName::CXXConstructorName) {
12176 Diag(UsingLoc, diag::err_using_if_exists_on_ctor);
12177 return nullptr;
12178 }
12179
12180 DeclContext *LookupContext = computeDeclContext(SS);
12181 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
12182 if (!LookupContext || EllipsisLoc.isValid()) {
12183 NamedDecl *D;
12184 // Dependent scope, or an unexpanded pack
12185 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword,
12186 SS, NameInfo, IdentLoc))
12187 return nullptr;
12188
12189 if (HasTypenameKeyword) {
12190 // FIXME: not all declaration name kinds are legal here
12191 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
12192 UsingLoc, TypenameLoc,
12193 QualifierLoc,
12194 IdentLoc, NameInfo.getName(),
12195 EllipsisLoc);
12196 } else {
12197 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
12198 QualifierLoc, NameInfo, EllipsisLoc);
12199 }
12200 D->setAccess(AS);
12201 CurContext->addDecl(D);
12202 ProcessDeclAttributeList(S, D, AttrList);
12203 return D;
12204 }
12205
12206 auto Build = [&](bool Invalid) {
12207 UsingDecl *UD =
12208 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
12209 UsingName, HasTypenameKeyword);
12210 UD->setAccess(AS);
12211 CurContext->addDecl(UD);
12212 ProcessDeclAttributeList(S, UD, AttrList);
12213 UD->setInvalidDecl(Invalid);
12214 return UD;
12215 };
12216 auto BuildInvalid = [&]{ return Build(true); };
12217 auto BuildValid = [&]{ return Build(false); };
12218
12219 if (RequireCompleteDeclContext(SS, LookupContext))
12220 return BuildInvalid();
12221
12222 // Look up the target name.
12223 LookupResult R(*this, NameInfo, LookupOrdinaryName);
12224
12225 // Unlike most lookups, we don't always want to hide tag
12226 // declarations: tag names are visible through the using declaration
12227 // even if hidden by ordinary names, *except* in a dependent context
12228 // where it's important for the sanity of two-phase lookup.
12229 if (!IsInstantiation)
12230 R.setHideTags(false);
12231
12232 // For the purposes of this lookup, we have a base object type
12233 // equal to that of the current context.
12234 if (CurContext->isRecord()) {
12235 R.setBaseObjectType(
12236 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
12237 }
12238
12239 LookupQualifiedName(R, LookupContext);
12240
12241 // Validate the context, now we have a lookup
12242 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
12243 IdentLoc, &R))
12244 return nullptr;
12245
12246 if (R.empty() && IsUsingIfExists)
12247 R.addDecl(UnresolvedUsingIfExistsDecl::Create(Context, CurContext, UsingLoc,
12248 UsingName.getName()),
12249 AS_public);
12250
12251 // Try to correct typos if possible. If constructor name lookup finds no
12252 // results, that means the named class has no explicit constructors, and we
12253 // suppressed declaring implicit ones (probably because it's dependent or
12254 // invalid).
12255 if (R.empty() &&
12256 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
12257 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
12258 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
12259 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
12260 auto *II = NameInfo.getName().getAsIdentifierInfo();
12261 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
12262 CurContext->isStdNamespace() &&
12263 isa<TranslationUnitDecl>(LookupContext) &&
12264 getSourceManager().isInSystemHeader(UsingLoc))
12265 return nullptr;
12266 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
12267 dyn_cast<CXXRecordDecl>(CurContext));
12268 if (TypoCorrection Corrected =
12269 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS, CCC,
12270 CTK_ErrorRecovery)) {
12271 // We reject candidates where DroppedSpecifier == true, hence the
12272 // literal '0' below.
12273 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
12274 << NameInfo.getName() << LookupContext << 0
12275 << SS.getRange());
12276
12277 // If we picked a correction with no attached Decl we can't do anything
12278 // useful with it, bail out.
12279 NamedDecl *ND = Corrected.getCorrectionDecl();
12280 if (!ND)
12281 return BuildInvalid();
12282
12283 // If we corrected to an inheriting constructor, handle it as one.
12284 auto *RD = dyn_cast<CXXRecordDecl>(ND);
12285 if (RD && RD->isInjectedClassName()) {
12286 // The parent of the injected class name is the class itself.
12287 RD = cast<CXXRecordDecl>(RD->getParent());
12288
12289 // Fix up the information we'll use to build the using declaration.
12290 if (Corrected.WillReplaceSpecifier()) {
12291 NestedNameSpecifierLocBuilder Builder;
12292 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
12293 QualifierLoc.getSourceRange());
12294 QualifierLoc = Builder.getWithLocInContext(Context);
12295 }
12296
12297 // In this case, the name we introduce is the name of a derived class
12298 // constructor.
12299 auto *CurClass = cast<CXXRecordDecl>(CurContext);
12300 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
12301 Context.getCanonicalType(Context.getRecordType(CurClass))));
12302 UsingName.setNamedTypeInfo(nullptr);
12303 for (auto *Ctor : LookupConstructors(RD))
12304 R.addDecl(Ctor);
12305 R.resolveKind();
12306 } else {
12307 // FIXME: Pick up all the declarations if we found an overloaded
12308 // function.
12309 UsingName.setName(ND->getDeclName());
12310 R.addDecl(ND);
12311 }
12312 } else {
12313 Diag(IdentLoc, diag::err_no_member)
12314 << NameInfo.getName() << LookupContext << SS.getRange();
12315 return BuildInvalid();
12316 }
12317 }
12318
12319 if (R.isAmbiguous())
12320 return BuildInvalid();
12321
12322 if (HasTypenameKeyword) {
12323 // If we asked for a typename and got a non-type decl, error out.
12324 if (!R.getAsSingle<TypeDecl>() &&
12325 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
12326 Diag(IdentLoc, diag::err_using_typename_non_type);
12327 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12328 Diag((*I)->getUnderlyingDecl()->getLocation(),
12329 diag::note_using_decl_target);
12330 return BuildInvalid();
12331 }
12332 } else {
12333 // If we asked for a non-typename and we got a type, error out,
12334 // but only if this is an instantiation of an unresolved using
12335 // decl. Otherwise just silently find the type name.
12336 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
12337 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
12338 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
12339 return BuildInvalid();
12340 }
12341 }
12342
12343 // C++14 [namespace.udecl]p6:
12344 // A using-declaration shall not name a namespace.
12345 if (R.getAsSingle<NamespaceDecl>()) {
12346 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
12347 << SS.getRange();
12348 return BuildInvalid();
12349 }
12350
12351 UsingDecl *UD = BuildValid();
12352
12353 // Some additional rules apply to inheriting constructors.
12354 if (UsingName.getName().getNameKind() ==
12355 DeclarationName::CXXConstructorName) {
12356 // Suppress access diagnostics; the access check is instead performed at the
12357 // point of use for an inheriting constructor.
12358 R.suppressDiagnostics();
12359 if (CheckInheritingConstructorUsingDecl(UD))
12360 return UD;
12361 }
12362
12363 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
12364 UsingShadowDecl *PrevDecl = nullptr;
12365 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
12366 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
12367 }
12368
12369 return UD;
12370}
12371
12372NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12373 SourceLocation UsingLoc,
12374 SourceLocation EnumLoc,
12375 SourceLocation NameLoc,
12376 EnumDecl *ED) {
12377 bool Invalid = false;
12378
12379 if (CurContext->getRedeclContext()->isRecord()) {
12380 /// In class scope, check if this is a duplicate, for better a diagnostic.
12381 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
12382 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
12383 ForVisibleRedeclaration);
12384
12385 LookupName(Previous, S);
12386
12387 for (NamedDecl *D : Previous)
12388 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(D))
12389 if (UED->getEnumDecl() == ED) {
12390 Diag(UsingLoc, diag::err_using_enum_decl_redeclaration)
12391 << SourceRange(EnumLoc, NameLoc);
12392 Diag(D->getLocation(), diag::note_using_enum_decl) << 1;
12393 Invalid = true;
12394 break;
12395 }
12396 }
12397
12398 if (RequireCompleteEnumDecl(ED, NameLoc))
12399 Invalid = true;
12400
12401 UsingEnumDecl *UD = UsingEnumDecl::Create(Context, CurContext, UsingLoc,
12402 EnumLoc, NameLoc, ED);
12403 UD->setAccess(AS);
12404 CurContext->addDecl(UD);
12405
12406 if (Invalid) {
12407 UD->setInvalidDecl();
12408 return UD;
12409 }
12410
12411 // Create the shadow decls for each enumerator
12412 for (EnumConstantDecl *EC : ED->enumerators()) {
12413 UsingShadowDecl *PrevDecl = nullptr;
12414 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
12415 LookupResult Previous(*this, DNI, LookupOrdinaryName,
12416 ForVisibleRedeclaration);
12417 LookupName(Previous, S);
12418 FilterUsingLookup(S, Previous);
12419
12420 if (!CheckUsingShadowDecl(UD, EC, Previous, PrevDecl))
12421 BuildUsingShadowDecl(S, UD, EC, PrevDecl);
12422 }
12423
12424 return UD;
12425}
12426
12427NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
12428 ArrayRef<NamedDecl *> Expansions) {
12429 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||(static_cast<void> (0))
12430 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||(static_cast<void> (0))
12431 isa<UsingPackDecl>(InstantiatedFrom))(static_cast<void> (0));
12432
12433 auto *UPD =
12434 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
12435 UPD->setAccess(InstantiatedFrom->getAccess());
12436 CurContext->addDecl(UPD);
12437 return UPD;
12438}
12439
12440/// Additional checks for a using declaration referring to a constructor name.
12441bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
12442 assert(!UD->hasTypename() && "expecting a constructor name")(static_cast<void> (0));
12443
12444 const Type *SourceType = UD->getQualifier()->getAsType();
12445 assert(SourceType &&(static_cast<void> (0))
12446 "Using decl naming constructor doesn't have type in scope spec.")(static_cast<void> (0));
12447 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
12448
12449 // Check whether the named type is a direct base class.
12450 bool AnyDependentBases = false;
12451 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
12452 AnyDependentBases);
12453 if (!Base && !AnyDependentBases) {
12454 Diag(UD->getUsingLoc(),
12455 diag::err_using_decl_constructor_not_in_direct_base)
12456 << UD->getNameInfo().getSourceRange()
12457 << QualType(SourceType, 0) << TargetClass;
12458 UD->setInvalidDecl();
12459 return true;
12460 }
12461
12462 if (Base)
12463 Base->setInheritConstructors();
12464
12465 return false;
12466}
12467
12468/// Checks that the given using declaration is not an invalid
12469/// redeclaration. Note that this is checking only for the using decl
12470/// itself, not for any ill-formedness among the UsingShadowDecls.
12471bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
12472 bool HasTypenameKeyword,
12473 const CXXScopeSpec &SS,
12474 SourceLocation NameLoc,
12475 const LookupResult &Prev) {
12476 NestedNameSpecifier *Qual = SS.getScopeRep();
12477
12478 // C++03 [namespace.udecl]p8:
12479 // C++0x [namespace.udecl]p10:
12480 // A using-declaration is a declaration and can therefore be used
12481 // repeatedly where (and only where) multiple declarations are
12482 // allowed.
12483 //
12484 // That's in non-member contexts.
12485 if (!CurContext->getRedeclContext()->isRecord()) {
12486 // A dependent qualifier outside a class can only ever resolve to an
12487 // enumeration type. Therefore it conflicts with any other non-type
12488 // declaration in the same scope.
12489 // FIXME: How should we check for dependent type-type conflicts at block
12490 // scope?
12491 if (Qual->isDependent() && !HasTypenameKeyword) {
12492 for (auto *D : Prev) {
12493 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
12494 bool OldCouldBeEnumerator =
12495 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
12496 Diag(NameLoc,
12497 OldCouldBeEnumerator ? diag::err_redefinition
12498 : diag::err_redefinition_different_kind)
12499 << Prev.getLookupName();
12500 Diag(D->getLocation(), diag::note_previous_definition);
12501 return true;
12502 }
12503 }
12504 }
12505 return false;
12506 }
12507
12508 const NestedNameSpecifier *CNNS =
12509 Context.getCanonicalNestedNameSpecifier(Qual);
12510 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
12511 NamedDecl *D = *I;
12512
12513 bool DTypename;
12514 NestedNameSpecifier *DQual;
12515 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
12516 DTypename = UD->hasTypename();
12517 DQual = UD->getQualifier();
12518 } else if (UnresolvedUsingValueDecl *UD
12519 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
12520 DTypename = false;
12521 DQual = UD->getQualifier();
12522 } else if (UnresolvedUsingTypenameDecl *UD
12523 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
12524 DTypename = true;
12525 DQual = UD->getQualifier();
12526 } else continue;
12527
12528 // using decls differ if one says 'typename' and the other doesn't.
12529 // FIXME: non-dependent using decls?
12530 if (HasTypenameKeyword != DTypename) continue;
12531
12532 // using decls differ if they name different scopes (but note that
12533 // template instantiation can cause this check to trigger when it
12534 // didn't before instantiation).
12535 if (CNNS != Context.getCanonicalNestedNameSpecifier(DQual))
12536 continue;
12537
12538 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
12539 Diag(D->getLocation(), diag::note_using_decl) << 1;
12540 return true;
12541 }
12542
12543 return false;
12544}
12545
12546/// Checks that the given nested-name qualifier used in a using decl
12547/// in the current context is appropriately related to the current
12548/// scope. If an error is found, diagnoses it and returns true.
12549/// R is nullptr, if the caller has not (yet) done a lookup, otherwise it's the
12550/// result of that lookup. UD is likewise nullptr, except when we have an
12551/// already-populated UsingDecl whose shadow decls contain the same information
12552/// (i.e. we're instantiating a UsingDecl with non-dependent scope).
12553bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
12554 const CXXScopeSpec &SS,
12555 const DeclarationNameInfo &NameInfo,
12556 SourceLocation NameLoc,
12557 const LookupResult *R, const UsingDecl *UD) {
12558 DeclContext *NamedContext = computeDeclContext(SS);
12559 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&(static_cast<void> (0))
12560 "resolvable context must have exactly one set of decls")(static_cast<void> (0));
12561
12562 // C++ 20 permits using an enumerator that does not have a class-hierarchy
12563 // relationship.
12564 bool Cxx20Enumerator = false;
12565 if (NamedContext) {
12566 EnumConstantDecl *EC = nullptr;
12567 if (R)
12568 EC = R->getAsSingle<EnumConstantDecl>();
12569 else if (UD && UD->shadow_size() == 1)
12570 EC = dyn_cast<EnumConstantDecl>(UD->shadow_begin()->getTargetDecl());
12571 if (EC)
12572 Cxx20Enumerator = getLangOpts().CPlusPlus20;
12573
12574 if (auto *ED = dyn_cast<EnumDecl>(NamedContext)) {
12575 // C++14 [namespace.udecl]p7:
12576 // A using-declaration shall not name a scoped enumerator.
12577 // C++20 p1099 permits enumerators.
12578 if (EC && R && ED->isScoped())
12579 Diag(SS.getBeginLoc(),
12580 getLangOpts().CPlusPlus20
12581 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
12582 : diag::ext_using_decl_scoped_enumerator)
12583 << SS.getRange();
12584
12585 // We want to consider the scope of the enumerator
12586 NamedContext = ED->getDeclContext();
12587 }
12588 }
12589
12590 if (!CurContext->isRecord()) {
12591 // C++03 [namespace.udecl]p3:
12592 // C++0x [namespace.udecl]p8:
12593 // A using-declaration for a class member shall be a member-declaration.
12594 // C++20 [namespace.udecl]p7
12595 // ... other than an enumerator ...
12596
12597 // If we weren't able to compute a valid scope, it might validly be a
12598 // dependent class or enumeration scope. If we have a 'typename' keyword,
12599 // the scope must resolve to a class type.
12600 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
12601 : !HasTypename)
12602 return false; // OK
12603
12604 Diag(NameLoc,
12605 Cxx20Enumerator
12606 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
12607 : diag::err_using_decl_can_not_refer_to_class_member)
12608 << SS.getRange();
12609
12610 if (Cxx20Enumerator)
12611 return false; // OK
12612
12613 auto *RD = NamedContext
12614 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
12615 : nullptr;
12616 if (RD && !RequireCompleteDeclContext(const_cast<CXXScopeSpec &>(SS), RD)) {
12617 // See if there's a helpful fixit
12618
12619 if (!R) {
12620 // We will have already diagnosed the problem on the template
12621 // definition, Maybe we should do so again?
12622 } else if (R->getAsSingle<TypeDecl>()) {
12623 if (getLangOpts().CPlusPlus11) {
12624 // Convert 'using X::Y;' to 'using Y = X::Y;'.
12625 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
12626 << 0 // alias declaration
12627 << FixItHint::CreateInsertion(SS.getBeginLoc(),
12628 NameInfo.getName().getAsString() +
12629 " = ");
12630 } else {
12631 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
12632 SourceLocation InsertLoc = getLocForEndOfToken(NameInfo.getEndLoc());
12633 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
12634 << 1 // typedef declaration
12635 << FixItHint::CreateReplacement(UsingLoc, "typedef")
12636 << FixItHint::CreateInsertion(
12637 InsertLoc, " " + NameInfo.getName().getAsString());
12638 }
12639 } else if (R->getAsSingle<VarDecl>()) {
12640 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12641 // repeating the type of the static data member here.
12642 FixItHint FixIt;
12643 if (getLangOpts().CPlusPlus11) {
12644 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12645 FixIt = FixItHint::CreateReplacement(
12646 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
12647 }
12648
12649 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12650 << 2 // reference declaration
12651 << FixIt;
12652 } else if (R->getAsSingle<EnumConstantDecl>()) {
12653 // Don't provide a fixit outside C++11 mode; we don't want to suggest
12654 // repeating the type of the enumeration here, and we can't do so if
12655 // the type is anonymous.
12656 FixItHint FixIt;
12657 if (getLangOpts().CPlusPlus11) {
12658 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
12659 FixIt = FixItHint::CreateReplacement(
12660 UsingLoc,
12661 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
12662 }
12663
12664 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
12665 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
12666 << FixIt;
12667 }
12668 }
12669
12670 return true; // Fail
12671 }
12672
12673 // If the named context is dependent, we can't decide much.
12674 if (!NamedContext) {
12675 // FIXME: in C++0x, we can diagnose if we can prove that the
12676 // nested-name-specifier does not refer to a base class, which is
12677 // still possible in some cases.
12678
12679 // Otherwise we have to conservatively report that things might be
12680 // okay.
12681 return false;
12682 }
12683
12684 // The current scope is a record.
12685 if (!NamedContext->isRecord()) {
12686 // Ideally this would point at the last name in the specifier,
12687 // but we don't have that level of source info.
12688 Diag(SS.getBeginLoc(),
12689 Cxx20Enumerator
12690 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
12691 : diag::err_using_decl_nested_name_specifier_is_not_class)
12692 << SS.getScopeRep() << SS.getRange();
12693
12694 if (Cxx20Enumerator)
12695 return false; // OK
12696
12697 return true;
12698 }
12699
12700 if (!NamedContext->isDependentContext() &&
12701 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
12702 return true;
12703
12704 if (getLangOpts().CPlusPlus11) {
12705 // C++11 [namespace.udecl]p3:
12706 // In a using-declaration used as a member-declaration, the
12707 // nested-name-specifier shall name a base class of the class
12708 // being defined.
12709
12710 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
12711 cast<CXXRecordDecl>(NamedContext))) {
12712
12713 if (Cxx20Enumerator) {
12714 Diag(NameLoc, diag::warn_cxx17_compat_using_decl_non_member_enumerator)
12715 << SS.getRange();
12716 return false;
12717 }
12718
12719 if (CurContext == NamedContext) {
12720 Diag(SS.getBeginLoc(),
12721 diag::err_using_decl_nested_name_specifier_is_current_class)
12722 << SS.getRange();
12723 return !getLangOpts().CPlusPlus20;
12724 }
12725
12726 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
12727 Diag(SS.getBeginLoc(),
12728 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12729 << SS.getScopeRep() << cast<CXXRecordDecl>(CurContext)
12730 << SS.getRange();
12731 }
12732 return true;
12733 }
12734
12735 return false;
12736 }
12737
12738 // C++03 [namespace.udecl]p4:
12739 // A using-declaration used as a member-declaration shall refer
12740 // to a member of a base class of the class being defined [etc.].
12741
12742 // Salient point: SS doesn't have to name a base class as long as
12743 // lookup only finds members from base classes. Therefore we can
12744 // diagnose here only if we can prove that that can't happen,
12745 // i.e. if the class hierarchies provably don't intersect.
12746
12747 // TODO: it would be nice if "definitely valid" results were cached
12748 // in the UsingDecl and UsingShadowDecl so that these checks didn't
12749 // need to be repeated.
12750
12751 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
12752 auto Collect = [&Bases](const CXXRecordDecl *Base) {
12753 Bases.insert(Base);
12754 return true;
12755 };
12756
12757 // Collect all bases. Return false if we find a dependent base.
12758 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
12759 return false;
12760
12761 // Returns true if the base is dependent or is one of the accumulated base
12762 // classes.
12763 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
12764 return !Bases.count(Base);
12765 };
12766
12767 // Return false if the class has a dependent base or if it or one
12768 // of its bases is present in the base set of the current context.
12769 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
12770 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
12771 return false;
12772
12773 Diag(SS.getRange().getBegin(),
12774 diag::err_using_decl_nested_name_specifier_is_not_base_class)
12775 << SS.getScopeRep()
12776 << cast<CXXRecordDecl>(CurContext)
12777 << SS.getRange();
12778
12779 return true;
12780}
12781
12782Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
12783 MultiTemplateParamsArg TemplateParamLists,
12784 SourceLocation UsingLoc, UnqualifiedId &Name,
12785 const ParsedAttributesView &AttrList,
12786 TypeResult Type, Decl *DeclFromDeclSpec) {
12787 // Skip up to the relevant declaration scope.
12788 while (S->isTemplateParamScope())
12789 S = S->getParent();
12790 assert((S->getFlags() & Scope::DeclScope) &&(static_cast<void> (0))
12791 "got alias-declaration outside of declaration scope")(static_cast<void> (0));
12792
12793 if (Type.isInvalid())
12794 return nullptr;
12795
12796 bool Invalid = false;
12797 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
12798 TypeSourceInfo *TInfo = nullptr;
12799 GetTypeFromParser(Type.get(), &TInfo);
12800
12801 if (DiagnoseClassNameShadow(CurContext, NameInfo))
12802 return nullptr;
12803
12804 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
12805 UPPC_DeclarationType)) {
12806 Invalid = true;
12807 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
12808 TInfo->getTypeLoc().getBeginLoc());
12809 }
12810
12811 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
12812 TemplateParamLists.size()
12813 ? forRedeclarationInCurContext()
12814 : ForVisibleRedeclaration);
12815 LookupName(Previous, S);
12816
12817 // Warn about shadowing the name of a template parameter.
12818 if (Previous.isSingleResult() &&
12819 Previous.getFoundDecl()->isTemplateParameter()) {
12820 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
12821 Previous.clear();
12822 }
12823
12824 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&(static_cast<void> (0))
12825 "name in alias declaration must be an identifier")(static_cast<void> (0));
12826 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
12827 Name.StartLocation,
12828 Name.Identifier, TInfo);
12829
12830 NewTD->setAccess(AS);
12831
12832 if (Invalid)
12833 NewTD->setInvalidDecl();
12834
12835 ProcessDeclAttributeList(S, NewTD, AttrList);
12836 AddPragmaAttributes(S, NewTD);
12837
12838 CheckTypedefForVariablyModifiedType(S, NewTD);
12839 Invalid |= NewTD->isInvalidDecl();
12840
12841 bool Redeclaration = false;
12842
12843 NamedDecl *NewND;
12844 if (TemplateParamLists.size()) {
12845 TypeAliasTemplateDecl *OldDecl = nullptr;
12846 TemplateParameterList *OldTemplateParams = nullptr;
12847
12848 if (TemplateParamLists.size() != 1) {
12849 Diag(UsingLoc, diag::err_alias_template_extra_headers)
12850 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
12851 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
12852 }
12853 TemplateParameterList *TemplateParams = TemplateParamLists[0];
12854
12855 // Check that we can declare a template here.
12856 if (CheckTemplateDeclScope(S, TemplateParams))
12857 return nullptr;
12858
12859 // Only consider previous declarations in the same scope.
12860 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
12861 /*ExplicitInstantiationOrSpecialization*/false);
12862 if (!Previous.empty()) {
12863 Redeclaration = true;
12864
12865 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
12866 if (!OldDecl && !Invalid) {
12867 Diag(UsingLoc, diag::err_redefinition_different_kind)
12868 << Name.Identifier;
12869
12870 NamedDecl *OldD = Previous.getRepresentativeDecl();
12871 if (OldD->getLocation().isValid())
12872 Diag(OldD->getLocation(), diag::note_previous_definition);
12873
12874 Invalid = true;
12875 }
12876
12877 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
12878 if (TemplateParameterListsAreEqual(TemplateParams,
12879 OldDecl->getTemplateParameters(),
12880 /*Complain=*/true,
12881 TPL_TemplateMatch))
12882 OldTemplateParams =
12883 OldDecl->getMostRecentDecl()->getTemplateParameters();
12884 else
12885 Invalid = true;
12886
12887 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
12888 if (!Invalid &&
12889 !Context.hasSameType(OldTD->getUnderlyingType(),
12890 NewTD->getUnderlyingType())) {
12891 // FIXME: The C++0x standard does not clearly say this is ill-formed,
12892 // but we can't reasonably accept it.
12893 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
12894 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
12895 if (OldTD->getLocation().isValid())
12896 Diag(OldTD->getLocation(), diag::note_previous_definition);
12897 Invalid = true;
12898 }
12899 }
12900 }
12901
12902 // Merge any previous default template arguments into our parameters,
12903 // and check the parameter list.
12904 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
12905 TPC_TypeAliasTemplate))
12906 return nullptr;
12907
12908 TypeAliasTemplateDecl *NewDecl =
12909 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
12910 Name.Identifier, TemplateParams,
12911 NewTD);
12912 NewTD->setDescribedAliasTemplate(NewDecl);
12913
12914 NewDecl->setAccess(AS);
12915
12916 if (Invalid)
12917 NewDecl->setInvalidDecl();
12918 else if (OldDecl) {
12919 NewDecl->setPreviousDecl(OldDecl);
12920 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
12921 }
12922
12923 NewND = NewDecl;
12924 } else {
12925 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
12926 setTagNameForLinkagePurposes(TD, NewTD);
12927 handleTagNumbering(TD, S);
12928 }
12929 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
12930 NewND = NewTD;
12931 }
12932
12933 PushOnScopeChains(NewND, S);
12934 ActOnDocumentableDecl(NewND);
12935 return NewND;
12936}
12937
12938Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
12939 SourceLocation AliasLoc,
12940 IdentifierInfo *Alias, CXXScopeSpec &SS,
12941 SourceLocation IdentLoc,
12942 IdentifierInfo *Ident) {
12943
12944 // Lookup the namespace name.
12945 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
12946 LookupParsedName(R, S, &SS);
12947
12948 if (R.isAmbiguous())
12949 return nullptr;
12950
12951 if (R.empty()) {
12952 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
12953 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
12954 return nullptr;
12955 }
12956 }
12957 assert(!R.isAmbiguous() && !R.empty())(static_cast<void> (0));
12958 NamedDecl *ND = R.getRepresentativeDecl();
12959
12960 // Check if we have a previous declaration with the same name.
12961 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
12962 ForVisibleRedeclaration);
12963 LookupName(PrevR, S);
12964
12965 // Check we're not shadowing a template parameter.
12966 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
12967 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
12968 PrevR.clear();
12969 }
12970
12971 // Filter out any other lookup result from an enclosing scope.
12972 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
12973 /*AllowInlineNamespace*/false);
12974
12975 // Find the previous declaration and check that we can redeclare it.
12976 NamespaceAliasDecl *Prev = nullptr;
12977 if (PrevR.isSingleResult()) {
12978 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
12979 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
12980 // We already have an alias with the same name that points to the same
12981 // namespace; check that it matches.
12982 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
12983 Prev = AD;
12984 } else if (isVisible(PrevDecl)) {
12985 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
12986 << Alias;
12987 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
12988 << AD->getNamespace();
12989 return nullptr;
12990 }
12991 } else if (isVisible(PrevDecl)) {
12992 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
12993 ? diag::err_redefinition
12994 : diag::err_redefinition_different_kind;
12995 Diag(AliasLoc, DiagID) << Alias;
12996 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12997 return nullptr;
12998 }
12999 }
13000
13001 // The use of a nested name specifier may trigger deprecation warnings.
13002 DiagnoseUseOfDecl(ND, IdentLoc);
13003
13004 NamespaceAliasDecl *AliasDecl =
13005 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
13006 Alias, SS.getWithLocInContext(Context),
13007 IdentLoc, ND);
13008 if (Prev)
13009 AliasDecl->setPreviousDecl(Prev);
13010
13011 PushOnScopeChains(AliasDecl, S);
13012 return AliasDecl;
13013}
13014
13015namespace {
13016struct SpecialMemberExceptionSpecInfo
13017 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
13018 SourceLocation Loc;
13019 Sema::ImplicitExceptionSpecification ExceptSpec;
13020
13021 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
13022 Sema::CXXSpecialMember CSM,
13023 Sema::InheritedConstructorInfo *ICI,
13024 SourceLocation Loc)
13025 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
13026
13027 bool visitBase(CXXBaseSpecifier *Base);
13028 bool visitField(FieldDecl *FD);
13029
13030 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
13031 unsigned Quals);
13032
13033 void visitSubobjectCall(Subobject Subobj,
13034 Sema::SpecialMemberOverloadResult SMOR);
13035};
13036}
13037
13038bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
13039 auto *RT = Base->getType()->getAs<RecordType>();
13040 if (!RT)
13041 return false;
13042
13043 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
13044 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
13045 if (auto *BaseCtor = SMOR.getMethod()) {
13046 visitSubobjectCall(Base, BaseCtor);
13047 return false;
13048 }
13049
13050 visitClassSubobject(BaseClass, Base, 0);
13051 return false;
13052}
13053
13054bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
13055 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
13056 Expr *E = FD->getInClassInitializer();
13057 if (!E)
13058 // FIXME: It's a little wasteful to build and throw away a
13059 // CXXDefaultInitExpr here.
13060 // FIXME: We should have a single context note pointing at Loc, and
13061 // this location should be MD->getLocation() instead, since that's
13062 // the location where we actually use the default init expression.
13063 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
13064 if (E)
13065 ExceptSpec.CalledExpr(E);
13066 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
13067 ->getAs<RecordType>()) {
13068 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
13069 FD->getType().getCVRQualifiers());
13070 }
13071 return false;
13072}
13073
13074void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
13075 Subobject Subobj,
13076 unsigned Quals) {
13077 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
13078 bool IsMutable = Field && Field->isMutable();
13079 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
13080}
13081
13082void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
13083 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
13084 // Note, if lookup fails, it doesn't matter what exception specification we
13085 // choose because the special member will be deleted.
13086 if (CXXMethodDecl *MD = SMOR.getMethod())
13087 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
13088}
13089
13090bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
13091 llvm::APSInt Result;
13092 ExprResult Converted = CheckConvertedConstantExpression(
13093 ExplicitSpec.getExpr(), Context.BoolTy, Result, CCEK_ExplicitBool);
13094 ExplicitSpec.setExpr(Converted.get());
13095 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
13096 ExplicitSpec.setKind(Result.getBoolValue()
13097 ? ExplicitSpecKind::ResolvedTrue
13098 : ExplicitSpecKind::ResolvedFalse);
13099 return true;
13100 }
13101 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
13102 return false;
13103}
13104
13105ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
13106 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
13107 if (!ExplicitExpr->isTypeDependent())
13108 tryResolveExplicitSpecifier(ES);
13109 return ES;
13110}
13111
13112static Sema::ImplicitExceptionSpecification
13113ComputeDefaultedSpecialMemberExceptionSpec(
13114 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
13115 Sema::InheritedConstructorInfo *ICI) {
13116 ComputingExceptionSpec CES(S, MD, Loc);
13117
13118 CXXRecordDecl *ClassDecl = MD->getParent();
13119
13120 // C++ [except.spec]p14:
13121 // An implicitly declared special member function (Clause 12) shall have an
13122 // exception-specification. [...]
13123 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
13124 if (ClassDecl->isInvalidDecl())
13125 return Info.ExceptSpec;
13126
13127 // FIXME: If this diagnostic fires, we're probably missing a check for
13128 // attempting to resolve an exception specification before it's known
13129 // at a higher level.
13130 if (S.RequireCompleteType(MD->getLocation(),
13131 S.Context.getRecordType(ClassDecl),
13132 diag::err_exception_spec_incomplete_type))
13133 return Info.ExceptSpec;
13134
13135 // C++1z [except.spec]p7:
13136 // [Look for exceptions thrown by] a constructor selected [...] to
13137 // initialize a potentially constructed subobject,
13138 // C++1z [except.spec]p8:
13139 // The exception specification for an implicitly-declared destructor, or a
13140 // destructor without a noexcept-specifier, is potentially-throwing if and
13141 // only if any of the destructors for any of its potentially constructed
13142 // subojects is potentially throwing.
13143 // FIXME: We respect the first rule but ignore the "potentially constructed"
13144 // in the second rule to resolve a core issue (no number yet) that would have
13145 // us reject:
13146 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
13147 // struct B : A {};
13148 // struct C : B { void f(); };
13149 // ... due to giving B::~B() a non-throwing exception specification.
13150 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
13151 : Info.VisitAllBases);
13152
13153 return Info.ExceptSpec;
13154}
13155
13156namespace {
13157/// RAII object to register a special member as being currently declared.
13158struct DeclaringSpecialMember {
13159 Sema &S;
13160 Sema::SpecialMemberDecl D;
13161 Sema::ContextRAII SavedContext;
13162 bool WasAlreadyBeingDeclared;
13163
13164 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
13165 : S(S), D(RD, CSM), SavedContext(S, RD) {
13166 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
13167 if (WasAlreadyBeingDeclared)
13168 // This almost never happens, but if it does, ensure that our cache
13169 // doesn't contain a stale result.
13170 S.SpecialMemberCache.clear();
13171 else {
13172 // Register a note to be produced if we encounter an error while
13173 // declaring the special member.
13174 Sema::CodeSynthesisContext Ctx;
13175 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
13176 // FIXME: We don't have a location to use here. Using the class's
13177 // location maintains the fiction that we declare all special members
13178 // with the class, but (1) it's not clear that lying about that helps our
13179 // users understand what's going on, and (2) there may be outer contexts
13180 // on the stack (some of which are relevant) and printing them exposes
13181 // our lies.
13182 Ctx.PointOfInstantiation = RD->getLocation();
13183 Ctx.Entity = RD;
13184 Ctx.SpecialMember = CSM;
13185 S.pushCodeSynthesisContext(Ctx);
13186 }
13187 }
13188 ~DeclaringSpecialMember() {
13189 if (!WasAlreadyBeingDeclared) {
13190 S.SpecialMembersBeingDeclared.erase(D);
13191 S.popCodeSynthesisContext();
13192 }
13193 }
13194
13195 /// Are we already trying to declare this special member?
13196 bool isAlreadyBeingDeclared() const {
13197 return WasAlreadyBeingDeclared;
13198 }
13199};
13200}
13201
13202void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
13203 // Look up any existing declarations, but don't trigger declaration of all
13204 // implicit special members with this name.
13205 DeclarationName Name = FD->getDeclName();
13206 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
13207 ForExternalRedeclaration);
13208 for (auto *D : FD->getParent()->lookup(Name))
13209 if (auto *Acceptable = R.getAcceptableDecl(D))
13210 R.addDecl(Acceptable);
13211 R.resolveKind();
13212 R.suppressDiagnostics();
13213
13214 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
13215}
13216
13217void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
13218 QualType ResultTy,
13219 ArrayRef<QualType> Args) {
13220 // Build an exception specification pointing back at this constructor.
13221 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, SpecialMem);
13222
13223 LangAS AS = getDefaultCXXMethodAddrSpace();
13224 if (AS != LangAS::Default) {
13225 EPI.TypeQuals.addAddressSpace(AS);
13226 }
13227
13228 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
13229 SpecialMem->setType(QT);
13230
13231 // During template instantiation of implicit special member functions we need
13232 // a reliable TypeSourceInfo for the function prototype in order to allow
13233 // functions to be substituted.
13234 if (inTemplateInstantiation() &&
13235 cast<CXXRecordDecl>(SpecialMem->getParent())->isLambda()) {
13236 TypeSourceInfo *TSI =
13237 Context.getTrivialTypeSourceInfo(SpecialMem->getType());
13238 SpecialMem->setTypeSourceInfo(TSI);
13239 }
13240}
13241
13242CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
13243 CXXRecordDecl *ClassDecl) {
13244 // C++ [class.ctor]p5:
13245 // A default constructor for a class X is a constructor of class X
13246 // that can be called without an argument. If there is no
13247 // user-declared constructor for class X, a default constructor is
13248 // implicitly declared. An implicitly-declared default constructor
13249 // is an inline public member of its class.
13250 assert(ClassDecl->needsImplicitDefaultConstructor() &&(static_cast<void> (0))
13251 "Should not build implicit default constructor!")(static_cast<void> (0));
13252
13253 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
13254 if (DSM.isAlreadyBeingDeclared())
13255 return nullptr;
13256
13257 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13258 CXXDefaultConstructor,
13259 false);
13260
13261 // Create the actual constructor declaration.
13262 CanQualType ClassType
13263 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13264 SourceLocation ClassLoc = ClassDecl->getLocation();
13265 DeclarationName Name
13266 = Context.DeclarationNames.getCXXConstructorName(ClassType);
13267 DeclarationNameInfo NameInfo(Name, ClassLoc);
13268 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
13269 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/ QualType(),
13270 /*TInfo=*/nullptr, ExplicitSpecifier(),
13271 getCurFPFeatures().isFPConstrained(),
13272 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
13273 Constexpr ? ConstexprSpecKind::Constexpr
13274 : ConstexprSpecKind::Unspecified);
13275 DefaultCon->setAccess(AS_public);
13276 DefaultCon->setDefaulted();
13277
13278 if (getLangOpts().CUDA) {
13279 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
13280 DefaultCon,
13281 /* ConstRHS */ false,
13282 /* Diagnose */ false);
13283 }
13284
13285 setupImplicitSpecialMemberType(DefaultCon, Context.VoidTy, None);
13286
13287 // We don't need to use SpecialMemberIsTrivial here; triviality for default
13288 // constructors is easy to compute.
13289 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
13290
13291 // Note that we have declared this constructor.
13292 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
13293
13294 Scope *S = getScopeForContext(ClassDecl);
13295 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
13296
13297 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
13298 SetDeclDeleted(DefaultCon, ClassLoc);
13299
13300 if (S)
13301 PushOnScopeChains(DefaultCon, S, false);
13302 ClassDecl->addDecl(DefaultCon);
13303
13304 return DefaultCon;
13305}
13306
13307void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
13308 CXXConstructorDecl *Constructor) {
13309 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&(static_cast<void> (0))
13310 !Constructor->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
13311 !Constructor->isDeleted()) &&(static_cast<void> (0))
13312 "DefineImplicitDefaultConstructor - call it for implicit default ctor")(static_cast<void> (0));
13313 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13314 return;
13315
13316 CXXRecordDecl *ClassDecl = Constructor->getParent();
13317 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor")(static_cast<void> (0));
13318
13319 SynthesizedFunctionScope Scope(*this, Constructor);
13320
13321 // The exception specification is needed because we are defining the
13322 // function.
13323 ResolveExceptionSpec(CurrentLocation,
13324 Constructor->getType()->castAs<FunctionProtoType>());
13325 MarkVTableUsed(CurrentLocation, ClassDecl);
13326
13327 // Add a context note for diagnostics produced after this point.
13328 Scope.addContextNote(CurrentLocation);
13329
13330 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
13331 Constructor->setInvalidDecl();
13332 return;
13333 }
13334
13335 SourceLocation Loc = Constructor->getEndLoc().isValid()
13336 ? Constructor->getEndLoc()
13337 : Constructor->getLocation();
13338 Constructor->setBody(new (Context) CompoundStmt(Loc));
13339 Constructor->markUsed(Context);
13340
13341 if (ASTMutationListener *L = getASTMutationListener()) {
13342 L->CompletedImplicitDefinition(Constructor);
13343 }
13344
13345 DiagnoseUninitializedFields(*this, Constructor);
13346}
13347
13348void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
13349 // Perform any delayed checks on exception specifications.
13350 CheckDelayedMemberExceptionSpecs();
13351}
13352
13353/// Find or create the fake constructor we synthesize to model constructing an
13354/// object of a derived class via a constructor of a base class.
13355CXXConstructorDecl *
13356Sema::findInheritingConstructor(SourceLocation Loc,
13357 CXXConstructorDecl *BaseCtor,
13358 ConstructorUsingShadowDecl *Shadow) {
13359 CXXRecordDecl *Derived = Shadow->getParent();
13360 SourceLocation UsingLoc = Shadow->getLocation();
13361
13362 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
13363 // For now we use the name of the base class constructor as a member of the
13364 // derived class to indicate a (fake) inherited constructor name.
13365 DeclarationName Name = BaseCtor->getDeclName();
13366
13367 // Check to see if we already have a fake constructor for this inherited
13368 // constructor call.
13369 for (NamedDecl *Ctor : Derived->lookup(Name))
13370 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
13371 ->getInheritedConstructor()
13372 .getConstructor(),
13373 BaseCtor))
13374 return cast<CXXConstructorDecl>(Ctor);
13375
13376 DeclarationNameInfo NameInfo(Name, UsingLoc);
13377 TypeSourceInfo *TInfo =
13378 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
13379 FunctionProtoTypeLoc ProtoLoc =
13380 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
13381
13382 // Check the inherited constructor is valid and find the list of base classes
13383 // from which it was inherited.
13384 InheritedConstructorInfo ICI(*this, Loc, Shadow);
13385
13386 bool Constexpr =
13387 BaseCtor->isConstexpr() &&
13388 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
13389 false, BaseCtor, &ICI);
13390
13391 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
13392 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
13393 BaseCtor->getExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
13394 /*isInline=*/true,
13395 /*isImplicitlyDeclared=*/true,
13396 Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
13397 InheritedConstructor(Shadow, BaseCtor),
13398 BaseCtor->getTrailingRequiresClause());
13399 if (Shadow->isInvalidDecl())
13400 DerivedCtor->setInvalidDecl();
13401
13402 // Build an unevaluated exception specification for this fake constructor.
13403 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
13404 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
13405 EPI.ExceptionSpec.Type = EST_Unevaluated;
13406 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
13407 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
13408 FPT->getParamTypes(), EPI));
13409
13410 // Build the parameter declarations.
13411 SmallVector<ParmVarDecl *, 16> ParamDecls;
13412 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
13413 TypeSourceInfo *TInfo =
13414 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
13415 ParmVarDecl *PD = ParmVarDecl::Create(
13416 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
13417 FPT->getParamType(I), TInfo, SC_None, /*DefArg=*/nullptr);
13418 PD->setScopeInfo(0, I);
13419 PD->setImplicit();
13420 // Ensure attributes are propagated onto parameters (this matters for
13421 // format, pass_object_size, ...).
13422 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
13423 ParamDecls.push_back(PD);
13424 ProtoLoc.setParam(I, PD);
13425 }
13426
13427 // Set up the new constructor.
13428 assert(!BaseCtor->isDeleted() && "should not use deleted constructor")(static_cast<void> (0));
13429 DerivedCtor->setAccess(BaseCtor->getAccess());
13430 DerivedCtor->setParams(ParamDecls);
13431 Derived->addDecl(DerivedCtor);
13432
13433 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
13434 SetDeclDeleted(DerivedCtor, UsingLoc);
13435
13436 return DerivedCtor;
13437}
13438
13439void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
13440 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
13441 Ctor->getInheritedConstructor().getShadowDecl());
13442 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
13443 /*Diagnose*/true);
13444}
13445
13446void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
13447 CXXConstructorDecl *Constructor) {
13448 CXXRecordDecl *ClassDecl = Constructor->getParent();
13449 assert(Constructor->getInheritedConstructor() &&(static_cast<void> (0))
13450 !Constructor->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
13451 !Constructor->isDeleted())(static_cast<void> (0));
13452 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
13453 return;
13454
13455 // Initializations are performed "as if by a defaulted default constructor",
13456 // so enter the appropriate scope.
13457 SynthesizedFunctionScope Scope(*this, Constructor);
13458
13459 // The exception specification is needed because we are defining the
13460 // function.
13461 ResolveExceptionSpec(CurrentLocation,
13462 Constructor->getType()->castAs<FunctionProtoType>());
13463 MarkVTableUsed(CurrentLocation, ClassDecl);
13464
13465 // Add a context note for diagnostics produced after this point.
13466 Scope.addContextNote(CurrentLocation);
13467
13468 ConstructorUsingShadowDecl *Shadow =
13469 Constructor->getInheritedConstructor().getShadowDecl();
13470 CXXConstructorDecl *InheritedCtor =
13471 Constructor->getInheritedConstructor().getConstructor();
13472
13473 // [class.inhctor.init]p1:
13474 // initialization proceeds as if a defaulted default constructor is used to
13475 // initialize the D object and each base class subobject from which the
13476 // constructor was inherited
13477
13478 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
13479 CXXRecordDecl *RD = Shadow->getParent();
13480 SourceLocation InitLoc = Shadow->getLocation();
13481
13482 // Build explicit initializers for all base classes from which the
13483 // constructor was inherited.
13484 SmallVector<CXXCtorInitializer*, 8> Inits;
13485 for (bool VBase : {false, true}) {
13486 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
13487 if (B.isVirtual() != VBase)
13488 continue;
13489
13490 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
13491 if (!BaseRD)
13492 continue;
13493
13494 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
13495 if (!BaseCtor.first)
13496 continue;
13497
13498 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
13499 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
13500 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
13501
13502 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
13503 Inits.push_back(new (Context) CXXCtorInitializer(
13504 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
13505 SourceLocation()));
13506 }
13507 }
13508
13509 // We now proceed as if for a defaulted default constructor, with the relevant
13510 // initializers replaced.
13511
13512 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
13513 Constructor->setInvalidDecl();
13514 return;
13515 }
13516
13517 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
13518 Constructor->markUsed(Context);
13519
13520 if (ASTMutationListener *L = getASTMutationListener()) {
13521 L->CompletedImplicitDefinition(Constructor);
13522 }
13523
13524 DiagnoseUninitializedFields(*this, Constructor);
13525}
13526
13527CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
13528 // C++ [class.dtor]p2:
13529 // If a class has no user-declared destructor, a destructor is
13530 // declared implicitly. An implicitly-declared destructor is an
13531 // inline public member of its class.
13532 assert(ClassDecl->needsImplicitDestructor())(static_cast<void> (0));
13533
13534 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
13535 if (DSM.isAlreadyBeingDeclared())
13536 return nullptr;
13537
13538 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
13539 CXXDestructor,
13540 false);
13541
13542 // Create the actual destructor declaration.
13543 CanQualType ClassType
13544 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
13545 SourceLocation ClassLoc = ClassDecl->getLocation();
13546 DeclarationName Name
13547 = Context.DeclarationNames.getCXXDestructorName(ClassType);
13548 DeclarationNameInfo NameInfo(Name, ClassLoc);
13549 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
13550 Context, ClassDecl, ClassLoc, NameInfo, QualType(), nullptr,
13551 getCurFPFeatures().isFPConstrained(),
13552 /*isInline=*/true,
13553 /*isImplicitlyDeclared=*/true,
13554 Constexpr ? ConstexprSpecKind::Constexpr
13555 : ConstexprSpecKind::Unspecified);
13556 Destructor->setAccess(AS_public);
13557 Destructor->setDefaulted();
13558
13559 if (getLangOpts().CUDA) {
13560 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
13561 Destructor,
13562 /* ConstRHS */ false,
13563 /* Diagnose */ false);
13564 }
13565
13566 setupImplicitSpecialMemberType(Destructor, Context.VoidTy, None);
13567
13568 // We don't need to use SpecialMemberIsTrivial here; triviality for
13569 // destructors is easy to compute.
13570 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
13571 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
13572 ClassDecl->hasTrivialDestructorForCall());
13573
13574 // Note that we have declared this destructor.
13575 ++getASTContext().NumImplicitDestructorsDeclared;
13576
13577 Scope *S = getScopeForContext(ClassDecl);
13578 CheckImplicitSpecialMemberDeclaration(S, Destructor);
13579
13580 // We can't check whether an implicit destructor is deleted before we complete
13581 // the definition of the class, because its validity depends on the alignment
13582 // of the class. We'll check this from ActOnFields once the class is complete.
13583 if (ClassDecl->isCompleteDefinition() &&
13584 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
13585 SetDeclDeleted(Destructor, ClassLoc);
13586
13587 // Introduce this destructor into its scope.
13588 if (S)
13589 PushOnScopeChains(Destructor, S, false);
13590 ClassDecl->addDecl(Destructor);
13591
13592 return Destructor;
13593}
13594
13595void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
13596 CXXDestructorDecl *Destructor) {
13597 assert((Destructor->isDefaulted() &&(static_cast<void> (0))
13598 !Destructor->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
13599 !Destructor->isDeleted()) &&(static_cast<void> (0))
13600 "DefineImplicitDestructor - call it for implicit default dtor")(static_cast<void> (0));
13601 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
13602 return;
13603
13604 CXXRecordDecl *ClassDecl = Destructor->getParent();
13605 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor")(static_cast<void> (0));
13606
13607 SynthesizedFunctionScope Scope(*this, Destructor);
13608
13609 // The exception specification is needed because we are defining the
13610 // function.
13611 ResolveExceptionSpec(CurrentLocation,
13612 Destructor->getType()->castAs<FunctionProtoType>());
13613 MarkVTableUsed(CurrentLocation, ClassDecl);
13614
13615 // Add a context note for diagnostics produced after this point.
13616 Scope.addContextNote(CurrentLocation);
13617
13618 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13619 Destructor->getParent());
13620
13621 if (CheckDestructor(Destructor)) {
13622 Destructor->setInvalidDecl();
13623 return;
13624 }
13625
13626 SourceLocation Loc = Destructor->getEndLoc().isValid()
13627 ? Destructor->getEndLoc()
13628 : Destructor->getLocation();
13629 Destructor->setBody(new (Context) CompoundStmt(Loc));
13630 Destructor->markUsed(Context);
13631
13632 if (ASTMutationListener *L = getASTMutationListener()) {
13633 L->CompletedImplicitDefinition(Destructor);
13634 }
13635}
13636
13637void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
13638 CXXDestructorDecl *Destructor) {
13639 if (Destructor->isInvalidDecl())
13640 return;
13641
13642 CXXRecordDecl *ClassDecl = Destructor->getParent();
13643 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&(static_cast<void> (0))
13644 "implicit complete dtors unneeded outside MS ABI")(static_cast<void> (0));
13645 assert(ClassDecl->getNumVBases() > 0 &&(static_cast<void> (0))
13646 "complete dtor only exists for classes with vbases")(static_cast<void> (0));
13647
13648 SynthesizedFunctionScope Scope(*this, Destructor);
13649
13650 // Add a context note for diagnostics produced after this point.
13651 Scope.addContextNote(CurrentLocation);
13652
13653 MarkVirtualBaseDestructorsReferenced(Destructor->getLocation(), ClassDecl);
13654}
13655
13656/// Perform any semantic analysis which needs to be delayed until all
13657/// pending class member declarations have been parsed.
13658void Sema::ActOnFinishCXXMemberDecls() {
13659 // If the context is an invalid C++ class, just suppress these checks.
13660 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
13661 if (Record->isInvalidDecl()) {
13662 DelayedOverridingExceptionSpecChecks.clear();
13663 DelayedEquivalentExceptionSpecChecks.clear();
13664 return;
13665 }
13666 checkForMultipleExportedDefaultConstructors(*this, Record);
13667 }
13668}
13669
13670void Sema::ActOnFinishCXXNonNestedClass() {
13671 referenceDLLExportedClassMethods();
13672
13673 if (!DelayedDllExportMemberFunctions.empty()) {
13674 SmallVector<CXXMethodDecl*, 4> WorkList;
13675 std::swap(DelayedDllExportMemberFunctions, WorkList);
13676 for (CXXMethodDecl *M : WorkList) {
13677 DefineDefaultedFunction(*this, M, M->getLocation());
13678
13679 // Pass the method to the consumer to get emitted. This is not necessary
13680 // for explicit instantiation definitions, as they will get emitted
13681 // anyway.
13682 if (M->getParent()->getTemplateSpecializationKind() !=
13683 TSK_ExplicitInstantiationDefinition)
13684 ActOnFinishInlineFunctionDef(M);
13685 }
13686 }
13687}
13688
13689void Sema::referenceDLLExportedClassMethods() {
13690 if (!DelayedDllExportClasses.empty()) {
13691 // Calling ReferenceDllExportedMembers might cause the current function to
13692 // be called again, so use a local copy of DelayedDllExportClasses.
13693 SmallVector<CXXRecordDecl *, 4> WorkList;
13694 std::swap(DelayedDllExportClasses, WorkList);
13695 for (CXXRecordDecl *Class : WorkList)
13696 ReferenceDllExportedMembers(*this, Class);
13697 }
13698}
13699
13700void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
13701 assert(getLangOpts().CPlusPlus11 &&(static_cast<void> (0))
13702 "adjusting dtor exception specs was introduced in c++11")(static_cast<void> (0));
13703
13704 if (Destructor->isDependentContext())
13705 return;
13706
13707 // C++11 [class.dtor]p3:
13708 // A declaration of a destructor that does not have an exception-
13709 // specification is implicitly considered to have the same exception-
13710 // specification as an implicit declaration.
13711 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
13712 if (DtorType->hasExceptionSpec())
13713 return;
13714
13715 // Replace the destructor's type, building off the existing one. Fortunately,
13716 // the only thing of interest in the destructor type is its extended info.
13717 // The return and arguments are fixed.
13718 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
13719 EPI.ExceptionSpec.Type = EST_Unevaluated;
13720 EPI.ExceptionSpec.SourceDecl = Destructor;
13721 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
13722
13723 // FIXME: If the destructor has a body that could throw, and the newly created
13724 // spec doesn't allow exceptions, we should emit a warning, because this
13725 // change in behavior can break conforming C++03 programs at runtime.
13726 // However, we don't have a body or an exception specification yet, so it
13727 // needs to be done somewhere else.
13728}
13729
13730namespace {
13731/// An abstract base class for all helper classes used in building the
13732// copy/move operators. These classes serve as factory functions and help us
13733// avoid using the same Expr* in the AST twice.
13734class ExprBuilder {
13735 ExprBuilder(const ExprBuilder&) = delete;
13736 ExprBuilder &operator=(const ExprBuilder&) = delete;
13737
13738protected:
13739 static Expr *assertNotNull(Expr *E) {
13740 assert(E && "Expression construction must not fail.")(static_cast<void> (0));
13741 return E;
13742 }
13743
13744public:
13745 ExprBuilder() {}
13746 virtual ~ExprBuilder() {}
13747
13748 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
13749};
13750
13751class RefBuilder: public ExprBuilder {
13752 VarDecl *Var;
13753 QualType VarType;
13754
13755public:
13756 Expr *build(Sema &S, SourceLocation Loc) const override {
13757 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc));
13758 }
13759
13760 RefBuilder(VarDecl *Var, QualType VarType)
13761 : Var(Var), VarType(VarType) {}
13762};
13763
13764class ThisBuilder: public ExprBuilder {
13765public:
13766 Expr *build(Sema &S, SourceLocation Loc) const override {
13767 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
13768 }
13769};
13770
13771class CastBuilder: public ExprBuilder {
13772 const ExprBuilder &Builder;
13773 QualType Type;
13774 ExprValueKind Kind;
13775 const CXXCastPath &Path;
13776
13777public:
13778 Expr *build(Sema &S, SourceLocation Loc) const override {
13779 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
13780 CK_UncheckedDerivedToBase, Kind,
13781 &Path).get());
13782 }
13783
13784 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
13785 const CXXCastPath &Path)
13786 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
13787};
13788
13789class DerefBuilder: public ExprBuilder {
13790 const ExprBuilder &Builder;
13791
13792public:
13793 Expr *build(Sema &S, SourceLocation Loc) const override {
13794 return assertNotNull(
13795 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
13796 }
13797
13798 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13799};
13800
13801class MemberBuilder: public ExprBuilder {
13802 const ExprBuilder &Builder;
13803 QualType Type;
13804 CXXScopeSpec SS;
13805 bool IsArrow;
13806 LookupResult &MemberLookup;
13807
13808public:
13809 Expr *build(Sema &S, SourceLocation Loc) const override {
13810 return assertNotNull(S.BuildMemberReferenceExpr(
13811 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
13812 nullptr, MemberLookup, nullptr, nullptr).get());
13813 }
13814
13815 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
13816 LookupResult &MemberLookup)
13817 : Builder(Builder), Type(Type), IsArrow(IsArrow),
13818 MemberLookup(MemberLookup) {}
13819};
13820
13821class MoveCastBuilder: public ExprBuilder {
13822 const ExprBuilder &Builder;
13823
13824public:
13825 Expr *build(Sema &S, SourceLocation Loc) const override {
13826 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
13827 }
13828
13829 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13830};
13831
13832class LvalueConvBuilder: public ExprBuilder {
13833 const ExprBuilder &Builder;
13834
13835public:
13836 Expr *build(Sema &S, SourceLocation Loc) const override {
13837 return assertNotNull(
13838 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
13839 }
13840
13841 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
13842};
13843
13844class SubscriptBuilder: public ExprBuilder {
13845 const ExprBuilder &Base;
13846 const ExprBuilder &Index;
13847
13848public:
13849 Expr *build(Sema &S, SourceLocation Loc) const override {
13850 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
13851 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
13852 }
13853
13854 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
13855 : Base(Base), Index(Index) {}
13856};
13857
13858} // end anonymous namespace
13859
13860/// When generating a defaulted copy or move assignment operator, if a field
13861/// should be copied with __builtin_memcpy rather than via explicit assignments,
13862/// do so. This optimization only applies for arrays of scalars, and for arrays
13863/// of class type where the selected copy/move-assignment operator is trivial.
13864static StmtResult
13865buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
13866 const ExprBuilder &ToB, const ExprBuilder &FromB) {
13867 // Compute the size of the memory buffer to be copied.
13868 QualType SizeType = S.Context.getSizeType();
13869 llvm::APInt Size(S.Context.getTypeSize(SizeType),
13870 S.Context.getTypeSizeInChars(T).getQuantity());
13871
13872 // Take the address of the field references for "from" and "to". We
13873 // directly construct UnaryOperators here because semantic analysis
13874 // does not permit us to take the address of an xvalue.
13875 Expr *From = FromB.build(S, Loc);
13876 From = UnaryOperator::Create(
13877 S.Context, From, UO_AddrOf, S.Context.getPointerType(From->getType()),
13878 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13879 Expr *To = ToB.build(S, Loc);
13880 To = UnaryOperator::Create(
13881 S.Context, To, UO_AddrOf, S.Context.getPointerType(To->getType()),
13882 VK_PRValue, OK_Ordinary, Loc, false, S.CurFPFeatureOverrides());
13883
13884 const Type *E = T->getBaseElementTypeUnsafe();
13885 bool NeedsCollectableMemCpy =
13886 E->isRecordType() &&
13887 E->castAs<RecordType>()->getDecl()->hasObjectMember();
13888
13889 // Create a reference to the __builtin_objc_memmove_collectable function
13890 StringRef MemCpyName = NeedsCollectableMemCpy ?
13891 "__builtin_objc_memmove_collectable" :
13892 "__builtin_memcpy";
13893 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
13894 Sema::LookupOrdinaryName);
13895 S.LookupName(R, S.TUScope, true);
13896
13897 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
13898 if (!MemCpy)
13899 // Something went horribly wrong earlier, and we will have complained
13900 // about it.
13901 return StmtError();
13902
13903 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
13904 VK_PRValue, Loc, nullptr);
13905 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail")(static_cast<void> (0));
13906
13907 Expr *CallArgs[] = {
13908 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
13909 };
13910 ExprResult Call = S.BuildCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
13911 Loc, CallArgs, Loc);
13912
13913 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!")(static_cast<void> (0));
13914 return Call.getAs<Stmt>();
13915}
13916
13917/// Builds a statement that copies/moves the given entity from \p From to
13918/// \c To.
13919///
13920/// This routine is used to copy/move the members of a class with an
13921/// implicitly-declared copy/move assignment operator. When the entities being
13922/// copied are arrays, this routine builds for loops to copy them.
13923///
13924/// \param S The Sema object used for type-checking.
13925///
13926/// \param Loc The location where the implicit copy/move is being generated.
13927///
13928/// \param T The type of the expressions being copied/moved. Both expressions
13929/// must have this type.
13930///
13931/// \param To The expression we are copying/moving to.
13932///
13933/// \param From The expression we are copying/moving from.
13934///
13935/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
13936/// Otherwise, it's a non-static member subobject.
13937///
13938/// \param Copying Whether we're copying or moving.
13939///
13940/// \param Depth Internal parameter recording the depth of the recursion.
13941///
13942/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
13943/// if a memcpy should be used instead.
13944static StmtResult
13945buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
13946 const ExprBuilder &To, const ExprBuilder &From,
13947 bool CopyingBaseSubobject, bool Copying,
13948 unsigned Depth = 0) {
13949 // C++11 [class.copy]p28:
13950 // Each subobject is assigned in the manner appropriate to its type:
13951 //
13952 // - if the subobject is of class type, as if by a call to operator= with
13953 // the subobject as the object expression and the corresponding
13954 // subobject of x as a single function argument (as if by explicit
13955 // qualification; that is, ignoring any possible virtual overriding
13956 // functions in more derived classes);
13957 //
13958 // C++03 [class.copy]p13:
13959 // - if the subobject is of class type, the copy assignment operator for
13960 // the class is used (as if by explicit qualification; that is,
13961 // ignoring any possible virtual overriding functions in more derived
13962 // classes);
13963 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
13964 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
13965
13966 // Look for operator=.
13967 DeclarationName Name
13968 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
13969 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
13970 S.LookupQualifiedName(OpLookup, ClassDecl, false);
13971
13972 // Prior to C++11, filter out any result that isn't a copy/move-assignment
13973 // operator.
13974 if (!S.getLangOpts().CPlusPlus11) {
13975 LookupResult::Filter F = OpLookup.makeFilter();
13976 while (F.hasNext()) {
13977 NamedDecl *D = F.next();
13978 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
13979 if (Method->isCopyAssignmentOperator() ||
13980 (!Copying && Method->isMoveAssignmentOperator()))
13981 continue;
13982
13983 F.erase();
13984 }
13985 F.done();
13986 }
13987
13988 // Suppress the protected check (C++ [class.protected]) for each of the
13989 // assignment operators we found. This strange dance is required when
13990 // we're assigning via a base classes's copy-assignment operator. To
13991 // ensure that we're getting the right base class subobject (without
13992 // ambiguities), we need to cast "this" to that subobject type; to
13993 // ensure that we don't go through the virtual call mechanism, we need
13994 // to qualify the operator= name with the base class (see below). However,
13995 // this means that if the base class has a protected copy assignment
13996 // operator, the protected member access check will fail. So, we
13997 // rewrite "protected" access to "public" access in this case, since we
13998 // know by construction that we're calling from a derived class.
13999 if (CopyingBaseSubobject) {
14000 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
14001 L != LEnd; ++L) {
14002 if (L.getAccess() == AS_protected)
14003 L.setAccess(AS_public);
14004 }
14005 }
14006
14007 // Create the nested-name-specifier that will be used to qualify the
14008 // reference to operator=; this is required to suppress the virtual
14009 // call mechanism.
14010 CXXScopeSpec SS;
14011 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
14012 SS.MakeTrivial(S.Context,
14013 NestedNameSpecifier::Create(S.Context, nullptr, false,
14014 CanonicalT),
14015 Loc);
14016
14017 // Create the reference to operator=.
14018 ExprResult OpEqualRef
14019 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*IsArrow=*/false,
14020 SS, /*TemplateKWLoc=*/SourceLocation(),
14021 /*FirstQualifierInScope=*/nullptr,
14022 OpLookup,
14023 /*TemplateArgs=*/nullptr, /*S*/nullptr,
14024 /*SuppressQualifierCheck=*/true);
14025 if (OpEqualRef.isInvalid())
14026 return StmtError();
14027
14028 // Build the call to the assignment operator.
14029
14030 Expr *FromInst = From.build(S, Loc);
14031 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
14032 OpEqualRef.getAs<Expr>(),
14033 Loc, FromInst, Loc);
14034 if (Call.isInvalid())
14035 return StmtError();
14036
14037 // If we built a call to a trivial 'operator=' while copying an array,
14038 // bail out. We'll replace the whole shebang with a memcpy.
14039 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
14040 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
14041 return StmtResult((Stmt*)nullptr);
14042
14043 // Convert to an expression-statement, and clean up any produced
14044 // temporaries.
14045 return S.ActOnExprStmt(Call);
14046 }
14047
14048 // - if the subobject is of scalar type, the built-in assignment
14049 // operator is used.
14050 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
14051 if (!ArrayTy) {
14052 ExprResult Assignment = S.CreateBuiltinBinOp(
14053 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
14054 if (Assignment.isInvalid())
14055 return StmtError();
14056 return S.ActOnExprStmt(Assignment);
14057 }
14058
14059 // - if the subobject is an array, each element is assigned, in the
14060 // manner appropriate to the element type;
14061
14062 // Construct a loop over the array bounds, e.g.,
14063 //
14064 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
14065 //
14066 // that will copy each of the array elements.
14067 QualType SizeType = S.Context.getSizeType();
14068
14069 // Create the iteration variable.
14070 IdentifierInfo *IterationVarName = nullptr;
14071 {
14072 SmallString<8> Str;
14073 llvm::raw_svector_ostream OS(Str);
14074 OS << "__i" << Depth;
14075 IterationVarName = &S.Context.Idents.get(OS.str());
14076 }
14077 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
14078 IterationVarName, SizeType,
14079 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
14080 SC_None);
14081
14082 // Initialize the iteration variable to zero.
14083 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
14084 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
14085
14086 // Creates a reference to the iteration variable.
14087 RefBuilder IterationVarRef(IterationVar, SizeType);
14088 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
14089
14090 // Create the DeclStmt that holds the iteration variable.
14091 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
14092
14093 // Subscript the "from" and "to" expressions with the iteration variable.
14094 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
14095 MoveCastBuilder FromIndexMove(FromIndexCopy);
14096 const ExprBuilder *FromIndex;
14097 if (Copying)
14098 FromIndex = &FromIndexCopy;
14099 else
14100 FromIndex = &FromIndexMove;
14101
14102 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
14103
14104 // Build the copy/move for an individual element of the array.
14105 StmtResult Copy =
14106 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
14107 ToIndex, *FromIndex, CopyingBaseSubobject,
14108 Copying, Depth + 1);
14109 // Bail out if copying fails or if we determined that we should use memcpy.
14110 if (Copy.isInvalid() || !Copy.get())
14111 return Copy;
14112
14113 // Create the comparison against the array bound.
14114 llvm::APInt Upper
14115 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
14116 Expr *Comparison = BinaryOperator::Create(
14117 S.Context, IterationVarRefRVal.build(S, Loc),
14118 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc), BO_NE,
14119 S.Context.BoolTy, VK_PRValue, OK_Ordinary, Loc,
14120 S.CurFPFeatureOverrides());
14121
14122 // Create the pre-increment of the iteration variable. We can determine
14123 // whether the increment will overflow based on the value of the array
14124 // bound.
14125 Expr *Increment = UnaryOperator::Create(
14126 S.Context, IterationVarRef.build(S, Loc), UO_PreInc, SizeType, VK_LValue,
14127 OK_Ordinary, Loc, Upper.isMaxValue(), S.CurFPFeatureOverrides());
14128
14129 // Construct the loop that copies all elements of this array.
14130 return S.ActOnForStmt(
14131 Loc, Loc, InitStmt,
14132 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
14133 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
14134}
14135
14136static StmtResult
14137buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
14138 const ExprBuilder &To, const ExprBuilder &From,
14139 bool CopyingBaseSubobject, bool Copying) {
14140 // Maybe we should use a memcpy?
14141 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
14142 T.isTriviallyCopyableType(S.Context))
14143 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14144
14145 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
14146 CopyingBaseSubobject,
14147 Copying, 0));
14148
14149 // If we ended up picking a trivial assignment operator for an array of a
14150 // non-trivially-copyable class type, just emit a memcpy.
14151 if (!Result.isInvalid() && !Result.get())
14152 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
14153
14154 return Result;
14155}
14156
14157CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
14158 // Note: The following rules are largely analoguous to the copy
14159 // constructor rules. Note that virtual bases are not taken into account
14160 // for determining the argument type of the operator. Note also that
14161 // operators taking an object instead of a reference are allowed.
14162 assert(ClassDecl->needsImplicitCopyAssignment())(static_cast<void> (0));
14163
14164 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
14165 if (DSM.isAlreadyBeingDeclared())
14166 return nullptr;
14167
14168 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14169 LangAS AS = getDefaultCXXMethodAddrSpace();
14170 if (AS != LangAS::Default)
14171 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14172 QualType RetType = Context.getLValueReferenceType(ArgType);
14173 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
14174 if (Const)
14175 ArgType = ArgType.withConst();
14176
14177 ArgType = Context.getLValueReferenceType(ArgType);
14178
14179 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14180 CXXCopyAssignment,
14181 Const);
14182
14183 // An implicitly-declared copy assignment operator is an inline public
14184 // member of its class.
14185 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14186 SourceLocation ClassLoc = ClassDecl->getLocation();
14187 DeclarationNameInfo NameInfo(Name, ClassLoc);
14188 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
14189 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14190 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14191 getCurFPFeatures().isFPConstrained(),
14192 /*isInline=*/true,
14193 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14194 SourceLocation());
14195 CopyAssignment->setAccess(AS_public);
14196 CopyAssignment->setDefaulted();
14197 CopyAssignment->setImplicit();
14198
14199 if (getLangOpts().CUDA) {
14200 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
14201 CopyAssignment,
14202 /* ConstRHS */ Const,
14203 /* Diagnose */ false);
14204 }
14205
14206 setupImplicitSpecialMemberType(CopyAssignment, RetType, ArgType);
14207
14208 // Add the parameter to the operator.
14209 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
14210 ClassLoc, ClassLoc,
14211 /*Id=*/nullptr, ArgType,
14212 /*TInfo=*/nullptr, SC_None,
14213 nullptr);
14214 CopyAssignment->setParams(FromParam);
14215
14216 CopyAssignment->setTrivial(
14217 ClassDecl->needsOverloadResolutionForCopyAssignment()
14218 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
14219 : ClassDecl->hasTrivialCopyAssignment());
14220
14221 // Note that we have added this copy-assignment operator.
14222 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
14223
14224 Scope *S = getScopeForContext(ClassDecl);
14225 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
14226
14227 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment)) {
14228 ClassDecl->setImplicitCopyAssignmentIsDeleted();
14229 SetDeclDeleted(CopyAssignment, ClassLoc);
14230 }
14231
14232 if (S)
14233 PushOnScopeChains(CopyAssignment, S, false);
14234 ClassDecl->addDecl(CopyAssignment);
14235
14236 return CopyAssignment;
14237}
14238
14239/// Diagnose an implicit copy operation for a class which is odr-used, but
14240/// which is deprecated because the class has a user-declared copy constructor,
14241/// copy assignment operator, or destructor.
14242static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
14243 assert(CopyOp->isImplicit())(static_cast<void> (0));
14244
14245 CXXRecordDecl *RD = CopyOp->getParent();
14246 CXXMethodDecl *UserDeclaredOperation = nullptr;
14247
14248 // In Microsoft mode, assignment operations don't affect constructors and
14249 // vice versa.
14250 if (RD->hasUserDeclaredDestructor()) {
14251 UserDeclaredOperation = RD->getDestructor();
14252 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
14253 RD->hasUserDeclaredCopyConstructor() &&
14254 !S.getLangOpts().MSVCCompat) {
14255 // Find any user-declared copy constructor.
14256 for (auto *I : RD->ctors()) {
14257 if (I->isCopyConstructor()) {
14258 UserDeclaredOperation = I;
14259 break;
14260 }
14261 }
14262 assert(UserDeclaredOperation)(static_cast<void> (0));
14263 } else if (isa<CXXConstructorDecl>(CopyOp) &&
14264 RD->hasUserDeclaredCopyAssignment() &&
14265 !S.getLangOpts().MSVCCompat) {
14266 // Find any user-declared move assignment operator.
14267 for (auto *I : RD->methods()) {
14268 if (I->isCopyAssignmentOperator()) {
14269 UserDeclaredOperation = I;
14270 break;
14271 }
14272 }
14273 assert(UserDeclaredOperation)(static_cast<void> (0));
14274 }
14275
14276 if (UserDeclaredOperation) {
14277 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
14278 bool UDOIsDestructor = isa<CXXDestructorDecl>(UserDeclaredOperation);
14279 bool IsCopyAssignment = !isa<CXXConstructorDecl>(CopyOp);
14280 unsigned DiagID =
14281 (UDOIsUserProvided && UDOIsDestructor)
14282 ? diag::warn_deprecated_copy_with_user_provided_dtor
14283 : (UDOIsUserProvided && !UDOIsDestructor)
14284 ? diag::warn_deprecated_copy_with_user_provided_copy
14285 : (!UDOIsUserProvided && UDOIsDestructor)
14286 ? diag::warn_deprecated_copy_with_dtor
14287 : diag::warn_deprecated_copy;
14288 S.Diag(UserDeclaredOperation->getLocation(), DiagID)
14289 << RD << IsCopyAssignment;
14290 }
14291}
14292
14293void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
14294 CXXMethodDecl *CopyAssignOperator) {
14295 assert((CopyAssignOperator->isDefaulted() &&(static_cast<void> (0))
14296 CopyAssignOperator->isOverloadedOperator() &&(static_cast<void> (0))
14297 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast<void> (0))
14298 !CopyAssignOperator->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
14299 !CopyAssignOperator->isDeleted()) &&(static_cast<void> (0))
14300 "DefineImplicitCopyAssignment called for wrong function")(static_cast<void> (0));
14301 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
14302 return;
14303
14304 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
14305 if (ClassDecl->isInvalidDecl()) {
14306 CopyAssignOperator->setInvalidDecl();
14307 return;
14308 }
14309
14310 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
14311
14312 // The exception specification is needed because we are defining the
14313 // function.
14314 ResolveExceptionSpec(CurrentLocation,
14315 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
14316
14317 // Add a context note for diagnostics produced after this point.
14318 Scope.addContextNote(CurrentLocation);
14319
14320 // C++11 [class.copy]p18:
14321 // The [definition of an implicitly declared copy assignment operator] is
14322 // deprecated if the class has a user-declared copy constructor or a
14323 // user-declared destructor.
14324 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
14325 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
14326
14327 // C++0x [class.copy]p30:
14328 // The implicitly-defined or explicitly-defaulted copy assignment operator
14329 // for a non-union class X performs memberwise copy assignment of its
14330 // subobjects. The direct base classes of X are assigned first, in the
14331 // order of their declaration in the base-specifier-list, and then the
14332 // immediate non-static data members of X are assigned, in the order in
14333 // which they were declared in the class definition.
14334
14335 // The statements that form the synthesized function body.
14336 SmallVector<Stmt*, 8> Statements;
14337
14338 // The parameter for the "other" object, which we are copying from.
14339 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
14340 Qualifiers OtherQuals = Other->getType().getQualifiers();
14341 QualType OtherRefType = Other->getType();
14342 if (const LValueReferenceType *OtherRef
14343 = OtherRefType->getAs<LValueReferenceType>()) {
14344 OtherRefType = OtherRef->getPointeeType();
14345 OtherQuals = OtherRefType.getQualifiers();
14346 }
14347
14348 // Our location for everything implicitly-generated.
14349 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
14350 ? CopyAssignOperator->getEndLoc()
14351 : CopyAssignOperator->getLocation();
14352
14353 // Builds a DeclRefExpr for the "other" object.
14354 RefBuilder OtherRef(Other, OtherRefType);
14355
14356 // Builds the "this" pointer.
14357 ThisBuilder This;
14358
14359 // Assign base classes.
14360 bool Invalid = false;
14361 for (auto &Base : ClassDecl->bases()) {
14362 // Form the assignment:
14363 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
14364 QualType BaseType = Base.getType().getUnqualifiedType();
14365 if (!BaseType->isRecordType()) {
14366 Invalid = true;
14367 continue;
14368 }
14369
14370 CXXCastPath BasePath;
14371 BasePath.push_back(&Base);
14372
14373 // Construct the "from" expression, which is an implicit cast to the
14374 // appropriately-qualified base type.
14375 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
14376 VK_LValue, BasePath);
14377
14378 // Dereference "this".
14379 DerefBuilder DerefThis(This);
14380 CastBuilder To(DerefThis,
14381 Context.getQualifiedType(
14382 BaseType, CopyAssignOperator->getMethodQualifiers()),
14383 VK_LValue, BasePath);
14384
14385 // Build the copy.
14386 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
14387 To, From,
14388 /*CopyingBaseSubobject=*/true,
14389 /*Copying=*/true);
14390 if (Copy.isInvalid()) {
14391 CopyAssignOperator->setInvalidDecl();
14392 return;
14393 }
14394
14395 // Success! Record the copy.
14396 Statements.push_back(Copy.getAs<Expr>());
14397 }
14398
14399 // Assign non-static members.
14400 for (auto *Field : ClassDecl->fields()) {
14401 // FIXME: We should form some kind of AST representation for the implied
14402 // memcpy in a union copy operation.
14403 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14404 continue;
14405
14406 if (Field->isInvalidDecl()) {
14407 Invalid = true;
14408 continue;
14409 }
14410
14411 // Check for members of reference type; we can't copy those.
14412 if (Field->getType()->isReferenceType()) {
14413 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14414 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14415 Diag(Field->getLocation(), diag::note_declared_at);
14416 Invalid = true;
14417 continue;
14418 }
14419
14420 // Check for members of const-qualified, non-class type.
14421 QualType BaseType = Context.getBaseElementType(Field->getType());
14422 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14423 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14424 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14425 Diag(Field->getLocation(), diag::note_declared_at);
14426 Invalid = true;
14427 continue;
14428 }
14429
14430 // Suppress assigning zero-width bitfields.
14431 if (Field->isZeroLengthBitField(Context))
14432 continue;
14433
14434 QualType FieldType = Field->getType().getNonReferenceType();
14435 if (FieldType->isIncompleteArrayType()) {
14436 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast<void> (0))
14437 "Incomplete array type is not valid")(static_cast<void> (0));
14438 continue;
14439 }
14440
14441 // Build references to the field in the object we're copying from and to.
14442 CXXScopeSpec SS; // Intentionally empty
14443 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14444 LookupMemberName);
14445 MemberLookup.addDecl(Field);
14446 MemberLookup.resolveKind();
14447
14448 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
14449
14450 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
14451
14452 // Build the copy of this field.
14453 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
14454 To, From,
14455 /*CopyingBaseSubobject=*/false,
14456 /*Copying=*/true);
14457 if (Copy.isInvalid()) {
14458 CopyAssignOperator->setInvalidDecl();
14459 return;
14460 }
14461
14462 // Success! Record the copy.
14463 Statements.push_back(Copy.getAs<Stmt>());
14464 }
14465
14466 if (!Invalid) {
14467 // Add a "return *this;"
14468 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14469
14470 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14471 if (Return.isInvalid())
14472 Invalid = true;
14473 else
14474 Statements.push_back(Return.getAs<Stmt>());
14475 }
14476
14477 if (Invalid) {
14478 CopyAssignOperator->setInvalidDecl();
14479 return;
14480 }
14481
14482 StmtResult Body;
14483 {
14484 CompoundScopeRAII CompoundScope(*this);
14485 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14486 /*isStmtExpr=*/false);
14487 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast<void> (0));
14488 }
14489 CopyAssignOperator->setBody(Body.getAs<Stmt>());
14490 CopyAssignOperator->markUsed(Context);
14491
14492 if (ASTMutationListener *L = getASTMutationListener()) {
14493 L->CompletedImplicitDefinition(CopyAssignOperator);
14494 }
14495}
14496
14497CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
14498 assert(ClassDecl->needsImplicitMoveAssignment())(static_cast<void> (0));
14499
14500 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
14501 if (DSM.isAlreadyBeingDeclared())
14502 return nullptr;
14503
14504 // Note: The following rules are largely analoguous to the move
14505 // constructor rules.
14506
14507 QualType ArgType = Context.getTypeDeclType(ClassDecl);
14508 LangAS AS = getDefaultCXXMethodAddrSpace();
14509 if (AS != LangAS::Default)
14510 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14511 QualType RetType = Context.getLValueReferenceType(ArgType);
14512 ArgType = Context.getRValueReferenceType(ArgType);
14513
14514 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14515 CXXMoveAssignment,
14516 false);
14517
14518 // An implicitly-declared move assignment operator is an inline public
14519 // member of its class.
14520 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
14521 SourceLocation ClassLoc = ClassDecl->getLocation();
14522 DeclarationNameInfo NameInfo(Name, ClassLoc);
14523 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
14524 Context, ClassDecl, ClassLoc, NameInfo, QualType(),
14525 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
14526 getCurFPFeatures().isFPConstrained(),
14527 /*isInline=*/true,
14528 Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
14529 SourceLocation());
14530 MoveAssignment->setAccess(AS_public);
14531 MoveAssignment->setDefaulted();
14532 MoveAssignment->setImplicit();
14533
14534 if (getLangOpts().CUDA) {
14535 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
14536 MoveAssignment,
14537 /* ConstRHS */ false,
14538 /* Diagnose */ false);
14539 }
14540
14541 setupImplicitSpecialMemberType(MoveAssignment, RetType, ArgType);
14542
14543 // Add the parameter to the operator.
14544 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
14545 ClassLoc, ClassLoc,
14546 /*Id=*/nullptr, ArgType,
14547 /*TInfo=*/nullptr, SC_None,
14548 nullptr);
14549 MoveAssignment->setParams(FromParam);
14550
14551 MoveAssignment->setTrivial(
14552 ClassDecl->needsOverloadResolutionForMoveAssignment()
14553 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
14554 : ClassDecl->hasTrivialMoveAssignment());
14555
14556 // Note that we have added this copy-assignment operator.
14557 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
14558
14559 Scope *S = getScopeForContext(ClassDecl);
14560 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
14561
14562 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
14563 ClassDecl->setImplicitMoveAssignmentIsDeleted();
14564 SetDeclDeleted(MoveAssignment, ClassLoc);
14565 }
14566
14567 if (S)
14568 PushOnScopeChains(MoveAssignment, S, false);
14569 ClassDecl->addDecl(MoveAssignment);
14570
14571 return MoveAssignment;
14572}
14573
14574/// Check if we're implicitly defining a move assignment operator for a class
14575/// with virtual bases. Such a move assignment might move-assign the virtual
14576/// base multiple times.
14577static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
14578 SourceLocation CurrentLocation) {
14579 assert(!Class->isDependentContext() && "should not define dependent move")(static_cast<void> (0));
14580
14581 // Only a virtual base could get implicitly move-assigned multiple times.
14582 // Only a non-trivial move assignment can observe this. We only want to
14583 // diagnose if we implicitly define an assignment operator that assigns
14584 // two base classes, both of which move-assign the same virtual base.
14585 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
14586 Class->getNumBases() < 2)
14587 return;
14588
14589 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
14590 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
14591 VBaseMap VBases;
14592
14593 for (auto &BI : Class->bases()) {
14594 Worklist.push_back(&BI);
14595 while (!Worklist.empty()) {
14596 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
14597 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
14598
14599 // If the base has no non-trivial move assignment operators,
14600 // we don't care about moves from it.
14601 if (!Base->hasNonTrivialMoveAssignment())
14602 continue;
14603
14604 // If there's nothing virtual here, skip it.
14605 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
14606 continue;
14607
14608 // If we're not actually going to call a move assignment for this base,
14609 // or the selected move assignment is trivial, skip it.
14610 Sema::SpecialMemberOverloadResult SMOR =
14611 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
14612 /*ConstArg*/false, /*VolatileArg*/false,
14613 /*RValueThis*/true, /*ConstThis*/false,
14614 /*VolatileThis*/false);
14615 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
14616 !SMOR.getMethod()->isMoveAssignmentOperator())
14617 continue;
14618
14619 if (BaseSpec->isVirtual()) {
14620 // We're going to move-assign this virtual base, and its move
14621 // assignment operator is not trivial. If this can happen for
14622 // multiple distinct direct bases of Class, diagnose it. (If it
14623 // only happens in one base, we'll diagnose it when synthesizing
14624 // that base class's move assignment operator.)
14625 CXXBaseSpecifier *&Existing =
14626 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
14627 .first->second;
14628 if (Existing && Existing != &BI) {
14629 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
14630 << Class << Base;
14631 S.Diag(Existing->getBeginLoc(), diag::note_vbase_moved_here)
14632 << (Base->getCanonicalDecl() ==
14633 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14634 << Base << Existing->getType() << Existing->getSourceRange();
14635 S.Diag(BI.getBeginLoc(), diag::note_vbase_moved_here)
14636 << (Base->getCanonicalDecl() ==
14637 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
14638 << Base << BI.getType() << BaseSpec->getSourceRange();
14639
14640 // Only diagnose each vbase once.
14641 Existing = nullptr;
14642 }
14643 } else {
14644 // Only walk over bases that have defaulted move assignment operators.
14645 // We assume that any user-provided move assignment operator handles
14646 // the multiple-moves-of-vbase case itself somehow.
14647 if (!SMOR.getMethod()->isDefaulted())
14648 continue;
14649
14650 // We're going to move the base classes of Base. Add them to the list.
14651 for (auto &BI : Base->bases())
14652 Worklist.push_back(&BI);
14653 }
14654 }
14655 }
14656}
14657
14658void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
14659 CXXMethodDecl *MoveAssignOperator) {
14660 assert((MoveAssignOperator->isDefaulted() &&(static_cast<void> (0))
14661 MoveAssignOperator->isOverloadedOperator() &&(static_cast<void> (0))
14662 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&(static_cast<void> (0))
14663 !MoveAssignOperator->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
14664 !MoveAssignOperator->isDeleted()) &&(static_cast<void> (0))
14665 "DefineImplicitMoveAssignment called for wrong function")(static_cast<void> (0));
14666 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
14667 return;
14668
14669 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
14670 if (ClassDecl->isInvalidDecl()) {
14671 MoveAssignOperator->setInvalidDecl();
14672 return;
14673 }
14674
14675 // C++0x [class.copy]p28:
14676 // The implicitly-defined or move assignment operator for a non-union class
14677 // X performs memberwise move assignment of its subobjects. The direct base
14678 // classes of X are assigned first, in the order of their declaration in the
14679 // base-specifier-list, and then the immediate non-static data members of X
14680 // are assigned, in the order in which they were declared in the class
14681 // definition.
14682
14683 // Issue a warning if our implicit move assignment operator will move
14684 // from a virtual base more than once.
14685 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
14686
14687 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
14688
14689 // The exception specification is needed because we are defining the
14690 // function.
14691 ResolveExceptionSpec(CurrentLocation,
14692 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
14693
14694 // Add a context note for diagnostics produced after this point.
14695 Scope.addContextNote(CurrentLocation);
14696
14697 // The statements that form the synthesized function body.
14698 SmallVector<Stmt*, 8> Statements;
14699
14700 // The parameter for the "other" object, which we are move from.
14701 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
14702 QualType OtherRefType =
14703 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
14704
14705 // Our location for everything implicitly-generated.
14706 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
14707 ? MoveAssignOperator->getEndLoc()
14708 : MoveAssignOperator->getLocation();
14709
14710 // Builds a reference to the "other" object.
14711 RefBuilder OtherRef(Other, OtherRefType);
14712 // Cast to rvalue.
14713 MoveCastBuilder MoveOther(OtherRef);
14714
14715 // Builds the "this" pointer.
14716 ThisBuilder This;
14717
14718 // Assign base classes.
14719 bool Invalid = false;
14720 for (auto &Base : ClassDecl->bases()) {
14721 // C++11 [class.copy]p28:
14722 // It is unspecified whether subobjects representing virtual base classes
14723 // are assigned more than once by the implicitly-defined copy assignment
14724 // operator.
14725 // FIXME: Do not assign to a vbase that will be assigned by some other base
14726 // class. For a move-assignment, this can result in the vbase being moved
14727 // multiple times.
14728
14729 // Form the assignment:
14730 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
14731 QualType BaseType = Base.getType().getUnqualifiedType();
14732 if (!BaseType->isRecordType()) {
14733 Invalid = true;
14734 continue;
14735 }
14736
14737 CXXCastPath BasePath;
14738 BasePath.push_back(&Base);
14739
14740 // Construct the "from" expression, which is an implicit cast to the
14741 // appropriately-qualified base type.
14742 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
14743
14744 // Dereference "this".
14745 DerefBuilder DerefThis(This);
14746
14747 // Implicitly cast "this" to the appropriately-qualified base type.
14748 CastBuilder To(DerefThis,
14749 Context.getQualifiedType(
14750 BaseType, MoveAssignOperator->getMethodQualifiers()),
14751 VK_LValue, BasePath);
14752
14753 // Build the move.
14754 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
14755 To, From,
14756 /*CopyingBaseSubobject=*/true,
14757 /*Copying=*/false);
14758 if (Move.isInvalid()) {
14759 MoveAssignOperator->setInvalidDecl();
14760 return;
14761 }
14762
14763 // Success! Record the move.
14764 Statements.push_back(Move.getAs<Expr>());
14765 }
14766
14767 // Assign non-static members.
14768 for (auto *Field : ClassDecl->fields()) {
14769 // FIXME: We should form some kind of AST representation for the implied
14770 // memcpy in a union copy operation.
14771 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
14772 continue;
14773
14774 if (Field->isInvalidDecl()) {
14775 Invalid = true;
14776 continue;
14777 }
14778
14779 // Check for members of reference type; we can't move those.
14780 if (Field->getType()->isReferenceType()) {
14781 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14782 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
14783 Diag(Field->getLocation(), diag::note_declared_at);
14784 Invalid = true;
14785 continue;
14786 }
14787
14788 // Check for members of const-qualified, non-class type.
14789 QualType BaseType = Context.getBaseElementType(Field->getType());
14790 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
14791 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
14792 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
14793 Diag(Field->getLocation(), diag::note_declared_at);
14794 Invalid = true;
14795 continue;
14796 }
14797
14798 // Suppress assigning zero-width bitfields.
14799 if (Field->isZeroLengthBitField(Context))
14800 continue;
14801
14802 QualType FieldType = Field->getType().getNonReferenceType();
14803 if (FieldType->isIncompleteArrayType()) {
14804 assert(ClassDecl->hasFlexibleArrayMember() &&(static_cast<void> (0))
14805 "Incomplete array type is not valid")(static_cast<void> (0));
14806 continue;
14807 }
14808
14809 // Build references to the field in the object we're copying from and to.
14810 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
14811 LookupMemberName);
14812 MemberLookup.addDecl(Field);
14813 MemberLookup.resolveKind();
14814 MemberBuilder From(MoveOther, OtherRefType,
14815 /*IsArrow=*/false, MemberLookup);
14816 MemberBuilder To(This, getCurrentThisType(),
14817 /*IsArrow=*/true, MemberLookup);
14818
14819 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue(static_cast<void> (0))
14820 "Member reference with rvalue base must be rvalue except for reference "(static_cast<void> (0))
14821 "members, which aren't allowed for move assignment.")(static_cast<void> (0));
14822
14823 // Build the move of this field.
14824 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
14825 To, From,
14826 /*CopyingBaseSubobject=*/false,
14827 /*Copying=*/false);
14828 if (Move.isInvalid()) {
14829 MoveAssignOperator->setInvalidDecl();
14830 return;
14831 }
14832
14833 // Success! Record the copy.
14834 Statements.push_back(Move.getAs<Stmt>());
14835 }
14836
14837 if (!Invalid) {
14838 // Add a "return *this;"
14839 ExprResult ThisObj =
14840 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
14841
14842 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
14843 if (Return.isInvalid())
14844 Invalid = true;
14845 else
14846 Statements.push_back(Return.getAs<Stmt>());
14847 }
14848
14849 if (Invalid) {
14850 MoveAssignOperator->setInvalidDecl();
14851 return;
14852 }
14853
14854 StmtResult Body;
14855 {
14856 CompoundScopeRAII CompoundScope(*this);
14857 Body = ActOnCompoundStmt(Loc, Loc, Statements,
14858 /*isStmtExpr=*/false);
14859 assert(!Body.isInvalid() && "Compound statement creation cannot fail")(static_cast<void> (0));
14860 }
14861 MoveAssignOperator->setBody(Body.getAs<Stmt>());
14862 MoveAssignOperator->markUsed(Context);
14863
14864 if (ASTMutationListener *L = getASTMutationListener()) {
14865 L->CompletedImplicitDefinition(MoveAssignOperator);
14866 }
14867}
14868
14869CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
14870 CXXRecordDecl *ClassDecl) {
14871 // C++ [class.copy]p4:
14872 // If the class definition does not explicitly declare a copy
14873 // constructor, one is declared implicitly.
14874 assert(ClassDecl->needsImplicitCopyConstructor())(static_cast<void> (0));
14875
14876 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
14877 if (DSM.isAlreadyBeingDeclared())
14878 return nullptr;
14879
14880 QualType ClassType = Context.getTypeDeclType(ClassDecl);
14881 QualType ArgType = ClassType;
14882 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
14883 if (Const)
14884 ArgType = ArgType.withConst();
14885
14886 LangAS AS = getDefaultCXXMethodAddrSpace();
14887 if (AS != LangAS::Default)
14888 ArgType = Context.getAddrSpaceQualType(ArgType, AS);
14889
14890 ArgType = Context.getLValueReferenceType(ArgType);
14891
14892 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
14893 CXXCopyConstructor,
14894 Const);
14895
14896 DeclarationName Name
14897 = Context.DeclarationNames.getCXXConstructorName(
14898 Context.getCanonicalType(ClassType));
14899 SourceLocation ClassLoc = ClassDecl->getLocation();
14900 DeclarationNameInfo NameInfo(Name, ClassLoc);
14901
14902 // An implicitly-declared copy constructor is an inline public
14903 // member of its class.
14904 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
14905 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
14906 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
14907 /*isInline=*/true,
14908 /*isImplicitlyDeclared=*/true,
14909 Constexpr ? ConstexprSpecKind::Constexpr
14910 : ConstexprSpecKind::Unspecified);
14911 CopyConstructor->setAccess(AS_public);
14912 CopyConstructor->setDefaulted();
14913
14914 if (getLangOpts().CUDA) {
14915 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
14916 CopyConstructor,
14917 /* ConstRHS */ Const,
14918 /* Diagnose */ false);
14919 }
14920
14921 setupImplicitSpecialMemberType(CopyConstructor, Context.VoidTy, ArgType);
14922
14923 // During template instantiation of special member functions we need a
14924 // reliable TypeSourceInfo for the parameter types in order to allow functions
14925 // to be substituted.
14926 TypeSourceInfo *TSI = nullptr;
14927 if (inTemplateInstantiation() && ClassDecl->isLambda())
14928 TSI = Context.getTrivialTypeSourceInfo(ArgType);
14929
14930 // Add the parameter to the constructor.
14931 ParmVarDecl *FromParam =
14932 ParmVarDecl::Create(Context, CopyConstructor, ClassLoc, ClassLoc,
14933 /*IdentifierInfo=*/nullptr, ArgType,
14934 /*TInfo=*/TSI, SC_None, nullptr);
14935 CopyConstructor->setParams(FromParam);
14936
14937 CopyConstructor->setTrivial(
14938 ClassDecl->needsOverloadResolutionForCopyConstructor()
14939 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
14940 : ClassDecl->hasTrivialCopyConstructor());
14941
14942 CopyConstructor->setTrivialForCall(
14943 ClassDecl->hasAttr<TrivialABIAttr>() ||
14944 (ClassDecl->needsOverloadResolutionForCopyConstructor()
14945 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor,
14946 TAH_ConsiderTrivialABI)
14947 : ClassDecl->hasTrivialCopyConstructorForCall()));
14948
14949 // Note that we have declared this constructor.
14950 ++getASTContext().NumImplicitCopyConstructorsDeclared;
14951
14952 Scope *S = getScopeForContext(ClassDecl);
14953 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
14954
14955 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
14956 ClassDecl->setImplicitCopyConstructorIsDeleted();
14957 SetDeclDeleted(CopyConstructor, ClassLoc);
14958 }
14959
14960 if (S)
14961 PushOnScopeChains(CopyConstructor, S, false);
14962 ClassDecl->addDecl(CopyConstructor);
14963
14964 return CopyConstructor;
14965}
14966
14967void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
14968 CXXConstructorDecl *CopyConstructor) {
14969 assert((CopyConstructor->isDefaulted() &&(static_cast<void> (0))
14970 CopyConstructor->isCopyConstructor() &&(static_cast<void> (0))
14971 !CopyConstructor->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
14972 !CopyConstructor->isDeleted()) &&(static_cast<void> (0))
14973 "DefineImplicitCopyConstructor - call it for implicit copy ctor")(static_cast<void> (0));
14974 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
14975 return;
14976
14977 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
14978 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor")(static_cast<void> (0));
14979
14980 SynthesizedFunctionScope Scope(*this, CopyConstructor);
14981
14982 // The exception specification is needed because we are defining the
14983 // function.
14984 ResolveExceptionSpec(CurrentLocation,
14985 CopyConstructor->getType()->castAs<FunctionProtoType>());
14986 MarkVTableUsed(CurrentLocation, ClassDecl);
14987
14988 // Add a context note for diagnostics produced after this point.
14989 Scope.addContextNote(CurrentLocation);
14990
14991 // C++11 [class.copy]p7:
14992 // The [definition of an implicitly declared copy constructor] is
14993 // deprecated if the class has a user-declared copy assignment operator
14994 // or a user-declared destructor.
14995 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
14996 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
14997
14998 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
14999 CopyConstructor->setInvalidDecl();
15000 } else {
15001 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
15002 ? CopyConstructor->getEndLoc()
15003 : CopyConstructor->getLocation();
15004 Sema::CompoundScopeRAII CompoundScope(*this);
15005 CopyConstructor->setBody(
15006 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
15007 CopyConstructor->markUsed(Context);
15008 }
15009
15010 if (ASTMutationListener *L = getASTMutationListener()) {
15011 L->CompletedImplicitDefinition(CopyConstructor);
15012 }
15013}
15014
15015CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
15016 CXXRecordDecl *ClassDecl) {
15017 assert(ClassDecl->needsImplicitMoveConstructor())(static_cast<void> (0));
15018
15019 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
15020 if (DSM.isAlreadyBeingDeclared())
15021 return nullptr;
15022
15023 QualType ClassType = Context.getTypeDeclType(ClassDecl);
15024
15025 QualType ArgType = ClassType;
15026 LangAS AS = getDefaultCXXMethodAddrSpace();
15027 if (AS != LangAS::Default)
15028 ArgType = Context.getAddrSpaceQualType(ClassType, AS);
15029 ArgType = Context.getRValueReferenceType(ArgType);
15030
15031 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
15032 CXXMoveConstructor,
15033 false);
15034
15035 DeclarationName Name
15036 = Context.DeclarationNames.getCXXConstructorName(
15037 Context.getCanonicalType(ClassType));
15038 SourceLocation ClassLoc = ClassDecl->getLocation();
15039 DeclarationNameInfo NameInfo(Name, ClassLoc);
15040
15041 // C++11 [class.copy]p11:
15042 // An implicitly-declared copy/move constructor is an inline public
15043 // member of its class.
15044 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
15045 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
15046 ExplicitSpecifier(), getCurFPFeatures().isFPConstrained(),
15047 /*isInline=*/true,
15048 /*isImplicitlyDeclared=*/true,
15049 Constexpr ? ConstexprSpecKind::Constexpr
15050 : ConstexprSpecKind::Unspecified);
15051 MoveConstructor->setAccess(AS_public);
15052 MoveConstructor->setDefaulted();
15053
15054 if (getLangOpts().CUDA) {
15055 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
15056 MoveConstructor,
15057 /* ConstRHS */ false,
15058 /* Diagnose */ false);
15059 }
15060
15061 setupImplicitSpecialMemberType(MoveConstructor, Context.VoidTy, ArgType);
15062
15063 // Add the parameter to the constructor.
15064 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
15065 ClassLoc, ClassLoc,
15066 /*IdentifierInfo=*/nullptr,
15067 ArgType, /*TInfo=*/nullptr,
15068 SC_None, nullptr);
15069 MoveConstructor->setParams(FromParam);
15070
15071 MoveConstructor->setTrivial(
15072 ClassDecl->needsOverloadResolutionForMoveConstructor()
15073 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
15074 : ClassDecl->hasTrivialMoveConstructor());
15075
15076 MoveConstructor->setTrivialForCall(
15077 ClassDecl->hasAttr<TrivialABIAttr>() ||
15078 (ClassDecl->needsOverloadResolutionForMoveConstructor()
15079 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor,
15080 TAH_ConsiderTrivialABI)
15081 : ClassDecl->hasTrivialMoveConstructorForCall()));
15082
15083 // Note that we have declared this constructor.
15084 ++getASTContext().NumImplicitMoveConstructorsDeclared;
15085
15086 Scope *S = getScopeForContext(ClassDecl);
15087 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
15088
15089 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
15090 ClassDecl->setImplicitMoveConstructorIsDeleted();
15091 SetDeclDeleted(MoveConstructor, ClassLoc);
15092 }
15093
15094 if (S)
15095 PushOnScopeChains(MoveConstructor, S, false);
15096 ClassDecl->addDecl(MoveConstructor);
15097
15098 return MoveConstructor;
15099}
15100
15101void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
15102 CXXConstructorDecl *MoveConstructor) {
15103 assert((MoveConstructor->isDefaulted() &&(static_cast<void> (0))
15104 MoveConstructor->isMoveConstructor() &&(static_cast<void> (0))
15105 !MoveConstructor->doesThisDeclarationHaveABody() &&(static_cast<void> (0))
15106 !MoveConstructor->isDeleted()) &&(static_cast<void> (0))
15107 "DefineImplicitMoveConstructor - call it for implicit move ctor")(static_cast<void> (0));
15108 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
15109 return;
15110
15111 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
15112 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor")(static_cast<void> (0));
15113
15114 SynthesizedFunctionScope Scope(*this, MoveConstructor);
15115
15116 // The exception specification is needed because we are defining the
15117 // function.
15118 ResolveExceptionSpec(CurrentLocation,
15119 MoveConstructor->getType()->castAs<FunctionProtoType>());
15120 MarkVTableUsed(CurrentLocation, ClassDecl);
15121
15122 // Add a context note for diagnostics produced after this point.
15123 Scope.addContextNote(CurrentLocation);
15124
15125 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
15126 MoveConstructor->setInvalidDecl();
15127 } else {
15128 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
15129 ? MoveConstructor->getEndLoc()
15130 : MoveConstructor->getLocation();
15131 Sema::CompoundScopeRAII CompoundScope(*this);
15132 MoveConstructor->setBody(ActOnCompoundStmt(
15133 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
15134 MoveConstructor->markUsed(Context);
15135 }
15136
15137 if (ASTMutationListener *L = getASTMutationListener()) {
15138 L->CompletedImplicitDefinition(MoveConstructor);
15139 }
15140}
15141
15142bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
15143 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
15144}
15145
15146void Sema::DefineImplicitLambdaToFunctionPointerConversion(
15147 SourceLocation CurrentLocation,
15148 CXXConversionDecl *Conv) {
15149 SynthesizedFunctionScope Scope(*this, Conv);
15150 assert(!Conv->getReturnType()->isUndeducedType())(static_cast<void> (0));
15151
15152 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
15153 CallingConv CC =
15154 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
15155
15156 CXXRecordDecl *Lambda = Conv->getParent();
15157 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
15158 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker(CC);
15159
15160 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
15161 CallOp = InstantiateFunctionDeclaration(
15162 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15163 if (!CallOp)
15164 return;
15165
15166 Invoker = InstantiateFunctionDeclaration(
15167 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
15168 if (!Invoker)
15169 return;
15170 }
15171
15172 if (CallOp->isInvalidDecl())
15173 return;
15174
15175 // Mark the call operator referenced (and add to pending instantiations
15176 // if necessary).
15177 // For both the conversion and static-invoker template specializations
15178 // we construct their body's in this function, so no need to add them
15179 // to the PendingInstantiations.
15180 MarkFunctionReferenced(CurrentLocation, CallOp);
15181
15182 // Fill in the __invoke function with a dummy implementation. IR generation
15183 // will fill in the actual details. Update its type in case it contained
15184 // an 'auto'.
15185 Invoker->markUsed(Context);
15186 Invoker->setReferenced();
15187 Invoker->setType(Conv->getReturnType()->getPointeeType());
15188 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
15189
15190 // Construct the body of the conversion function { return __invoke; }.
15191 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
15192 VK_LValue, Conv->getLocation());
15193 assert(FunctionRef && "Can't refer to __invoke function?")(static_cast<void> (0));
15194 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
15195 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
15196 Conv->getLocation()));
15197 Conv->markUsed(Context);
15198 Conv->setReferenced();
15199
15200 if (ASTMutationListener *L = getASTMutationListener()) {
15201 L->CompletedImplicitDefinition(Conv);
15202 L->CompletedImplicitDefinition(Invoker);
15203 }
15204}
15205
15206
15207
15208void Sema::DefineImplicitLambdaToBlockPointerConversion(
15209 SourceLocation CurrentLocation,
15210 CXXConversionDecl *Conv)
15211{
15212 assert(!Conv->getParent()->isGenericLambda())(static_cast<void> (0));
15213
15214 SynthesizedFunctionScope Scope(*this, Conv);
15215
15216 // Copy-initialize the lambda object as needed to capture it.
15217 Expr *This = ActOnCXXThis(CurrentLocation).get();
15218 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
15219
15220 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
15221 Conv->getLocation(),
15222 Conv, DerefThis);
15223
15224 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
15225 // behavior. Note that only the general conversion function does this
15226 // (since it's unusable otherwise); in the case where we inline the
15227 // block literal, it has block literal lifetime semantics.
15228 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
15229 BuildBlock = ImplicitCastExpr::Create(
15230 Context, BuildBlock.get()->getType(), CK_CopyAndAutoreleaseBlockObject,
15231 BuildBlock.get(), nullptr, VK_PRValue, FPOptionsOverride());
15232
15233 if (BuildBlock.isInvalid()) {
15234 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15235 Conv->setInvalidDecl();
15236 return;
15237 }
15238
15239 // Create the return statement that returns the block from the conversion
15240 // function.
15241 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
15242 if (Return.isInvalid()) {
15243 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
15244 Conv->setInvalidDecl();
15245 return;
15246 }
15247
15248 // Set the body of the conversion function.
15249 Stmt *ReturnS = Return.get();
15250 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
15251 Conv->getLocation()));
15252 Conv->markUsed(Context);
15253
15254 // We're done; notify the mutation listener, if any.
15255 if (ASTMutationListener *L = getASTMutationListener()) {
15256 L->CompletedImplicitDefinition(Conv);
15257 }
15258}
15259
15260/// Determine whether the given list arguments contains exactly one
15261/// "real" (non-default) argument.
15262static bool hasOneRealArgument(MultiExprArg Args) {
15263 switch (Args.size()) {
15264 case 0:
15265 return false;
15266
15267 default:
15268 if (!Args[1]->isDefaultArgument())
15269 return false;
15270
15271 LLVM_FALLTHROUGH[[gnu::fallthrough]];
15272 case 1:
15273 return !Args[0]->isDefaultArgument();
15274 }
15275
15276 return false;
15277}
15278
15279ExprResult
15280Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15281 NamedDecl *FoundDecl,
15282 CXXConstructorDecl *Constructor,
15283 MultiExprArg ExprArgs,
15284 bool HadMultipleCandidates,
15285 bool IsListInitialization,
15286 bool IsStdInitListInitialization,
15287 bool RequiresZeroInit,
15288 unsigned ConstructKind,
15289 SourceRange ParenRange) {
15290 bool Elidable = false;
15291
15292 // C++0x [class.copy]p34:
15293 // When certain criteria are met, an implementation is allowed to
15294 // omit the copy/move construction of a class object, even if the
15295 // copy/move constructor and/or destructor for the object have
15296 // side effects. [...]
15297 // - when a temporary class object that has not been bound to a
15298 // reference (12.2) would be copied/moved to a class object
15299 // with the same cv-unqualified type, the copy/move operation
15300 // can be omitted by constructing the temporary object
15301 // directly into the target of the omitted copy/move
15302 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
15303 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
15304 Expr *SubExpr = ExprArgs[0];
15305 Elidable = SubExpr->isTemporaryObject(
15306 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
15307 }
15308
15309 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
15310 FoundDecl, Constructor,
15311 Elidable, ExprArgs, HadMultipleCandidates,
15312 IsListInitialization,
15313 IsStdInitListInitialization, RequiresZeroInit,
15314 ConstructKind, ParenRange);
15315}
15316
15317ExprResult
15318Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15319 NamedDecl *FoundDecl,
15320 CXXConstructorDecl *Constructor,
15321 bool Elidable,
15322 MultiExprArg ExprArgs,
15323 bool HadMultipleCandidates,
15324 bool IsListInitialization,
15325 bool IsStdInitListInitialization,
15326 bool RequiresZeroInit,
15327 unsigned ConstructKind,
15328 SourceRange ParenRange) {
15329 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
15330 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
15331 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
15332 return ExprError();
15333 }
15334
15335 return BuildCXXConstructExpr(
15336 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
15337 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
15338 RequiresZeroInit, ConstructKind, ParenRange);
15339}
15340
15341/// BuildCXXConstructExpr - Creates a complete call to a constructor,
15342/// including handling of its default argument expressions.
15343ExprResult
15344Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
15345 CXXConstructorDecl *Constructor,
15346 bool Elidable,
15347 MultiExprArg ExprArgs,
15348 bool HadMultipleCandidates,
15349 bool IsListInitialization,
15350 bool IsStdInitListInitialization,
15351 bool RequiresZeroInit,
15352 unsigned ConstructKind,
15353 SourceRange ParenRange) {
15354 assert(declaresSameEntity((static_cast<void> (0))
15355 Constructor->getParent(),(static_cast<void> (0))
15356 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&(static_cast<void> (0))
15357 "given constructor for wrong type")(static_cast<void> (0));
15358 MarkFunctionReferenced(ConstructLoc, Constructor);
15359 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
15360 return ExprError();
15361 if (getLangOpts().SYCLIsDevice &&
15362 !checkSYCLDeviceFunction(ConstructLoc, Constructor))
15363 return ExprError();
15364
15365 return CheckForImmediateInvocation(
15366 CXXConstructExpr::Create(
15367 Context, DeclInitType, ConstructLoc, Constructor, Elidable, ExprArgs,
15368 HadMultipleCandidates, IsListInitialization,
15369 IsStdInitListInitialization, RequiresZeroInit,
15370 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
15371 ParenRange),
15372 Constructor);
15373}
15374
15375ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
15376 assert(Field->hasInClassInitializer())(static_cast<void> (0));
15377
15378 // If we already have the in-class initializer nothing needs to be done.
15379 if (Field->getInClassInitializer())
15380 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15381
15382 // If we might have already tried and failed to instantiate, don't try again.
15383 if (Field->isInvalidDecl())
15384 return ExprError();
15385
15386 // Maybe we haven't instantiated the in-class initializer. Go check the
15387 // pattern FieldDecl to see if it has one.
15388 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
15389
15390 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
15391 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
15392 DeclContext::lookup_result Lookup =
15393 ClassPattern->lookup(Field->getDeclName());
15394
15395 FieldDecl *Pattern = nullptr;
15396 for (auto L : Lookup) {
15397 if (isa<FieldDecl>(L)) {
15398 Pattern = cast<FieldDecl>(L);
15399 break;
15400 }
15401 }
15402 assert(Pattern && "We must have set the Pattern!")(static_cast<void> (0));
15403
15404 if (!Pattern->hasInClassInitializer() ||
15405 InstantiateInClassInitializer(Loc, Field, Pattern,
15406 getTemplateInstantiationArgs(Field))) {
15407 // Don't diagnose this again.
15408 Field->setInvalidDecl();
15409 return ExprError();
15410 }
15411 return CXXDefaultInitExpr::Create(Context, Loc, Field, CurContext);
15412 }
15413
15414 // DR1351:
15415 // If the brace-or-equal-initializer of a non-static data member
15416 // invokes a defaulted default constructor of its class or of an
15417 // enclosing class in a potentially evaluated subexpression, the
15418 // program is ill-formed.
15419 //
15420 // This resolution is unworkable: the exception specification of the
15421 // default constructor can be needed in an unevaluated context, in
15422 // particular, in the operand of a noexcept-expression, and we can be
15423 // unable to compute an exception specification for an enclosed class.
15424 //
15425 // Any attempt to resolve the exception specification of a defaulted default
15426 // constructor before the initializer is lexically complete will ultimately
15427 // come here at which point we can diagnose it.
15428 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
15429 Diag(Loc, diag::err_default_member_initializer_not_yet_parsed)
15430 << OutermostClass << Field;
15431 Diag(Field->getEndLoc(),
15432 diag::note_default_member_initializer_not_yet_parsed);
15433 // Recover by marking the field invalid, unless we're in a SFINAE context.
15434 if (!isSFINAEContext())
15435 Field->setInvalidDecl();
15436 return ExprError();
15437}
15438
15439void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
15440 if (VD->isInvalidDecl()) return;
15441 // If initializing the variable failed, don't also diagnose problems with
15442 // the desctructor, they're likely related.
15443 if (VD->getInit() && VD->getInit()->containsErrors())
15444 return;
15445
15446 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
15447 if (ClassDecl->isInvalidDecl()) return;
15448 if (ClassDecl->hasIrrelevantDestructor()) return;
15449 if (ClassDecl->isDependentContext()) return;
15450
15451 if (VD->isNoDestroy(getASTContext()))
15452 return;
15453
15454 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
15455
15456 // If this is an array, we'll require the destructor during initialization, so
15457 // we can skip over this. We still want to emit exit-time destructor warnings
15458 // though.
15459 if (!VD->getType()->isArrayType()) {
15460 MarkFunctionReferenced(VD->getLocation(), Destructor);
15461 CheckDestructorAccess(VD->getLocation(), Destructor,
15462 PDiag(diag::err_access_dtor_var)
15463 << VD->getDeclName() << VD->getType());
15464 DiagnoseUseOfDecl(Destructor, VD->getLocation());
15465 }
15466
15467 if (Destructor->isTrivial()) return;
15468
15469 // If the destructor is constexpr, check whether the variable has constant
15470 // destruction now.
15471 if (Destructor->isConstexpr()) {
15472 bool HasConstantInit = false;
15473 if (VD->getInit() && !VD->getInit()->isValueDependent())
15474 HasConstantInit = VD->evaluateValue();
15475 SmallVector<PartialDiagnosticAt, 8> Notes;
15476 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
15477 HasConstantInit) {
15478 Diag(VD->getLocation(),
15479 diag::err_constexpr_var_requires_const_destruction) << VD;
15480 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
15481 Diag(Notes[I].first, Notes[I].second);
15482 }
15483 }
15484
15485 if (!VD->hasGlobalStorage()) return;
15486
15487 // Emit warning for non-trivial dtor in global scope (a real global,
15488 // class-static, function-static).
15489 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
15490
15491 // TODO: this should be re-enabled for static locals by !CXAAtExit
15492 if (!VD->isStaticLocal())
15493 Diag(VD->getLocation(), diag::warn_global_destructor);
15494}
15495
15496/// Given a constructor and the set of arguments provided for the
15497/// constructor, convert the arguments and add any required default arguments
15498/// to form a proper call to this constructor.
15499///
15500/// \returns true if an error occurred, false otherwise.
15501bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
15502 QualType DeclInitType, MultiExprArg ArgsPtr,
15503 SourceLocation Loc,
15504 SmallVectorImpl<Expr *> &ConvertedArgs,
15505 bool AllowExplicit,
15506 bool IsListInitialization) {
15507 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
15508 unsigned NumArgs = ArgsPtr.size();
15509 Expr **Args = ArgsPtr.data();
15510
15511 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
15512 unsigned NumParams = Proto->getNumParams();
15513
15514 // If too few arguments are available, we'll fill in the rest with defaults.
15515 if (NumArgs < NumParams)
15516 ConvertedArgs.reserve(NumParams);
15517 else
15518 ConvertedArgs.reserve(NumArgs);
15519
15520 VariadicCallType CallType =
15521 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
15522 SmallVector<Expr *, 8> AllArgs;
15523 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
15524 Proto, 0,
15525 llvm::makeArrayRef(Args, NumArgs),
15526 AllArgs,
15527 CallType, AllowExplicit,
15528 IsListInitialization);
15529 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
15530
15531 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
15532
15533 CheckConstructorCall(Constructor, DeclInitType,
15534 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
15535 Proto, Loc);
15536
15537 return Invalid;
15538}
15539
15540static inline bool
15541CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
15542 const FunctionDecl *FnDecl) {
15543 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
15544 if (isa<NamespaceDecl>(DC)) {
15545 return SemaRef.Diag(FnDecl->getLocation(),
15546 diag::err_operator_new_delete_declared_in_namespace)
15547 << FnDecl->getDeclName();
15548 }
15549
15550 if (isa<TranslationUnitDecl>(DC) &&
15551 FnDecl->getStorageClass() == SC_Static) {
15552 return SemaRef.Diag(FnDecl->getLocation(),
15553 diag::err_operator_new_delete_declared_static)
15554 << FnDecl->getDeclName();
15555 }
15556
15557 return false;
15558}
15559
15560static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
15561 const PointerType *PtrTy) {
15562 auto &Ctx = SemaRef.Context;
15563 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
15564 PtrQuals.removeAddressSpace();
15565 return Ctx.getPointerType(Ctx.getCanonicalType(Ctx.getQualifiedType(
15566 PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
15567}
15568
15569static inline bool
15570CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
15571 CanQualType ExpectedResultType,
15572 CanQualType ExpectedFirstParamType,
15573 unsigned DependentParamTypeDiag,
15574 unsigned InvalidParamTypeDiag) {
15575 QualType ResultType =
15576 FnDecl->getType()->castAs<FunctionType>()->getReturnType();
15577
15578 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15579 // The operator is valid on any address space for OpenCL.
15580 // Drop address space from actual and expected result types.
15581 if (const auto *PtrTy = ResultType->getAs<PointerType>())
15582 ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15583
15584 if (auto ExpectedPtrTy = ExpectedResultType->getAs<PointerType>())
15585 ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15586 }
15587
15588 // Check that the result type is what we expect.
15589 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType) {
15590 // Reject even if the type is dependent; an operator delete function is
15591 // required to have a non-dependent result type.
15592 return SemaRef.Diag(
15593 FnDecl->getLocation(),
15594 ResultType->isDependentType()
15595 ? diag::err_operator_new_delete_dependent_result_type
15596 : diag::err_operator_new_delete_invalid_result_type)
15597 << FnDecl->getDeclName() << ExpectedResultType;
15598 }
15599
15600 // A function template must have at least 2 parameters.
15601 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
15602 return SemaRef.Diag(FnDecl->getLocation(),
15603 diag::err_operator_new_delete_template_too_few_parameters)
15604 << FnDecl->getDeclName();
15605
15606 // The function decl must have at least 1 parameter.
15607 if (FnDecl->getNumParams() == 0)
15608 return SemaRef.Diag(FnDecl->getLocation(),
15609 diag::err_operator_new_delete_too_few_parameters)
15610 << FnDecl->getDeclName();
15611
15612 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
15613 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
15614 // The operator is valid on any address space for OpenCL.
15615 // Drop address space from actual and expected first parameter types.
15616 if (const auto *PtrTy =
15617 FnDecl->getParamDecl(0)->getType()->getAs<PointerType>())
15618 FirstParamType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
15619
15620 if (auto ExpectedPtrTy = ExpectedFirstParamType->getAs<PointerType>())
15621 ExpectedFirstParamType =
15622 RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
15623 }
15624
15625 // Check that the first parameter type is what we expect.
15626 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
15627 ExpectedFirstParamType) {
15628 // The first parameter type is not allowed to be dependent. As a tentative
15629 // DR resolution, we allow a dependent parameter type if it is the right
15630 // type anyway, to allow destroying operator delete in class templates.
15631 return SemaRef.Diag(FnDecl->getLocation(), FirstParamType->isDependentType()
15632 ? DependentParamTypeDiag
15633 : InvalidParamTypeDiag)
15634 << FnDecl->getDeclName() << ExpectedFirstParamType;
15635 }
15636
15637 return false;
15638}
15639
15640static bool
15641CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
15642 // C++ [basic.stc.dynamic.allocation]p1:
15643 // A program is ill-formed if an allocation function is declared in a
15644 // namespace scope other than global scope or declared static in global
15645 // scope.
15646 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15647 return true;
15648
15649 CanQualType SizeTy =
15650 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
15651
15652 // C++ [basic.stc.dynamic.allocation]p1:
15653 // The return type shall be void*. The first parameter shall have type
15654 // std::size_t.
15655 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
15656 SizeTy,
15657 diag::err_operator_new_dependent_param_type,
15658 diag::err_operator_new_param_type))
15659 return true;
15660
15661 // C++ [basic.stc.dynamic.allocation]p1:
15662 // The first parameter shall not have an associated default argument.
15663 if (FnDecl->getParamDecl(0)->hasDefaultArg())
15664 return SemaRef.Diag(FnDecl->getLocation(),
15665 diag::err_operator_new_default_arg)
15666 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
15667
15668 return false;
15669}
15670
15671static bool
15672CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
15673 // C++ [basic.stc.dynamic.deallocation]p1:
15674 // A program is ill-formed if deallocation functions are declared in a
15675 // namespace scope other than global scope or declared static in global
15676 // scope.
15677 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
15678 return true;
15679
15680 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
15681
15682 // C++ P0722:
15683 // Within a class C, the first parameter of a destroying operator delete
15684 // shall be of type C *. The first parameter of any other deallocation
15685 // function shall be of type void *.
15686 CanQualType ExpectedFirstParamType =
15687 MD && MD->isDestroyingOperatorDelete()
15688 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
15689 SemaRef.Context.getRecordType(MD->getParent())))
15690 : SemaRef.Context.VoidPtrTy;
15691
15692 // C++ [basic.stc.dynamic.deallocation]p2:
15693 // Each deallocation function shall return void
15694 if (CheckOperatorNewDeleteTypes(
15695 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
15696 diag::err_operator_delete_dependent_param_type,
15697 diag::err_operator_delete_param_type))
15698 return true;
15699
15700 // C++ P0722:
15701 // A destroying operator delete shall be a usual deallocation function.
15702 if (MD && !MD->getParent()->isDependentContext() &&
15703 MD->isDestroyingOperatorDelete() &&
15704 !SemaRef.isUsualDeallocationFunction(MD)) {
15705 SemaRef.Diag(MD->getLocation(),
15706 diag::err_destroying_operator_delete_not_usual);
15707 return true;
15708 }
15709
15710 return false;
15711}
15712
15713/// CheckOverloadedOperatorDeclaration - Check whether the declaration
15714/// of this overloaded operator is well-formed. If so, returns false;
15715/// otherwise, emits appropriate diagnostics and returns true.
15716bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
15717 assert(FnDecl && FnDecl->isOverloadedOperator() &&(static_cast<void> (0))
15718 "Expected an overloaded operator declaration")(static_cast<void> (0));
15719
15720 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
15721
15722 // C++ [over.oper]p5:
15723 // The allocation and deallocation functions, operator new,
15724 // operator new[], operator delete and operator delete[], are
15725 // described completely in 3.7.3. The attributes and restrictions
15726 // found in the rest of this subclause do not apply to them unless
15727 // explicitly stated in 3.7.3.
15728 if (Op == OO_Delete || Op == OO_Array_Delete)
15729 return CheckOperatorDeleteDeclaration(*this, FnDecl);
15730
15731 if (Op == OO_New || Op == OO_Array_New)
15732 return CheckOperatorNewDeclaration(*this, FnDecl);
15733
15734 // C++ [over.oper]p6:
15735 // An operator function shall either be a non-static member
15736 // function or be a non-member function and have at least one
15737 // parameter whose type is a class, a reference to a class, an
15738 // enumeration, or a reference to an enumeration.
15739 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
15740 if (MethodDecl->isStatic())
15741 return Diag(FnDecl->getLocation(),
15742 diag::err_operator_overload_static) << FnDecl->getDeclName();
15743 } else {
15744 bool ClassOrEnumParam = false;
15745 for (auto Param : FnDecl->parameters()) {
15746 QualType ParamType = Param->getType().getNonReferenceType();
15747 if (ParamType->isDependentType() || ParamType->isRecordType() ||
15748 ParamType->isEnumeralType()) {
15749 ClassOrEnumParam = true;
15750 break;
15751 }
15752 }
15753
15754 if (!ClassOrEnumParam)
15755 return Diag(FnDecl->getLocation(),
15756 diag::err_operator_overload_needs_class_or_enum)
15757 << FnDecl->getDeclName();
15758 }
15759
15760 // C++ [over.oper]p8:
15761 // An operator function cannot have default arguments (8.3.6),
15762 // except where explicitly stated below.
15763 //
15764 // Only the function-call operator allows default arguments
15765 // (C++ [over.call]p1).
15766 if (Op != OO_Call) {
15767 for (auto Param : FnDecl->parameters()) {
15768 if (Param->hasDefaultArg())
15769 return Diag(Param->getLocation(),
15770 diag::err_operator_overload_default_arg)
15771 << FnDecl->getDeclName() << Param->getDefaultArgRange();
15772 }
15773 }
15774
15775 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
15776 { false, false, false }
15777#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
15778 , { Unary, Binary, MemberOnly }
15779#include "clang/Basic/OperatorKinds.def"
15780 };
15781
15782 bool CanBeUnaryOperator = OperatorUses[Op][0];
15783 bool CanBeBinaryOperator = OperatorUses[Op][1];
15784 bool MustBeMemberOperator = OperatorUses[Op][2];
15785
15786 // C++ [over.oper]p8:
15787 // [...] Operator functions cannot have more or fewer parameters
15788 // than the number required for the corresponding operator, as
15789 // described in the rest of this subclause.
15790 unsigned NumParams = FnDecl->getNumParams()
15791 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
15792 if (Op != OO_Call &&
15793 ((NumParams == 1 && !CanBeUnaryOperator) ||
15794 (NumParams == 2 && !CanBeBinaryOperator) ||
15795 (NumParams < 1) || (NumParams > 2))) {
15796 // We have the wrong number of parameters.
15797 unsigned ErrorKind;
15798 if (CanBeUnaryOperator && CanBeBinaryOperator) {
15799 ErrorKind = 2; // 2 -> unary or binary.
15800 } else if (CanBeUnaryOperator) {
15801 ErrorKind = 0; // 0 -> unary
15802 } else {
15803 assert(CanBeBinaryOperator &&(static_cast<void> (0))
15804 "All non-call overloaded operators are unary or binary!")(static_cast<void> (0));
15805 ErrorKind = 1; // 1 -> binary
15806 }
15807
15808 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
15809 << FnDecl->getDeclName() << NumParams << ErrorKind;
15810 }
15811
15812 // Overloaded operators other than operator() cannot be variadic.
15813 if (Op != OO_Call &&
15814 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
15815 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
15816 << FnDecl->getDeclName();
15817 }
15818
15819 // Some operators must be non-static member functions.
15820 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
15821 return Diag(FnDecl->getLocation(),
15822 diag::err_operator_overload_must_be_member)
15823 << FnDecl->getDeclName();
15824 }
15825
15826 // C++ [over.inc]p1:
15827 // The user-defined function called operator++ implements the
15828 // prefix and postfix ++ operator. If this function is a member
15829 // function with no parameters, or a non-member function with one
15830 // parameter of class or enumeration type, it defines the prefix
15831 // increment operator ++ for objects of that type. If the function
15832 // is a member function with one parameter (which shall be of type
15833 // int) or a non-member function with two parameters (the second
15834 // of which shall be of type int), it defines the postfix
15835 // increment operator ++ for objects of that type.
15836 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
15837 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
15838 QualType ParamType = LastParam->getType();
15839
15840 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
15841 !ParamType->isDependentType())
15842 return Diag(LastParam->getLocation(),
15843 diag::err_operator_overload_post_incdec_must_be_int)
15844 << LastParam->getType() << (Op == OO_MinusMinus);
15845 }
15846
15847 return false;
15848}
15849
15850static bool
15851checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
15852 FunctionTemplateDecl *TpDecl) {
15853 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
15854
15855 // Must have one or two template parameters.
15856 if (TemplateParams->size() == 1) {
15857 NonTypeTemplateParmDecl *PmDecl =
15858 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
15859
15860 // The template parameter must be a char parameter pack.
15861 if (PmDecl && PmDecl->isTemplateParameterPack() &&
15862 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
15863 return false;
15864
15865 // C++20 [over.literal]p5:
15866 // A string literal operator template is a literal operator template
15867 // whose template-parameter-list comprises a single non-type
15868 // template-parameter of class type.
15869 //
15870 // As a DR resolution, we also allow placeholders for deduced class
15871 // template specializations.
15872 if (SemaRef.getLangOpts().CPlusPlus20 &&
15873 !PmDecl->isTemplateParameterPack() &&
15874 (PmDecl->getType()->isRecordType() ||
15875 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
15876 return false;
15877 } else if (TemplateParams->size() == 2) {
15878 TemplateTypeParmDecl *PmType =
15879 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
15880 NonTypeTemplateParmDecl *PmArgs =
15881 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
15882
15883 // The second template parameter must be a parameter pack with the
15884 // first template parameter as its type.
15885 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
15886 PmArgs->isTemplateParameterPack()) {
15887 const TemplateTypeParmType *TArgs =
15888 PmArgs->getType()->getAs<TemplateTypeParmType>();
15889 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
15890 TArgs->getIndex() == PmType->getIndex()) {
15891 if (!SemaRef.inTemplateInstantiation())
15892 SemaRef.Diag(TpDecl->getLocation(),
15893 diag::ext_string_literal_operator_template);
15894 return false;
15895 }
15896 }
15897 }
15898
15899 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
15900 diag::err_literal_operator_template)
15901 << TpDecl->getTemplateParameters()->getSourceRange();
15902 return true;
15903}
15904
15905/// CheckLiteralOperatorDeclaration - Check whether the declaration
15906/// of this literal operator function is well-formed. If so, returns
15907/// false; otherwise, emits appropriate diagnostics and returns true.
15908bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
15909 if (isa<CXXMethodDecl>(FnDecl)) {
15910 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
15911 << FnDecl->getDeclName();
15912 return true;
15913 }
15914
15915 if (FnDecl->isExternC()) {
15916 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
15917 if (const LinkageSpecDecl *LSD =
15918 FnDecl->getDeclContext()->getExternCContext())
15919 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
15920 return true;
15921 }
15922
15923 // This might be the definition of a literal operator template.
15924 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
15925
15926 // This might be a specialization of a literal operator template.
15927 if (!TpDecl)
15928 TpDecl = FnDecl->getPrimaryTemplate();
15929
15930 // template <char...> type operator "" name() and
15931 // template <class T, T...> type operator "" name() are the only valid
15932 // template signatures, and the only valid signatures with no parameters.
15933 //
15934 // C++20 also allows template <SomeClass T> type operator "" name().
15935 if (TpDecl) {
15936 if (FnDecl->param_size() != 0) {
15937 Diag(FnDecl->getLocation(),
15938 diag::err_literal_operator_template_with_params);
15939 return true;
15940 }
15941
15942 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
15943 return true;
15944
15945 } else if (FnDecl->param_size() == 1) {
15946 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
15947
15948 QualType ParamType = Param->getType().getUnqualifiedType();
15949
15950 // Only unsigned long long int, long double, any character type, and const
15951 // char * are allowed as the only parameters.
15952 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
15953 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
15954 Context.hasSameType(ParamType, Context.CharTy) ||
15955 Context.hasSameType(ParamType, Context.WideCharTy) ||
15956 Context.hasSameType(ParamType, Context.Char8Ty) ||
15957 Context.hasSameType(ParamType, Context.Char16Ty) ||
15958 Context.hasSameType(ParamType, Context.Char32Ty)) {
15959 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
15960 QualType InnerType = Ptr->getPointeeType();
15961
15962 // Pointer parameter must be a const char *.
15963 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
15964 Context.CharTy) &&
15965 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
15966 Diag(Param->getSourceRange().getBegin(),
15967 diag::err_literal_operator_param)
15968 << ParamType << "'const char *'" << Param->getSourceRange();
15969 return true;
15970 }
15971
15972 } else if (ParamType->isRealFloatingType()) {
15973 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15974 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
15975 return true;
15976
15977 } else if (ParamType->isIntegerType()) {
15978 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
15979 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
15980 return true;
15981
15982 } else {
15983 Diag(Param->getSourceRange().getBegin(),
15984 diag::err_literal_operator_invalid_param)
15985 << ParamType << Param->getSourceRange();
15986 return true;
15987 }
15988
15989 } else if (FnDecl->param_size() == 2) {
15990 FunctionDecl::param_iterator Param = FnDecl->param_begin();
15991
15992 // First, verify that the first parameter is correct.
15993
15994 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
15995
15996 // Two parameter function must have a pointer to const as a
15997 // first parameter; let's strip those qualifiers.
15998 const PointerType *PT = FirstParamType->getAs<PointerType>();
15999
16000 if (!PT) {
16001 Diag((*Param)->getSourceRange().getBegin(),
16002 diag::err_literal_operator_param)
16003 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16004 return true;
16005 }
16006
16007 QualType PointeeType = PT->getPointeeType();
16008 // First parameter must be const
16009 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
16010 Diag((*Param)->getSourceRange().getBegin(),
16011 diag::err_literal_operator_param)
16012 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16013 return true;
16014 }
16015
16016 QualType InnerType = PointeeType.getUnqualifiedType();
16017 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
16018 // const char32_t* are allowed as the first parameter to a two-parameter
16019 // function
16020 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
16021 Context.hasSameType(InnerType, Context.WideCharTy) ||
16022 Context.hasSameType(InnerType, Context.Char8Ty) ||
16023 Context.hasSameType(InnerType, Context.Char16Ty) ||
16024 Context.hasSameType(InnerType, Context.Char32Ty))) {
16025 Diag((*Param)->getSourceRange().getBegin(),
16026 diag::err_literal_operator_param)
16027 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
16028 return true;
16029 }
16030
16031 // Move on to the second and final parameter.
16032 ++Param;
16033
16034 // The second parameter must be a std::size_t.
16035 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
16036 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
16037 Diag((*Param)->getSourceRange().getBegin(),
16038 diag::err_literal_operator_param)
16039 << SecondParamType << Context.getSizeType()
16040 << (*Param)->getSourceRange();
16041 return true;
16042 }
16043 } else {
16044 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
16045 return true;
16046 }
16047
16048 // Parameters are good.
16049
16050 // A parameter-declaration-clause containing a default argument is not
16051 // equivalent to any of the permitted forms.
16052 for (auto Param : FnDecl->parameters()) {
16053 if (Param->hasDefaultArg()) {
16054 Diag(Param->getDefaultArgRange().getBegin(),
16055 diag::err_literal_operator_default_argument)
16056 << Param->getDefaultArgRange();
16057 break;
16058 }
16059 }
16060
16061 StringRef LiteralName
16062 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
16063 if (LiteralName[0] != '_' &&
16064 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
16065 // C++11 [usrlit.suffix]p1:
16066 // Literal suffix identifiers that do not start with an underscore
16067 // are reserved for future standardization.
16068 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
16069 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
16070 }
16071
16072 return false;
16073}
16074
16075/// ActOnStartLinkageSpecification - Parsed the beginning of a C++
16076/// linkage specification, including the language and (if present)
16077/// the '{'. ExternLoc is the location of the 'extern', Lang is the
16078/// language string literal. LBraceLoc, if valid, provides the location of
16079/// the '{' brace. Otherwise, this linkage specification does not
16080/// have any braces.
16081Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
16082 Expr *LangStr,
16083 SourceLocation LBraceLoc) {
16084 StringLiteral *Lit = cast<StringLiteral>(LangStr);
16085 if (!Lit->isAscii()) {
16086 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
16087 << LangStr->getSourceRange();
16088 return nullptr;
16089 }
16090
16091 StringRef Lang = Lit->getString();
16092 LinkageSpecDecl::LanguageIDs Language;
16093 if (Lang == "C")
16094 Language = LinkageSpecDecl::lang_c;
16095 else if (Lang == "C++")
16096 Language = LinkageSpecDecl::lang_cxx;
16097 else {
16098 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
16099 << LangStr->getSourceRange();
16100 return nullptr;
16101 }
16102
16103 // FIXME: Add all the various semantics of linkage specifications
16104
16105 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
16106 LangStr->getExprLoc(), Language,
16107 LBraceLoc.isValid());
16108 CurContext->addDecl(D);
16109 PushDeclContext(S, D);
16110 return D;
16111}
16112
16113/// ActOnFinishLinkageSpecification - Complete the definition of
16114/// the C++ linkage specification LinkageSpec. If RBraceLoc is
16115/// valid, it's the position of the closing '}' brace in a linkage
16116/// specification that uses braces.
16117Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
16118 Decl *LinkageSpec,
16119 SourceLocation RBraceLoc) {
16120 if (RBraceLoc.isValid()) {
16121 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
16122 LSDecl->setRBraceLoc(RBraceLoc);
16123 }
16124 PopDeclContext();
16125 return LinkageSpec;
16126}
16127
16128Decl *Sema::ActOnEmptyDeclaration(Scope *S,
16129 const ParsedAttributesView &AttrList,
16130 SourceLocation SemiLoc) {
16131 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
16132 // Attribute declarations appertain to empty declaration so we handle
16133 // them here.
16134 ProcessDeclAttributeList(S, ED, AttrList);
16135
16136 CurContext->addDecl(ED);
16137 return ED;
16138}
16139
16140/// Perform semantic analysis for the variable declaration that
16141/// occurs within a C++ catch clause, returning the newly-created
16142/// variable.
16143VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
16144 TypeSourceInfo *TInfo,
16145 SourceLocation StartLoc,
16146 SourceLocation Loc,
16147 IdentifierInfo *Name) {
16148 bool Invalid = false;
16149 QualType ExDeclType = TInfo->getType();
16150
16151 // Arrays and functions decay.
16152 if (ExDeclType->isArrayType())
16153 ExDeclType = Context.getArrayDecayedType(ExDeclType);
16154 else if (ExDeclType->isFunctionType())
16155 ExDeclType = Context.getPointerType(ExDeclType);
16156
16157 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
16158 // The exception-declaration shall not denote a pointer or reference to an
16159 // incomplete type, other than [cv] void*.
16160 // N2844 forbids rvalue references.
16161 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
16162 Diag(Loc, diag::err_catch_rvalue_ref);
16163 Invalid = true;
16164 }
16165
16166 if (ExDeclType->isVariablyModifiedType()) {
16167 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
16168 Invalid = true;
16169 }
16170
16171 QualType BaseType = ExDeclType;
16172 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
16173 unsigned DK = diag::err_catch_incomplete;
16174 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
16175 BaseType = Ptr->getPointeeType();
16176 Mode = 1;
16177 DK = diag::err_catch_incomplete_ptr;
16178 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
16179 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
16180 BaseType = Ref->getPointeeType();
16181 Mode = 2;
16182 DK = diag::err_catch_incomplete_ref;
16183 }
16184 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
16185 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
16186 Invalid = true;
16187
16188 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
16189 Diag(Loc, diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
16190 Invalid = true;
16191 }
16192
16193 if (!Invalid && !ExDeclType->isDependentType() &&
16194 RequireNonAbstractType(Loc, ExDeclType,
16195 diag::err_abstract_type_in_decl,
16196 AbstractVariableType))
16197 Invalid = true;
16198
16199 // Only the non-fragile NeXT runtime currently supports C++ catches
16200 // of ObjC types, and no runtime supports catching ObjC types by value.
16201 if (!Invalid && getLangOpts().ObjC) {
16202 QualType T = ExDeclType;
16203 if (const ReferenceType *RT = T->getAs<ReferenceType>())
16204 T = RT->getPointeeType();
16205
16206 if (T->isObjCObjectType()) {
16207 Diag(Loc, diag::err_objc_object_catch);
16208 Invalid = true;
16209 } else if (T->isObjCObjectPointerType()) {
16210 // FIXME: should this be a test for macosx-fragile specifically?
16211 if (getLangOpts().ObjCRuntime.isFragile())
16212 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
16213 }
16214 }
16215
16216 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
16217 ExDeclType, TInfo, SC_None);
16218 ExDecl->setExceptionVariable(true);
16219
16220 // In ARC, infer 'retaining' for variables of retainable type.
16221 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
16222 Invalid = true;
16223
16224 if (!Invalid && !ExDeclType->isDependentType()) {
16225 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
16226 // Insulate this from anything else we might currently be parsing.
16227 EnterExpressionEvaluationContext scope(
16228 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
16229
16230 // C++ [except.handle]p16:
16231 // The object declared in an exception-declaration or, if the
16232 // exception-declaration does not specify a name, a temporary (12.2) is
16233 // copy-initialized (8.5) from the exception object. [...]
16234 // The object is destroyed when the handler exits, after the destruction
16235 // of any automatic objects initialized within the handler.
16236 //
16237 // We just pretend to initialize the object with itself, then make sure
16238 // it can be destroyed later.
16239 QualType initType = Context.getExceptionObjectType(ExDeclType);
16240
16241 InitializedEntity entity =
16242 InitializedEntity::InitializeVariable(ExDecl);
16243 InitializationKind initKind =
16244 InitializationKind::CreateCopy(Loc, SourceLocation());
16245
16246 Expr *opaqueValue =
16247 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
16248 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
16249 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
16250 if (result.isInvalid())
16251 Invalid = true;
16252 else {
16253 // If the constructor used was non-trivial, set this as the
16254 // "initializer".
16255 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
16256 if (!construct->getConstructor()->isTrivial()) {
16257 Expr *init = MaybeCreateExprWithCleanups(construct);
16258 ExDecl->setInit(init);
16259 }
16260
16261 // And make sure it's destructable.
16262 FinalizeVarWithDestructor(ExDecl, recordType);
16263 }
16264 }
16265 }
16266
16267 if (Invalid)
16268 ExDecl->setInvalidDecl();
16269
16270 return ExDecl;
16271}
16272
16273/// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
16274/// handler.
16275Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
16276 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16277 bool Invalid = D.isInvalidType();
16278
16279 // Check for unexpanded parameter packs.
16280 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
16281 UPPC_ExceptionType)) {
16282 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
16283 D.getIdentifierLoc());
16284 Invalid = true;
16285 }
16286
16287 IdentifierInfo *II = D.getIdentifier();
16288 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
16289 LookupOrdinaryName,
16290 ForVisibleRedeclaration)) {
16291 // The scope should be freshly made just for us. There is just no way
16292 // it contains any previous declaration, except for function parameters in
16293 // a function-try-block's catch statement.
16294 assert(!S->isDeclScope(PrevDecl))(static_cast<void> (0));
16295 if (isDeclInScope(PrevDecl, CurContext, S)) {
16296 Diag(D.getIdentifierLoc(), diag::err_redefinition)
16297 << D.getIdentifier();
16298 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
16299 Invalid = true;
16300 } else if (PrevDecl->isTemplateParameter())
16301 // Maybe we will complain about the shadowed template parameter.
16302 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
16303 }
16304
16305 if (D.getCXXScopeSpec().isSet() && !Invalid) {
16306 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
16307 << D.getCXXScopeSpec().getRange();
16308 Invalid = true;
16309 }
16310
16311 VarDecl *ExDecl = BuildExceptionDeclaration(
16312 S, TInfo, D.getBeginLoc(), D.getIdentifierLoc(), D.getIdentifier());
16313 if (Invalid)
16314 ExDecl->setInvalidDecl();
16315
16316 // Add the exception declaration into this scope.
16317 if (II)
16318 PushOnScopeChains(ExDecl, S);
16319 else
16320 CurContext->addDecl(ExDecl);
16321
16322 ProcessDeclAttributes(S, ExDecl, D);
16323 return ExDecl;
16324}
16325
16326Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16327 Expr *AssertExpr,
16328 Expr *AssertMessageExpr,
16329 SourceLocation RParenLoc) {
16330 StringLiteral *AssertMessage =
16331 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
16332
16333 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
16334 return nullptr;
16335
16336 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
16337 AssertMessage, RParenLoc, false);
16338}
16339
16340Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
16341 Expr *AssertExpr,
16342 StringLiteral *AssertMessage,
16343 SourceLocation RParenLoc,
16344 bool Failed) {
16345 assert(AssertExpr != nullptr && "Expected non-null condition")(static_cast<void> (0));
16346 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
16347 !Failed) {
16348 // In a static_assert-declaration, the constant-expression shall be a
16349 // constant expression that can be contextually converted to bool.
16350 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
16351 if (Converted.isInvalid())
16352 Failed = true;
16353
16354 ExprResult FullAssertExpr =
16355 ActOnFinishFullExpr(Converted.get(), StaticAssertLoc,
16356 /*DiscardedValue*/ false,
16357 /*IsConstexpr*/ true);
16358 if (FullAssertExpr.isInvalid())
16359 Failed = true;
16360 else
16361 AssertExpr = FullAssertExpr.get();
16362
16363 llvm::APSInt Cond;
16364 if (!Failed && VerifyIntegerConstantExpression(
16365 AssertExpr, &Cond,
16366 diag::err_static_assert_expression_is_not_constant)
16367 .isInvalid())
16368 Failed = true;
16369
16370 if (!Failed && !Cond) {
16371 SmallString<256> MsgBuffer;
16372 llvm::raw_svector_ostream Msg(MsgBuffer);
16373 if (AssertMessage)
16374 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
16375
16376 Expr *InnerCond = nullptr;
16377 std::string InnerCondDescription;
16378 std::tie(InnerCond, InnerCondDescription) =
16379 findFailedBooleanCondition(Converted.get());
16380 if (InnerCond && isa<ConceptSpecializationExpr>(InnerCond)) {
16381 // Drill down into concept specialization expressions to see why they
16382 // weren't satisfied.
16383 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16384 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16385 ConstraintSatisfaction Satisfaction;
16386 if (!CheckConstraintSatisfaction(InnerCond, Satisfaction))
16387 DiagnoseUnsatisfiedConstraint(Satisfaction);
16388 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(InnerCond)
16389 && !isa<IntegerLiteral>(InnerCond)) {
16390 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
16391 << InnerCondDescription << !AssertMessage
16392 << Msg.str() << InnerCond->getSourceRange();
16393 } else {
16394 Diag(StaticAssertLoc, diag::err_static_assert_failed)
16395 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
16396 }
16397 Failed = true;
16398 }
16399 } else {
16400 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
16401 /*DiscardedValue*/false,
16402 /*IsConstexpr*/true);
16403 if (FullAssertExpr.isInvalid())
16404 Failed = true;
16405 else
16406 AssertExpr = FullAssertExpr.get();
16407 }
16408
16409 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
16410 AssertExpr, AssertMessage, RParenLoc,
16411 Failed);
16412
16413 CurContext->addDecl(Decl);
16414 return Decl;
16415}
16416
16417/// Perform semantic analysis of the given friend type declaration.
16418///
16419/// \returns A friend declaration that.
16420FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
16421 SourceLocation FriendLoc,
16422 TypeSourceInfo *TSInfo) {
16423 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration")(static_cast<void> (0));
16424
16425 QualType T = TSInfo->getType();
16426 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
16427
16428 // C++03 [class.friend]p2:
16429 // An elaborated-type-specifier shall be used in a friend declaration
16430 // for a class.*
16431 //
16432 // * The class-key of the elaborated-type-specifier is required.
16433 if (!CodeSynthesisContexts.empty()) {
16434 // Do not complain about the form of friend template types during any kind
16435 // of code synthesis. For template instantiation, we will have complained
16436 // when the template was defined.
16437 } else {
16438 if (!T->isElaboratedTypeSpecifier()) {
16439 // If we evaluated the type to a record type, suggest putting
16440 // a tag in front.
16441 if (const RecordType *RT = T->getAs<RecordType>()) {
16442 RecordDecl *RD = RT->getDecl();
16443
16444 SmallString<16> InsertionText(" ");
16445 InsertionText += RD->getKindName();
16446
16447 Diag(TypeRange.getBegin(),
16448 getLangOpts().CPlusPlus11 ?
16449 diag::warn_cxx98_compat_unelaborated_friend_type :
16450 diag::ext_unelaborated_friend_type)
16451 << (unsigned) RD->getTagKind()
16452 << T
16453 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
16454 InsertionText);
16455 } else {
16456 Diag(FriendLoc,
16457 getLangOpts().CPlusPlus11 ?
16458 diag::warn_cxx98_compat_nonclass_type_friend :
16459 diag::ext_nonclass_type_friend)
16460 << T
16461 << TypeRange;
16462 }
16463 } else if (T->getAs<EnumType>()) {
16464 Diag(FriendLoc,
16465 getLangOpts().CPlusPlus11 ?
16466 diag::warn_cxx98_compat_enum_friend :
16467 diag::ext_enum_friend)
16468 << T
16469 << TypeRange;
16470 }
16471
16472 // C++11 [class.friend]p3:
16473 // A friend declaration that does not declare a function shall have one
16474 // of the following forms:
16475 // friend elaborated-type-specifier ;
16476 // friend simple-type-specifier ;
16477 // friend typename-specifier ;
16478 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
16479 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
16480 }
16481
16482 // If the type specifier in a friend declaration designates a (possibly
16483 // cv-qualified) class type, that class is declared as a friend; otherwise,
16484 // the friend declaration is ignored.
16485 return FriendDecl::Create(Context, CurContext,
16486 TSInfo->getTypeLoc().getBeginLoc(), TSInfo,
16487 FriendLoc);
16488}
16489
16490/// Handle a friend tag declaration where the scope specifier was
16491/// templated.
16492Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
16493 unsigned TagSpec, SourceLocation TagLoc,
16494 CXXScopeSpec &SS, IdentifierInfo *Name,
16495 SourceLocation NameLoc,
16496 const ParsedAttributesView &Attr,
16497 MultiTemplateParamsArg TempParamLists) {
16498 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
16499
16500 bool IsMemberSpecialization = false;
16501 bool Invalid = false;
16502
16503 if (TemplateParameterList *TemplateParams =
16504 MatchTemplateParametersToScopeSpecifier(
16505 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
16506 IsMemberSpecialization, Invalid)) {
16507 if (TemplateParams->size() > 0) {
16508 // This is a declaration of a class template.
16509 if (Invalid)
16510 return nullptr;
16511
16512 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
16513 NameLoc, Attr, TemplateParams, AS_public,
16514 /*ModulePrivateLoc=*/SourceLocation(),
16515 FriendLoc, TempParamLists.size() - 1,
16516 TempParamLists.data()).get();
16517 } else {
16518 // The "template<>" header is extraneous.
16519 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
16520 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
16521 IsMemberSpecialization = true;
16522 }
16523 }
16524
16525 if (Invalid) return nullptr;
16526
16527 bool isAllExplicitSpecializations = true;
16528 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
16529 if (TempParamLists[I]->size()) {
16530 isAllExplicitSpecializations = false;
16531 break;
16532 }
16533 }
16534
16535 // FIXME: don't ignore attributes.
16536
16537 // If it's explicit specializations all the way down, just forget
16538 // about the template header and build an appropriate non-templated
16539 // friend. TODO: for source fidelity, remember the headers.
16540 if (isAllExplicitSpecializations) {
16541 if (SS.isEmpty()) {
16542 bool Owned = false;
16543 bool IsDependent = false;
16544 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
16545 Attr, AS_public,
16546 /*ModulePrivateLoc=*/SourceLocation(),
16547 MultiTemplateParamsArg(), Owned, IsDependent,
16548 /*ScopedEnumKWLoc=*/SourceLocation(),
16549 /*ScopedEnumUsesClassTag=*/false,
16550 /*UnderlyingType=*/TypeResult(),
16551 /*IsTypeSpecifier=*/false,
16552 /*IsTemplateParamOrArg=*/false);
16553 }
16554
16555 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
16556 ElaboratedTypeKeyword Keyword
16557 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16558 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
16559 *Name, NameLoc);
16560 if (T.isNull())
16561 return nullptr;
16562
16563 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16564 if (isa<DependentNameType>(T)) {
16565 DependentNameTypeLoc TL =
16566 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16567 TL.setElaboratedKeywordLoc(TagLoc);
16568 TL.setQualifierLoc(QualifierLoc);
16569 TL.setNameLoc(NameLoc);
16570 } else {
16571 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
16572 TL.setElaboratedKeywordLoc(TagLoc);
16573 TL.setQualifierLoc(QualifierLoc);
16574 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
16575 }
16576
16577 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16578 TSI, FriendLoc, TempParamLists);
16579 Friend->setAccess(AS_public);
16580 CurContext->addDecl(Friend);
16581 return Friend;
16582 }
16583
16584 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?")(static_cast<void> (0));
16585
16586
16587
16588 // Handle the case of a templated-scope friend class. e.g.
16589 // template <class T> class A<T>::B;
16590 // FIXME: we don't support these right now.
16591 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
16592 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
16593 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
16594 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
16595 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
16596 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
16597 TL.setElaboratedKeywordLoc(TagLoc);
16598 TL.setQualifierLoc(SS.getWithLocInContext(Context));
16599 TL.setNameLoc(NameLoc);
16600
16601 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
16602 TSI, FriendLoc, TempParamLists);
16603 Friend->setAccess(AS_public);
16604 Friend->setUnsupportedFriend(true);
16605 CurContext->addDecl(Friend);
16606 return Friend;
16607}
16608
16609/// Handle a friend type declaration. This works in tandem with
16610/// ActOnTag.
16611///
16612/// Notes on friend class templates:
16613///
16614/// We generally treat friend class declarations as if they were
16615/// declaring a class. So, for example, the elaborated type specifier
16616/// in a friend declaration is required to obey the restrictions of a
16617/// class-head (i.e. no typedefs in the scope chain), template
16618/// parameters are required to match up with simple template-ids, &c.
16619/// However, unlike when declaring a template specialization, it's
16620/// okay to refer to a template specialization without an empty
16621/// template parameter declaration, e.g.
16622/// friend class A<T>::B<unsigned>;
16623/// We permit this as a special case; if there are any template
16624/// parameters present at all, require proper matching, i.e.
16625/// template <> template \<class T> friend class A<int>::B;
16626Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
16627 MultiTemplateParamsArg TempParams) {
16628 SourceLocation Loc = DS.getBeginLoc();
16629
16630 assert(DS.isFriendSpecified())(static_cast<void> (0));
16631 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast<void> (0));
16632
16633 // C++ [class.friend]p3:
16634 // A friend declaration that does not declare a function shall have one of
16635 // the following forms:
16636 // friend elaborated-type-specifier ;
16637 // friend simple-type-specifier ;
16638 // friend typename-specifier ;
16639 //
16640 // Any declaration with a type qualifier does not have that form. (It's
16641 // legal to specify a qualified type as a friend, you just can't write the
16642 // keywords.)
16643 if (DS.getTypeQualifiers()) {
16644 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
16645 Diag(DS.getConstSpecLoc(), diag::err_friend_decl_spec) << "const";
16646 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
16647 Diag(DS.getVolatileSpecLoc(), diag::err_friend_decl_spec) << "volatile";
16648 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
16649 Diag(DS.getRestrictSpecLoc(), diag::err_friend_decl_spec) << "restrict";
16650 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
16651 Diag(DS.getAtomicSpecLoc(), diag::err_friend_decl_spec) << "_Atomic";
16652 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
16653 Diag(DS.getUnalignedSpecLoc(), diag::err_friend_decl_spec) << "__unaligned";
16654 }
16655
16656 // Try to convert the decl specifier to a type. This works for
16657 // friend templates because ActOnTag never produces a ClassTemplateDecl
16658 // for a TUK_Friend.
16659 Declarator TheDeclarator(DS, DeclaratorContext::Member);
16660 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
16661 QualType T = TSI->getType();
16662 if (TheDeclarator.isInvalidType())
16663 return nullptr;
16664
16665 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
16666 return nullptr;
16667
16668 // This is definitely an error in C++98. It's probably meant to
16669 // be forbidden in C++0x, too, but the specification is just
16670 // poorly written.
16671 //
16672 // The problem is with declarations like the following:
16673 // template <T> friend A<T>::foo;
16674 // where deciding whether a class C is a friend or not now hinges
16675 // on whether there exists an instantiation of A that causes
16676 // 'foo' to equal C. There are restrictions on class-heads
16677 // (which we declare (by fiat) elaborated friend declarations to
16678 // be) that makes this tractable.
16679 //
16680 // FIXME: handle "template <> friend class A<T>;", which
16681 // is possibly well-formed? Who even knows?
16682 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
16683 Diag(Loc, diag::err_tagless_friend_type_template)
16684 << DS.getSourceRange();
16685 return nullptr;
16686 }
16687
16688 // C++98 [class.friend]p1: A friend of a class is a function
16689 // or class that is not a member of the class . . .
16690 // This is fixed in DR77, which just barely didn't make the C++03
16691 // deadline. It's also a very silly restriction that seriously
16692 // affects inner classes and which nobody else seems to implement;
16693 // thus we never diagnose it, not even in -pedantic.
16694 //
16695 // But note that we could warn about it: it's always useless to
16696 // friend one of your own members (it's not, however, worthless to
16697 // friend a member of an arbitrary specialization of your template).
16698
16699 Decl *D;
16700 if (!TempParams.empty())
16701 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
16702 TempParams,
16703 TSI,
16704 DS.getFriendSpecLoc());
16705 else
16706 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
16707
16708 if (!D)
16709 return nullptr;
16710
16711 D->setAccess(AS_public);
16712 CurContext->addDecl(D);
16713
16714 return D;
16715}
16716
16717NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
16718 MultiTemplateParamsArg TemplateParams) {
16719 const DeclSpec &DS = D.getDeclSpec();
16720
16721 assert(DS.isFriendSpecified())(static_cast<void> (0));
16722 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified)(static_cast<void> (0));
16723
16724 SourceLocation Loc = D.getIdentifierLoc();
16725 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16726
16727 // C++ [class.friend]p1
16728 // A friend of a class is a function or class....
16729 // Note that this sees through typedefs, which is intended.
16730 // It *doesn't* see through dependent types, which is correct
16731 // according to [temp.arg.type]p3:
16732 // If a declaration acquires a function type through a
16733 // type dependent on a template-parameter and this causes
16734 // a declaration that does not use the syntactic form of a
16735 // function declarator to have a function type, the program
16736 // is ill-formed.
16737 if (!TInfo->getType()->isFunctionType()) {
16738 Diag(Loc, diag::err_unexpected_friend);
16739
16740 // It might be worthwhile to try to recover by creating an
16741 // appropriate declaration.
16742 return nullptr;
16743 }
16744
16745 // C++ [namespace.memdef]p3
16746 // - If a friend declaration in a non-local class first declares a
16747 // class or function, the friend class or function is a member
16748 // of the innermost enclosing namespace.
16749 // - The name of the friend is not found by simple name lookup
16750 // until a matching declaration is provided in that namespace
16751 // scope (either before or after the class declaration granting
16752 // friendship).
16753 // - If a friend function is called, its name may be found by the
16754 // name lookup that considers functions from namespaces and
16755 // classes associated with the types of the function arguments.
16756 // - When looking for a prior declaration of a class or a function
16757 // declared as a friend, scopes outside the innermost enclosing
16758 // namespace scope are not considered.
16759
16760 CXXScopeSpec &SS = D.getCXXScopeSpec();
16761 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
16762 assert(NameInfo.getName())(static_cast<void> (0));
16763
16764 // Check for unexpanded parameter packs.
16765 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
16766 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
16767 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
16768 return nullptr;
16769
16770 // The context we found the declaration in, or in which we should
16771 // create the declaration.
16772 DeclContext *DC;
16773 Scope *DCScope = S;
16774 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
16775 ForExternalRedeclaration);
16776
16777 // There are five cases here.
16778 // - There's no scope specifier and we're in a local class. Only look
16779 // for functions declared in the immediately-enclosing block scope.
16780 // We recover from invalid scope qualifiers as if they just weren't there.
16781 FunctionDecl *FunctionContainingLocalClass = nullptr;
16782 if ((SS.isInvalid() || !SS.isSet()) &&
16783 (FunctionContainingLocalClass =
16784 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
16785 // C++11 [class.friend]p11:
16786 // If a friend declaration appears in a local class and the name
16787 // specified is an unqualified name, a prior declaration is
16788 // looked up without considering scopes that are outside the
16789 // innermost enclosing non-class scope. For a friend function
16790 // declaration, if there is no prior declaration, the program is
16791 // ill-formed.
16792
16793 // Find the innermost enclosing non-class scope. This is the block
16794 // scope containing the local class definition (or for a nested class,
16795 // the outer local class).
16796 DCScope = S->getFnParent();
16797
16798 // Look up the function name in the scope.
16799 Previous.clear(LookupLocalFriendName);
16800 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
16801
16802 if (!Previous.empty()) {
16803 // All possible previous declarations must have the same context:
16804 // either they were declared at block scope or they are members of
16805 // one of the enclosing local classes.
16806 DC = Previous.getRepresentativeDecl()->getDeclContext();
16807 } else {
16808 // This is ill-formed, but provide the context that we would have
16809 // declared the function in, if we were permitted to, for error recovery.
16810 DC = FunctionContainingLocalClass;
16811 }
16812 adjustContextForLocalExternDecl(DC);
16813
16814 // C++ [class.friend]p6:
16815 // A function can be defined in a friend declaration of a class if and
16816 // only if the class is a non-local class (9.8), the function name is
16817 // unqualified, and the function has namespace scope.
16818 if (D.isFunctionDefinition()) {
16819 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
16820 }
16821
16822 // - There's no scope specifier, in which case we just go to the
16823 // appropriate scope and look for a function or function template
16824 // there as appropriate.
16825 } else if (SS.isInvalid() || !SS.isSet()) {
16826 // C++11 [namespace.memdef]p3:
16827 // If the name in a friend declaration is neither qualified nor
16828 // a template-id and the declaration is a function or an
16829 // elaborated-type-specifier, the lookup to determine whether
16830 // the entity has been previously declared shall not consider
16831 // any scopes outside the innermost enclosing namespace.
16832 bool isTemplateId =
16833 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
16834
16835 // Find the appropriate context according to the above.
16836 DC = CurContext;
16837
16838 // Skip class contexts. If someone can cite chapter and verse
16839 // for this behavior, that would be nice --- it's what GCC and
16840 // EDG do, and it seems like a reasonable intent, but the spec
16841 // really only says that checks for unqualified existing
16842 // declarations should stop at the nearest enclosing namespace,
16843 // not that they should only consider the nearest enclosing
16844 // namespace.
16845 while (DC->isRecord())
16846 DC = DC->getParent();
16847
16848 DeclContext *LookupDC = DC->getNonTransparentContext();
16849 while (true) {
16850 LookupQualifiedName(Previous, LookupDC);
16851
16852 if (!Previous.empty()) {
16853 DC = LookupDC;
16854 break;
16855 }
16856
16857 if (isTemplateId) {
16858 if (isa<TranslationUnitDecl>(LookupDC)) break;
16859 } else {
16860 if (LookupDC->isFileContext()) break;
16861 }
16862 LookupDC = LookupDC->getParent();
16863 }
16864
16865 DCScope = getScopeForDeclContext(S, DC);
16866
16867 // - There's a non-dependent scope specifier, in which case we
16868 // compute it and do a previous lookup there for a function
16869 // or function template.
16870 } else if (!SS.getScopeRep()->isDependent()) {
16871 DC = computeDeclContext(SS);
16872 if (!DC) return nullptr;
16873
16874 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
16875
16876 LookupQualifiedName(Previous, DC);
16877
16878 // C++ [class.friend]p1: A friend of a class is a function or
16879 // class that is not a member of the class . . .
16880 if (DC->Equals(CurContext))
16881 Diag(DS.getFriendSpecLoc(),
16882 getLangOpts().CPlusPlus11 ?
16883 diag::warn_cxx98_compat_friend_is_member :
16884 diag::err_friend_is_member);
16885
16886 if (D.isFunctionDefinition()) {
16887 // C++ [class.friend]p6:
16888 // A function can be defined in a friend declaration of a class if and
16889 // only if the class is a non-local class (9.8), the function name is
16890 // unqualified, and the function has namespace scope.
16891 //
16892 // FIXME: We should only do this if the scope specifier names the
16893 // innermost enclosing namespace; otherwise the fixit changes the
16894 // meaning of the code.
16895 SemaDiagnosticBuilder DB
16896 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
16897
16898 DB << SS.getScopeRep();
16899 if (DC->isFileContext())
16900 DB << FixItHint::CreateRemoval(SS.getRange());
16901 SS.clear();
16902 }
16903
16904 // - There's a scope specifier that does not match any template
16905 // parameter lists, in which case we use some arbitrary context,
16906 // create a method or method template, and wait for instantiation.
16907 // - There's a scope specifier that does match some template
16908 // parameter lists, which we don't handle right now.
16909 } else {
16910 if (D.isFunctionDefinition()) {
16911 // C++ [class.friend]p6:
16912 // A function can be defined in a friend declaration of a class if and
16913 // only if the class is a non-local class (9.8), the function name is
16914 // unqualified, and the function has namespace scope.
16915 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
16916 << SS.getScopeRep();
16917 }
16918
16919 DC = CurContext;
16920 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?")(static_cast<void> (0));
16921 }
16922
16923 if (!DC->isRecord()) {
16924 int DiagArg = -1;
16925 switch (D.getName().getKind()) {
16926 case UnqualifiedIdKind::IK_ConstructorTemplateId:
16927 case UnqualifiedIdKind::IK_ConstructorName:
16928 DiagArg = 0;
16929 break;
16930 case UnqualifiedIdKind::IK_DestructorName:
16931 DiagArg = 1;
16932 break;
16933 case UnqualifiedIdKind::IK_ConversionFunctionId:
16934 DiagArg = 2;
16935 break;
16936 case UnqualifiedIdKind::IK_DeductionGuideName:
16937 DiagArg = 3;
16938 break;
16939 case UnqualifiedIdKind::IK_Identifier:
16940 case UnqualifiedIdKind::IK_ImplicitSelfParam:
16941 case UnqualifiedIdKind::IK_LiteralOperatorId:
16942 case UnqualifiedIdKind::IK_OperatorFunctionId:
16943 case UnqualifiedIdKind::IK_TemplateId:
16944 break;
16945 }
16946 // This implies that it has to be an operator or function.
16947 if (DiagArg >= 0) {
16948 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
16949 return nullptr;
16950 }
16951 }
16952
16953 // FIXME: This is an egregious hack to cope with cases where the scope stack
16954 // does not contain the declaration context, i.e., in an out-of-line
16955 // definition of a class.
16956 Scope FakeDCScope(S, Scope::DeclScope, Diags);
16957 if (!DCScope) {
16958 FakeDCScope.setEntity(DC);
16959 DCScope = &FakeDCScope;
16960 }
16961
16962 bool AddToScope = true;
16963 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
16964 TemplateParams, AddToScope);
16965 if (!ND) return nullptr;
16966
16967 assert(ND->getLexicalDeclContext() == CurContext)(static_cast<void> (0));
16968
16969 // If we performed typo correction, we might have added a scope specifier
16970 // and changed the decl context.
16971 DC = ND->getDeclContext();
16972
16973 // Add the function declaration to the appropriate lookup tables,
16974 // adjusting the redeclarations list as necessary. We don't
16975 // want to do this yet if the friending class is dependent.
16976 //
16977 // Also update the scope-based lookup if the target context's
16978 // lookup context is in lexical scope.
16979 if (!CurContext->isDependentContext()) {
16980 DC = DC->getRedeclContext();
16981 DC->makeDeclVisibleInContext(ND);
16982 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16983 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
16984 }
16985
16986 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
16987 D.getIdentifierLoc(), ND,
16988 DS.getFriendSpecLoc());
16989 FrD->setAccess(AS_public);
16990 CurContext->addDecl(FrD);
16991
16992 if (ND->isInvalidDecl()) {
16993 FrD->setInvalidDecl();
16994 } else {
16995 if (DC->isRecord()) CheckFriendAccess(ND);
16996
16997 FunctionDecl *FD;
16998 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
16999 FD = FTD->getTemplatedDecl();
17000 else
17001 FD = cast<FunctionDecl>(ND);
17002
17003 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
17004 // default argument expression, that declaration shall be a definition
17005 // and shall be the only declaration of the function or function
17006 // template in the translation unit.
17007 if (functionDeclHasDefaultArgument(FD)) {
17008 // We can't look at FD->getPreviousDecl() because it may not have been set
17009 // if we're in a dependent context. If the function is known to be a
17010 // redeclaration, we will have narrowed Previous down to the right decl.
17011 if (D.isRedeclaration()) {
17012 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
17013 Diag(Previous.getRepresentativeDecl()->getLocation(),
17014 diag::note_previous_declaration);
17015 } else if (!D.isFunctionDefinition())
17016 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
17017 }
17018
17019 // Mark templated-scope function declarations as unsupported.
17020 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
17021 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
17022 << SS.getScopeRep() << SS.getRange()
17023 << cast<CXXRecordDecl>(CurContext);
17024 FrD->setUnsupportedFriend(true);
17025 }
17026 }
17027
17028 warnOnReservedIdentifier(ND);
17029
17030 return ND;
17031}
17032
17033void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
17034 AdjustDeclIfTemplate(Dcl);
17035
17036 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
17037 if (!Fn) {
17038 Diag(DelLoc, diag::err_deleted_non_function);
17039 return;
17040 }
17041
17042 // Deleted function does not have a body.
17043 Fn->setWillHaveBody(false);
17044
17045 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
17046 // Don't consider the implicit declaration we generate for explicit
17047 // specializations. FIXME: Do not generate these implicit declarations.
17048 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
17049 Prev->getPreviousDecl()) &&
17050 !Prev->isDefined()) {
17051 Diag(DelLoc, diag::err_deleted_decl_not_first);
17052 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
17053 Prev->isImplicit() ? diag::note_previous_implicit_declaration
17054 : diag::note_previous_declaration);
17055 // We can't recover from this; the declaration might have already
17056 // been used.
17057 Fn->setInvalidDecl();
17058 return;
17059 }
17060
17061 // To maintain the invariant that functions are only deleted on their first
17062 // declaration, mark the implicitly-instantiated declaration of the
17063 // explicitly-specialized function as deleted instead of marking the
17064 // instantiated redeclaration.
17065 Fn = Fn->getCanonicalDecl();
17066 }
17067
17068 // dllimport/dllexport cannot be deleted.
17069 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
17070 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
17071 Fn->setInvalidDecl();
17072 }
17073
17074 // C++11 [basic.start.main]p3:
17075 // A program that defines main as deleted [...] is ill-formed.
17076 if (Fn->isMain())
17077 Diag(DelLoc, diag::err_deleted_main);
17078
17079 // C++11 [dcl.fct.def.delete]p4:
17080 // A deleted function is implicitly inline.
17081 Fn->setImplicitlyInline();
17082 Fn->setDeletedAsWritten();
17083}
17084
17085void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
17086 if (!Dcl || Dcl->isInvalidDecl())
17087 return;
17088
17089 auto *FD = dyn_cast<FunctionDecl>(Dcl);
17090 if (!FD) {
17091 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Dcl)) {
17092 if (getDefaultedFunctionKind(FTD->getTemplatedDecl()).isComparison()) {
17093 Diag(DefaultLoc, diag::err_defaulted_comparison_template);
17094 return;
17095 }
17096 }
17097
17098 Diag(DefaultLoc, diag::err_default_special_members)
17099 << getLangOpts().CPlusPlus20;
17100 return;
17101 }
17102
17103 // Reject if this can't possibly be a defaultable function.
17104 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
17105 if (!DefKind &&
17106 // A dependent function that doesn't locally look defaultable can
17107 // still instantiate to a defaultable function if it's a constructor
17108 // or assignment operator.
17109 (!FD->isDependentContext() ||
17110 (!isa<CXXConstructorDecl>(FD) &&
17111 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
17112 Diag(DefaultLoc, diag::err_default_special_members)
17113 << getLangOpts().CPlusPlus20;
17114 return;
17115 }
17116
17117 if (DefKind.isComparison() &&
17118 !isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
17119 Diag(FD->getLocation(), diag::err_defaulted_comparison_out_of_class)
17120 << (int)DefKind.asComparison();
17121 return;
17122 }
17123
17124 // Issue compatibility warning. We already warned if the operator is
17125 // 'operator<=>' when parsing the '<=>' token.
17126 if (DefKind.isComparison() &&
17127 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
17128 Diag(DefaultLoc, getLangOpts().CPlusPlus20
17129 ? diag::warn_cxx17_compat_defaulted_comparison
17130 : diag::ext_defaulted_comparison);
17131 }
17132
17133 FD->setDefaulted();
17134 FD->setExplicitlyDefaulted();
17135
17136 // Defer checking functions that are defaulted in a dependent context.
17137 if (FD->isDependentContext())
17138 return;
17139
17140 // Unset that we will have a body for this function. We might not,
17141 // if it turns out to be trivial, and we don't need this marking now
17142 // that we've marked it as defaulted.
17143 FD->setWillHaveBody(false);
17144
17145 // If this definition appears within the record, do the checking when
17146 // the record is complete. This is always the case for a defaulted
17147 // comparison.
17148 if (DefKind.isComparison())
17149 return;
17150 auto *MD = cast<CXXMethodDecl>(FD);
17151
17152 const FunctionDecl *Primary = FD;
17153 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
17154 // Ask the template instantiation pattern that actually had the
17155 // '= default' on it.
17156 Primary = Pattern;
17157
17158 // If the method was defaulted on its first declaration, we will have
17159 // already performed the checking in CheckCompletedCXXClass. Such a
17160 // declaration doesn't trigger an implicit definition.
17161 if (Primary->getCanonicalDecl()->isDefaulted())
17162 return;
17163
17164 // FIXME: Once we support defining comparisons out of class, check for a
17165 // defaulted comparison here.
17166 if (CheckExplicitlyDefaultedSpecialMember(MD, DefKind.asSpecialMember()))
17167 MD->setInvalidDecl();
17168 else
17169 DefineDefaultedFunction(*this, MD, DefaultLoc);
17170}
17171
17172static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
17173 for (Stmt *SubStmt : S->children()) {
17174 if (!SubStmt)
17175 continue;
17176 if (isa<ReturnStmt>(SubStmt))
17177 Self.Diag(SubStmt->getBeginLoc(),
17178 diag::err_return_in_constructor_handler);
17179 if (!isa<Expr>(SubStmt))
17180 SearchForReturnInStmt(Self, SubStmt);
17181 }
17182}
17183
17184void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
17185 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
17186 CXXCatchStmt *Handler = TryBlock->getHandler(I);
17187 SearchForReturnInStmt(*this, Handler);
17188 }
17189}
17190
17191bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
17192 const CXXMethodDecl *Old) {
17193 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
17194 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
17195
17196 if (OldFT->hasExtParameterInfos()) {
17197 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
17198 // A parameter of the overriding method should be annotated with noescape
17199 // if the corresponding parameter of the overridden method is annotated.
17200 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
17201 !NewFT->getExtParameterInfo(I).isNoEscape()) {
17202 Diag(New->getParamDecl(I)->getLocation(),
17203 diag::warn_overriding_method_missing_noescape);
17204 Diag(Old->getParamDecl(I)->getLocation(),
17205 diag::note_overridden_marked_noescape);
17206 }
17207 }
17208
17209 // Virtual overrides must have the same code_seg.
17210 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
17211 const auto *NewCSA = New->getAttr<CodeSegAttr>();
17212 if ((NewCSA || OldCSA) &&
17213 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
17214 Diag(New->getLocation(), diag::err_mismatched_code_seg_override);
17215 Diag(Old->getLocation(), diag::note_previous_declaration);
17216 return true;
17217 }
17218
17219 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
17220
17221 // If the calling conventions match, everything is fine
17222 if (NewCC == OldCC)
17223 return false;
17224
17225 // If the calling conventions mismatch because the new function is static,
17226 // suppress the calling convention mismatch error; the error about static
17227 // function override (err_static_overrides_virtual from
17228 // Sema::CheckFunctionDeclaration) is more clear.
17229 if (New->getStorageClass() == SC_Static)
17230 return false;
17231
17232 Diag(New->getLocation(),
17233 diag::err_conflicting_overriding_cc_attributes)
17234 << New->getDeclName() << New->getType() << Old->getType();
17235 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
17236 return true;
17237}
17238
17239bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
17240 const CXXMethodDecl *Old) {
17241 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
17242 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
17243
17244 if (Context.hasSameType(NewTy, OldTy) ||
17245 NewTy->isDependentType() || OldTy->isDependentType())
17246 return false;
17247
17248 // Check if the return types are covariant
17249 QualType NewClassTy, OldClassTy;
17250
17251 /// Both types must be pointers or references to classes.
17252 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
17253 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
17254 NewClassTy = NewPT->getPointeeType();
17255 OldClassTy = OldPT->getPointeeType();
17256 }
17257 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
17258 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
17259 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
17260 NewClassTy = NewRT->getPointeeType();
17261 OldClassTy = OldRT->getPointeeType();
17262 }
17263 }
17264 }
17265
17266 // The return types aren't either both pointers or references to a class type.
17267 if (NewClassTy.isNull()) {
17268 Diag(New->getLocation(),
17269 diag::err_different_return_type_for_overriding_virtual_function)
17270 << New->getDeclName() << NewTy << OldTy
17271 << New->getReturnTypeSourceRange();
17272 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17273 << Old->getReturnTypeSourceRange();
17274
17275 return true;
17276 }
17277
17278 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
17279 // C++14 [class.virtual]p8:
17280 // If the class type in the covariant return type of D::f differs from
17281 // that of B::f, the class type in the return type of D::f shall be
17282 // complete at the point of declaration of D::f or shall be the class
17283 // type D.
17284 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
17285 if (!RT->isBeingDefined() &&
17286 RequireCompleteType(New->getLocation(), NewClassTy,
17287 diag::err_covariant_return_incomplete,
17288 New->getDeclName()))
17289 return true;
17290 }
17291
17292 // Check if the new class derives from the old class.
17293 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
17294 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
17295 << New->getDeclName() << NewTy << OldTy
17296 << New->getReturnTypeSourceRange();
17297 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17298 << Old->getReturnTypeSourceRange();
17299 return true;
17300 }
17301
17302 // Check if we the conversion from derived to base is valid.
17303 if (CheckDerivedToBaseConversion(
17304 NewClassTy, OldClassTy,
17305 diag::err_covariant_return_inaccessible_base,
17306 diag::err_covariant_return_ambiguous_derived_to_base_conv,
17307 New->getLocation(), New->getReturnTypeSourceRange(),
17308 New->getDeclName(), nullptr)) {
17309 // FIXME: this note won't trigger for delayed access control
17310 // diagnostics, and it's impossible to get an undelayed error
17311 // here from access control during the original parse because
17312 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
17313 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17314 << Old->getReturnTypeSourceRange();
17315 return true;
17316 }
17317 }
17318
17319 // The qualifiers of the return types must be the same.
17320 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
17321 Diag(New->getLocation(),
17322 diag::err_covariant_return_type_different_qualifications)
17323 << New->getDeclName() << NewTy << OldTy
17324 << New->getReturnTypeSourceRange();
17325 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17326 << Old->getReturnTypeSourceRange();
17327 return true;
17328 }
17329
17330
17331 // The new class type must have the same or less qualifiers as the old type.
17332 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
17333 Diag(New->getLocation(),
17334 diag::err_covariant_return_type_class_type_more_qualified)
17335 << New->getDeclName() << NewTy << OldTy
17336 << New->getReturnTypeSourceRange();
17337 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
17338 << Old->getReturnTypeSourceRange();
17339 return true;
17340 }
17341
17342 return false;
17343}
17344
17345/// Mark the given method pure.
17346///
17347/// \param Method the method to be marked pure.
17348///
17349/// \param InitRange the source range that covers the "0" initializer.
17350bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
17351 SourceLocation EndLoc = InitRange.getEnd();
17352 if (EndLoc.isValid())
17353 Method->setRangeEnd(EndLoc);
17354
17355 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
17356 Method->setPure();
17357 return false;
17358 }
17359
17360 if (!Method->isInvalidDecl())
17361 Diag(Method->getLocation(), diag::err_non_virtual_pure)
17362 << Method->getDeclName() << InitRange;
17363 return true;
17364}
17365
17366void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
17367 if (D->getFriendObjectKind())
17368 Diag(D->getLocation(), diag::err_pure_friend);
17369 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
17370 CheckPureMethod(M, ZeroLoc);
17371 else
17372 Diag(D->getLocation(), diag::err_illegal_initializer);
17373}
17374
17375/// Determine whether the given declaration is a global variable or
17376/// static data member.
17377static bool isNonlocalVariable(const Decl *D) {
17378 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
17379 return Var->hasGlobalStorage();
17380
17381 return false;
17382}
17383
17384/// Invoked when we are about to parse an initializer for the declaration
17385/// 'Dcl'.
17386///
17387/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
17388/// static data member of class X, names should be looked up in the scope of
17389/// class X. If the declaration had a scope specifier, a scope will have
17390/// been created and passed in for this purpose. Otherwise, S will be null.
17391void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
17392 // If there is no declaration, there was an error parsing it.
17393 if (!D || D->isInvalidDecl())
17394 return;
17395
17396 // We will always have a nested name specifier here, but this declaration
17397 // might not be out of line if the specifier names the current namespace:
17398 // extern int n;
17399 // int ::n = 0;
17400 if (S && D->isOutOfLine())
17401 EnterDeclaratorContext(S, D->getDeclContext());
17402
17403 // If we are parsing the initializer for a static data member, push a
17404 // new expression evaluation context that is associated with this static
17405 // data member.
17406 if (isNonlocalVariable(D))
17407 PushExpressionEvaluationContext(
17408 ExpressionEvaluationContext::PotentiallyEvaluated, D);
17409}
17410
17411/// Invoked after we are finished parsing an initializer for the declaration D.
17412void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
17413 // If there is no declaration, there was an error parsing it.
17414 if (!D || D->isInvalidDecl())
17415 return;
17416
17417 if (isNonlocalVariable(D))
17418 PopExpressionEvaluationContext();
17419
17420 if (S && D->isOutOfLine())
17421 ExitDeclaratorContext(S);
17422}
17423
17424/// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
17425/// C++ if/switch/while/for statement.
17426/// e.g: "if (int x = f()) {...}"
17427DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
17428 // C++ 6.4p2:
17429 // The declarator shall not specify a function or an array.
17430 // The type-specifier-seq shall not contain typedef and shall not declare a
17431 // new class or enumeration.
17432 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&(static_cast<void> (0))
17433 "Parser allowed 'typedef' as storage class of condition decl.")(static_cast<void> (0));
17434
17435 Decl *Dcl = ActOnDeclarator(S, D);
17436 if (!Dcl)
17437 return true;
17438
17439 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
17440 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
17441 << D.getSourceRange();
17442 return true;
17443 }
17444
17445 return Dcl;
17446}
17447
17448void Sema::LoadExternalVTableUses() {
17449 if (!ExternalSource)
17450 return;
17451
17452 SmallVector<ExternalVTableUse, 4> VTables;
17453 ExternalSource->ReadUsedVTables(VTables);
17454 SmallVector<VTableUse, 4> NewUses;
17455 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
17456 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
17457 = VTablesUsed.find(VTables[I].Record);
17458 // Even if a definition wasn't required before, it may be required now.
17459 if (Pos != VTablesUsed.end()) {
17460 if (!Pos->second && VTables[I].DefinitionRequired)
17461 Pos->second = true;
17462 continue;
17463 }
17464
17465 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
17466 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
17467 }
17468
17469 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
17470}
17471
17472void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
17473 bool DefinitionRequired) {
17474 // Ignore any vtable uses in unevaluated operands or for classes that do
17475 // not have a vtable.
17476 if (!Class->isDynamicClass() || Class->isDependentContext() ||
17477 CurContext->isDependentContext() || isUnevaluatedContext())
17478 return;
17479 // Do not mark as used if compiling for the device outside of the target
17480 // region.
17481 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
17482 !isInOpenMPDeclareTargetContext() &&
17483 !isInOpenMPTargetExecutionDirective()) {
17484 if (!DefinitionRequired)
17485 MarkVirtualMembersReferenced(Loc, Class);
17486 return;
17487 }
17488
17489 // Try to insert this class into the map.
17490 LoadExternalVTableUses();
17491 Class = Class->getCanonicalDecl();
17492 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
17493 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
17494 if (!Pos.second) {
17495 // If we already had an entry, check to see if we are promoting this vtable
17496 // to require a definition. If so, we need to reappend to the VTableUses
17497 // list, since we may have already processed the first entry.
17498 if (DefinitionRequired && !Pos.first->second) {
17499 Pos.first->second = true;
17500 } else {
17501 // Otherwise, we can early exit.
17502 return;
17503 }
17504 } else {
17505 // The Microsoft ABI requires that we perform the destructor body
17506 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
17507 // the deleting destructor is emitted with the vtable, not with the
17508 // destructor definition as in the Itanium ABI.
17509 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
17510 CXXDestructorDecl *DD = Class->getDestructor();
17511 if (DD && DD->isVirtual() && !DD->isDeleted()) {
17512 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
17513 // If this is an out-of-line declaration, marking it referenced will
17514 // not do anything. Manually call CheckDestructor to look up operator
17515 // delete().
17516 ContextRAII SavedContext(*this, DD);
17517 CheckDestructor(DD);
17518 } else {
17519 MarkFunctionReferenced(Loc, Class->getDestructor());
17520 }
17521 }
17522 }
17523 }
17524
17525 // Local classes need to have their virtual members marked
17526 // immediately. For all other classes, we mark their virtual members
17527 // at the end of the translation unit.
17528 if (Class->isLocalClass())
17529 MarkVirtualMembersReferenced(Loc, Class);
17530 else
17531 VTableUses.push_back(std::make_pair(Class, Loc));
17532}
17533
17534bool Sema::DefineUsedVTables() {
17535 LoadExternalVTableUses();
17536 if (VTableUses.empty())
17537 return false;
17538
17539 // Note: The VTableUses vector could grow as a result of marking
17540 // the members of a class as "used", so we check the size each
17541 // time through the loop and prefer indices (which are stable) to
17542 // iterators (which are not).
17543 bool DefinedAnything = false;
17544 for (unsigned I = 0; I != VTableUses.size(); ++I) {
17545 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
17546 if (!Class)
17547 continue;
17548 TemplateSpecializationKind ClassTSK =
17549 Class->getTemplateSpecializationKind();
17550
17551 SourceLocation Loc = VTableUses[I].second;
17552
17553 bool DefineVTable = true;
17554
17555 // If this class has a key function, but that key function is
17556 // defined in another translation unit, we don't need to emit the
17557 // vtable even though we're using it.
17558 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
17559 if (KeyFunction && !KeyFunction->hasBody()) {
17560 // The key function is in another translation unit.
17561 DefineVTable = false;
17562 TemplateSpecializationKind TSK =
17563 KeyFunction->getTemplateSpecializationKind();
17564 assert(TSK != TSK_ExplicitInstantiationDefinition &&(static_cast<void> (0))
17565 TSK != TSK_ImplicitInstantiation &&(static_cast<void> (0))
17566 "Instantiations don't have key functions")(static_cast<void> (0));
17567 (void)TSK;
17568 } else if (!KeyFunction) {
17569 // If we have a class with no key function that is the subject
17570 // of an explicit instantiation declaration, suppress the
17571 // vtable; it will live with the explicit instantiation
17572 // definition.
17573 bool IsExplicitInstantiationDeclaration =
17574 ClassTSK == TSK_ExplicitInstantiationDeclaration;
17575 for (auto R : Class->redecls()) {
17576 TemplateSpecializationKind TSK
17577 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
17578 if (TSK == TSK_ExplicitInstantiationDeclaration)
17579 IsExplicitInstantiationDeclaration = true;
17580 else if (TSK == TSK_ExplicitInstantiationDefinition) {
17581 IsExplicitInstantiationDeclaration = false;
17582 break;
17583 }
17584 }
17585
17586 if (IsExplicitInstantiationDeclaration)
17587 DefineVTable = false;
17588 }
17589
17590 // The exception specifications for all virtual members may be needed even
17591 // if we are not providing an authoritative form of the vtable in this TU.
17592 // We may choose to emit it available_externally anyway.
17593 if (!DefineVTable) {
17594 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
17595 continue;
17596 }
17597
17598 // Mark all of the virtual members of this class as referenced, so
17599 // that we can build a vtable. Then, tell the AST consumer that a
17600 // vtable for this class is required.
17601 DefinedAnything = true;
17602 MarkVirtualMembersReferenced(Loc, Class);
17603 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
17604 if (VTablesUsed[Canonical])
17605 Consumer.HandleVTable(Class);
17606
17607 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
17608 // no key function or the key function is inlined. Don't warn in C++ ABIs
17609 // that lack key functions, since the user won't be able to make one.
17610 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
17611 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
17612 const FunctionDecl *KeyFunctionDef = nullptr;
17613 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
17614 KeyFunctionDef->isInlined())) {
17615 Diag(Class->getLocation(),
17616 ClassTSK == TSK_ExplicitInstantiationDefinition
17617 ? diag::warn_weak_template_vtable
17618 : diag::warn_weak_vtable)
17619 << Class;
17620 }
17621 }
17622 }
17623 VTableUses.clear();
17624
17625 return DefinedAnything;
17626}
17627
17628void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
17629 const CXXRecordDecl *RD) {
17630 for (const auto *I : RD->methods())
17631 if (I->isVirtual() && !I->isPure())
17632 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
17633}
17634
17635void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
17636 const CXXRecordDecl *RD,
17637 bool ConstexprOnly) {
17638 // Mark all functions which will appear in RD's vtable as used.
17639 CXXFinalOverriderMap FinalOverriders;
17640 RD->getFinalOverriders(FinalOverriders);
17641 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
17642 E = FinalOverriders.end();
17643 I != E; ++I) {
17644 for (OverridingMethods::const_iterator OI = I->second.begin(),
17645 OE = I->second.end();
17646 OI != OE; ++OI) {
17647 assert(OI->second.size() > 0 && "no final overrider")(static_cast<void> (0));
17648 CXXMethodDecl *Overrider = OI->second.front().Method;
17649
17650 // C++ [basic.def.odr]p2:
17651 // [...] A virtual member function is used if it is not pure. [...]
17652 if (!Overrider->isPure() && (!ConstexprOnly || Overrider->isConstexpr()))
17653 MarkFunctionReferenced(Loc, Overrider);
17654 }
17655 }
17656
17657 // Only classes that have virtual bases need a VTT.
17658 if (RD->getNumVBases() == 0)
17659 return;
17660
17661 for (const auto &I : RD->bases()) {
17662 const auto *Base =
17663 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
17664 if (Base->getNumVBases() == 0)
17665 continue;
17666 MarkVirtualMembersReferenced(Loc, Base);
17667 }
17668}
17669
17670/// SetIvarInitializers - This routine builds initialization ASTs for the
17671/// Objective-C implementation whose ivars need be initialized.
17672void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
17673 if (!getLangOpts().CPlusPlus)
17674 return;
17675 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
17676 SmallVector<ObjCIvarDecl*, 8> ivars;
17677 CollectIvarsToConstructOrDestruct(OID, ivars);
17678 if (ivars.empty())
17679 return;
17680 SmallVector<CXXCtorInitializer*, 32> AllToInit;
17681 for (unsigned i = 0; i < ivars.size(); i++) {
17682 FieldDecl *Field = ivars[i];
17683 if (Field->isInvalidDecl())
17684 continue;
17685
17686 CXXCtorInitializer *Member;
17687 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
17688 InitializationKind InitKind =
17689 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
17690
17691 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
17692 ExprResult MemberInit =
17693 InitSeq.Perform(*this, InitEntity, InitKind, None);
17694 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
17695 // Note, MemberInit could actually come back empty if no initialization
17696 // is required (e.g., because it would call a trivial default constructor)
17697 if (!MemberInit.get() || MemberInit.isInvalid())
17698 continue;
17699
17700 Member =
17701 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
17702 SourceLocation(),
17703 MemberInit.getAs<Expr>(),
17704 SourceLocation());
17705 AllToInit.push_back(Member);
17706
17707 // Be sure that the destructor is accessible and is marked as referenced.
17708 if (const RecordType *RecordTy =
17709 Context.getBaseElementType(Field->getType())
17710 ->getAs<RecordType>()) {
17711 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
17712 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
17713 MarkFunctionReferenced(Field->getLocation(), Destructor);
17714 CheckDestructorAccess(Field->getLocation(), Destructor,
17715 PDiag(diag::err_access_dtor_ivar)
17716 << Context.getBaseElementType(Field->getType()));
17717 }
17718 }
17719 }
17720 ObjCImplementation->setIvarInitializers(Context,
17721 AllToInit.data(), AllToInit.size());
17722 }
17723}
17724
17725static
17726void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
17727 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
17728 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
17729 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
17730 Sema &S) {
17731 if (Ctor->isInvalidDecl())
17732 return;
17733
17734 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
17735
17736 // Target may not be determinable yet, for instance if this is a dependent
17737 // call in an uninstantiated template.
17738 if (Target) {
17739 const FunctionDecl *FNTarget = nullptr;
17740 (void)Target->hasBody(FNTarget);
17741 Target = const_cast<CXXConstructorDecl*>(
17742 cast_or_null<CXXConstructorDecl>(FNTarget));
17743 }
17744
17745 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
17746 // Avoid dereferencing a null pointer here.
17747 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
17748
17749 if (!Current.insert(Canonical).second)
17750 return;
17751
17752 // We know that beyond here, we aren't chaining into a cycle.
17753 if (!Target || !Target->isDelegatingConstructor() ||
17754 Target->isInvalidDecl() || Valid.count(TCanonical)) {
17755 Valid.insert(Current.begin(), Current.end());
17756 Current.clear();
17757 // We've hit a cycle.
17758 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
17759 Current.count(TCanonical)) {
17760 // If we haven't diagnosed this cycle yet, do so now.
17761 if (!Invalid.count(TCanonical)) {
17762 S.Diag((*Ctor->init_begin())->getSourceLocation(),
17763 diag::warn_delegating_ctor_cycle)
17764 << Ctor;
17765
17766 // Don't add a note for a function delegating directly to itself.
17767 if (TCanonical != Canonical)
17768 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
17769
17770 CXXConstructorDecl *C = Target;
17771 while (C->getCanonicalDecl() != Canonical) {
17772 const FunctionDecl *FNTarget = nullptr;
17773 (void)C->getTargetConstructor()->hasBody(FNTarget);
17774 assert(FNTarget && "Ctor cycle through bodiless function")(static_cast<void> (0));
17775
17776 C = const_cast<CXXConstructorDecl*>(
17777 cast<CXXConstructorDecl>(FNTarget));
17778 S.Diag(C->getLocation(), diag::note_which_delegates_to);
17779 }
17780 }
17781
17782 Invalid.insert(Current.begin(), Current.end());
17783 Current.clear();
17784 } else {
17785 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
17786 }
17787}
17788
17789
17790void Sema::CheckDelegatingCtorCycles() {
17791 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
17792
17793 for (DelegatingCtorDeclsType::iterator
17794 I = DelegatingCtorDecls.begin(ExternalSource),
17795 E = DelegatingCtorDecls.end();
17796 I != E; ++I)
17797 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
17798
17799 for (auto CI = Invalid.begin(), CE = Invalid.end(); CI != CE; ++CI)
17800 (*CI)->setInvalidDecl();
17801}
17802
17803namespace {
17804 /// AST visitor that finds references to the 'this' expression.
17805 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
17806 Sema &S;
17807
17808 public:
17809 explicit FindCXXThisExpr(Sema &S) : S(S) { }
17810
17811 bool VisitCXXThisExpr(CXXThisExpr *E) {
17812 S.Diag(E->getLocation(), diag::err_this_static_member_func)
17813 << E->isImplicit();
17814 return false;
17815 }
17816 };
17817}
17818
17819bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
17820 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17821 if (!TSInfo)
17822 return false;
17823
17824 TypeLoc TL = TSInfo->getTypeLoc();
17825 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17826 if (!ProtoTL)
17827 return false;
17828
17829 // C++11 [expr.prim.general]p3:
17830 // [The expression this] shall not appear before the optional
17831 // cv-qualifier-seq and it shall not appear within the declaration of a
17832 // static member function (although its type and value category are defined
17833 // within a static member function as they are within a non-static member
17834 // function). [ Note: this is because declaration matching does not occur
17835 // until the complete declarator is known. - end note ]
17836 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17837 FindCXXThisExpr Finder(*this);
17838
17839 // If the return type came after the cv-qualifier-seq, check it now.
17840 if (Proto->hasTrailingReturn() &&
17841 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
17842 return true;
17843
17844 // Check the exception specification.
17845 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
17846 return true;
17847
17848 // Check the trailing requires clause
17849 if (Expr *E = Method->getTrailingRequiresClause())
17850 if (!Finder.TraverseStmt(E))
17851 return true;
17852
17853 return checkThisInStaticMemberFunctionAttributes(Method);
17854}
17855
17856bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
17857 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
17858 if (!TSInfo)
17859 return false;
17860
17861 TypeLoc TL = TSInfo->getTypeLoc();
17862 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
17863 if (!ProtoTL)
17864 return false;
17865
17866 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
17867 FindCXXThisExpr Finder(*this);
17868
17869 switch (Proto->getExceptionSpecType()) {
17870 case EST_Unparsed:
17871 case EST_Uninstantiated:
17872 case EST_Unevaluated:
17873 case EST_BasicNoexcept:
17874 case EST_NoThrow:
17875 case EST_DynamicNone:
17876 case EST_MSAny:
17877 case EST_None:
17878 break;
17879
17880 case EST_DependentNoexcept:
17881 case EST_NoexceptFalse:
17882 case EST_NoexceptTrue:
17883 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
17884 return true;
17885 LLVM_FALLTHROUGH[[gnu::fallthrough]];
17886
17887 case EST_Dynamic:
17888 for (const auto &E : Proto->exceptions()) {
17889 if (!Finder.TraverseType(E))
17890 return true;
17891 }
17892 break;
17893 }
17894
17895 return false;
17896}
17897
17898bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
17899 FindCXXThisExpr Finder(*this);
17900
17901 // Check attributes.
17902 for (const auto *A : Method->attrs()) {
17903 // FIXME: This should be emitted by tblgen.
17904 Expr *Arg = nullptr;
17905 ArrayRef<Expr *> Args;
17906 if (const auto *G = dyn_cast<GuardedByAttr>(A))
17907 Arg = G->getArg();
17908 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
17909 Arg = G->getArg();
17910 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
17911 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
17912 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
17913 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
17914 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
17915 Arg = ETLF->getSuccessValue();
17916 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
17917 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
17918 Arg = STLF->getSuccessValue();
17919 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
17920 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
17921 Arg = LR->getArg();
17922 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
17923 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
17924 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
17925 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17926 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
17927 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17928 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
17929 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
17930 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
17931 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
17932
17933 if (Arg && !Finder.TraverseStmt(Arg))
17934 return true;
17935
17936 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
17937 if (!Finder.TraverseStmt(Args[I]))
17938 return true;
17939 }
17940 }
17941
17942 return false;
17943}
17944
17945void Sema::checkExceptionSpecification(
17946 bool IsTopLevel, ExceptionSpecificationType EST,
17947 ArrayRef<ParsedType> DynamicExceptions,
17948 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
17949 SmallVectorImpl<QualType> &Exceptions,
17950 FunctionProtoType::ExceptionSpecInfo &ESI) {
17951 Exceptions.clear();
17952 ESI.Type = EST;
17953 if (EST == EST_Dynamic) {
17954 Exceptions.reserve(DynamicExceptions.size());
17955 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
17956 // FIXME: Preserve type source info.
17957 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
17958
17959 if (IsTopLevel) {
17960 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
17961 collectUnexpandedParameterPacks(ET, Unexpanded);
17962 if (!Unexpanded.empty()) {
17963 DiagnoseUnexpandedParameterPacks(
17964 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
17965 Unexpanded);
17966 continue;
17967 }
17968 }
17969
17970 // Check that the type is valid for an exception spec, and
17971 // drop it if not.
17972 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
17973 Exceptions.push_back(ET);
17974 }
17975 ESI.Exceptions = Exceptions;
17976 return;
17977 }
17978
17979 if (isComputedNoexcept(EST)) {
17980 assert((NoexceptExpr->isTypeDependent() ||(static_cast<void> (0))
17981 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==(static_cast<void> (0))
17982 Context.BoolTy) &&(static_cast<void> (0))
17983 "Parser should have made sure that the expression is boolean")(static_cast<void> (0));
17984 if (IsTopLevel && DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
17985 ESI.Type = EST_BasicNoexcept;
17986 return;
17987 }
17988
17989 ESI.NoexceptExpr = NoexceptExpr;
17990 return;
17991 }
17992}
17993
17994void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
17995 ExceptionSpecificationType EST,
17996 SourceRange SpecificationRange,
17997 ArrayRef<ParsedType> DynamicExceptions,
17998 ArrayRef<SourceRange> DynamicExceptionRanges,
17999 Expr *NoexceptExpr) {
18000 if (!MethodD)
18001 return;
18002
18003 // Dig out the method we're referring to.
18004 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
18005 MethodD = FunTmpl->getTemplatedDecl();
18006
18007 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
18008 if (!Method)
18009 return;
18010
18011 // Check the exception specification.
18012 llvm::SmallVector<QualType, 4> Exceptions;
18013 FunctionProtoType::ExceptionSpecInfo ESI;
18014 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
18015 DynamicExceptionRanges, NoexceptExpr, Exceptions,
18016 ESI);
18017
18018 // Update the exception specification on the function type.
18019 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
18020
18021 if (Method->isStatic())
18022 checkThisInStaticMemberFunctionExceptionSpec(Method);
18023
18024 if (Method->isVirtual()) {
18025 // Check overrides, which we previously had to delay.
18026 for (const CXXMethodDecl *O : Method->overridden_methods())
18027 CheckOverridingFunctionExceptionSpec(Method, O);
18028 }
18029}
18030
18031/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
18032///
18033MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
18034 SourceLocation DeclStart, Declarator &D,
18035 Expr *BitWidth,
18036 InClassInitStyle InitStyle,
18037 AccessSpecifier AS,
18038 const ParsedAttr &MSPropertyAttr) {
18039 IdentifierInfo *II = D.getIdentifier();
18040 if (!II) {
18041 Diag(DeclStart, diag::err_anonymous_property);
18042 return nullptr;
18043 }
18044 SourceLocation Loc = D.getIdentifierLoc();
18045
18046 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
18047 QualType T = TInfo->getType();
18048 if (getLangOpts().CPlusPlus) {
18049 CheckExtraCXXDefaultArguments(D);
18050
18051 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
18052 UPPC_DataMemberType)) {
18053 D.setInvalidType();
18054 T = Context.IntTy;
18055 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
18056 }
18057 }
18058
18059 DiagnoseFunctionSpecifiers(D.getDeclSpec());
18060
18061 if (D.getDeclSpec().isInlineSpecified())
18062 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
18063 << getLangOpts().CPlusPlus17;
18064 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
18065 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
18066 diag::err_invalid_thread)
18067 << DeclSpec::getSpecifierName(TSCS);
18068
18069 // Check to see if this name was declared as a member previously
18070 NamedDecl *PrevDecl = nullptr;
18071 LookupResult Previous(*this, II, Loc, LookupMemberName,
18072 ForVisibleRedeclaration);
18073 LookupName(Previous, S);
18074 switch (Previous.getResultKind()) {
18075 case LookupResult::Found:
18076 case LookupResult::FoundUnresolvedValue:
18077 PrevDecl = Previous.getAsSingle<NamedDecl>();
18078 break;
18079
18080 case LookupResult::FoundOverloaded:
18081 PrevDecl = Previous.getRepresentativeDecl();
18082 break;
18083
18084 case LookupResult::NotFound:
18085 case LookupResult::NotFoundInCurrentInstantiation:
18086 case LookupResult::Ambiguous:
18087 break;
18088 }
18089
18090 if (PrevDecl && PrevDecl->isTemplateParameter()) {
18091 // Maybe we will complain about the shadowed template parameter.
18092 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
18093 // Just pretend that we didn't see the previous declaration.
18094 PrevDecl = nullptr;
18095 }
18096
18097 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
18098 PrevDecl = nullptr;
18099
18100 SourceLocation TSSL = D.getBeginLoc();
18101 MSPropertyDecl *NewPD =
18102 MSPropertyDecl::Create(Context, Record, Loc, II, T, TInfo, TSSL,
18103 MSPropertyAttr.getPropertyDataGetter(),
18104 MSPropertyAttr.getPropertyDataSetter());
18105 ProcessDeclAttributes(TUScope, NewPD, D);
18106 NewPD->setAccess(AS);
18107
18108 if (NewPD->isInvalidDecl())
18109 Record->setInvalidDecl();
18110
18111 if (D.getDeclSpec().isModulePrivateSpecified())
18112 NewPD->setModulePrivate();
18113
18114 if (NewPD->isInvalidDecl() && PrevDecl) {
18115 // Don't introduce NewFD into scope; there's already something
18116 // with the same name in the same scope.
18117 } else if (II) {
18118 PushOnScopeChains(NewPD, S);
18119 } else
18120 Record->addDecl(NewPD);
18121
18122 return NewPD;
18123}
18124
18125void Sema::ActOnStartFunctionDeclarationDeclarator(
18126 Declarator &Declarator, unsigned TemplateParameterDepth) {
18127 auto &Info = InventedParameterInfos.emplace_back();
18128 TemplateParameterList *ExplicitParams = nullptr;
18129 ArrayRef<TemplateParameterList *> ExplicitLists =
18130 Declarator.getTemplateParameterLists();
18131 if (!ExplicitLists.empty()) {
18132 bool IsMemberSpecialization, IsInvalid;
18133 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
18134 Declarator.getBeginLoc(), Declarator.getIdentifierLoc(),
18135 Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
18136 ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, IsInvalid,
18137 /*SuppressDiagnostic=*/true);
18138 }
18139 if (ExplicitParams) {
18140 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
18141 for (NamedDecl *Param : *ExplicitParams)
18142 Info.TemplateParams.push_back(Param);
18143 Info.NumExplicitTemplateParams = ExplicitParams->size();
18144 } else {
18145 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
18146 Info.NumExplicitTemplateParams = 0;
18147 }
18148}
18149
18150void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
18151 auto &FSI = InventedParameterInfos.back();
18152 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
18153 if (FSI.NumExplicitTemplateParams != 0) {
18154 TemplateParameterList *ExplicitParams =
18155 Declarator.getTemplateParameterLists().back();
18156 Declarator.setInventedTemplateParameterList(
18157 TemplateParameterList::Create(
18158 Context, ExplicitParams->getTemplateLoc(),
18159 ExplicitParams->getLAngleLoc(), FSI.TemplateParams,
18160 ExplicitParams->getRAngleLoc(),
18161 ExplicitParams->getRequiresClause()));
18162 } else {
18163 Declarator.setInventedTemplateParameterList(
18164 TemplateParameterList::Create(
18165 Context, SourceLocation(), SourceLocation(), FSI.TemplateParams,
18166 SourceLocation(), /*RequiresClause=*/nullptr));
18167 }
18168 }
18169 InventedParameterInfos.pop_back();
18170}

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/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; }
14
Assuming the condition is false
15
Returning zero, which participates in a condition later
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")(static_cast<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; }
3
Assuming field 'PtrWithInvalid' is > 1
4
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")(static_cast<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")(static_cast<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!")(static_cast<void> (0));
294 return R.get();
295 }
296
297 inline Stmt *AssertSuccess(StmtResult R) {
298 assert(!R.isInvalid() && "operation was asserted to never fail!")(static_cast<void> (0));
299 return R.get();
300 }
301
302} // namespace clang
303
304#endif // LLVM_CLANG_SEMA_OWNERSHIP_H

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/Sema/DeclSpec.h

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

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the PointerUnion class, which is a discriminated union of
10// pointer types.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_ADT_POINTERUNION_H
15#define LLVM_ADT_POINTERUNION_H
16
17#include "llvm/ADT/DenseMapInfo.h"
18#include "llvm/ADT/PointerIntPair.h"
19#include "llvm/Support/PointerLikeTypeTraits.h"
20#include <cassert>
21#include <cstddef>
22#include <cstdint>
23
24namespace llvm {
25
26namespace pointer_union_detail {
27 /// Determine the number of bits required to store integers with values < n.
28 /// This is ceil(log2(n)).
29 constexpr int bitsRequired(unsigned n) {
30 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
31 }
32
33 template <typename... Ts> constexpr int lowBitsAvailable() {
34 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
35 }
36
37 /// Find the index of a type in a list of types. TypeIndex<T, Us...>::Index
38 /// is the index of T in Us, or sizeof...(Us) if T does not appear in the
39 /// list.
40 template <typename T, typename ...Us> struct TypeIndex;
41 template <typename T, typename ...Us> struct TypeIndex<T, T, Us...> {
42 static constexpr int Index = 0;
43 };
44 template <typename T, typename U, typename... Us>
45 struct TypeIndex<T, U, Us...> {
46 static constexpr int Index = 1 + TypeIndex<T, Us...>::Index;
47 };
48 template <typename T> struct TypeIndex<T> {
49 static constexpr int Index = 0;
50 };
51
52 /// Find the first type in a list of types.
53 template <typename T, typename...> struct GetFirstType {
54 using type = T;
55 };
56
57 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
58 /// for the template arguments.
59 template <typename ...PTs> class PointerUnionUIntTraits {
60 public:
61 static inline void *getAsVoidPointer(void *P) { return P; }
62 static inline void *getFromVoidPointer(void *P) { return P; }
63 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
64 };
65
66 template <typename Derived, typename ValTy, int I, typename ...Types>
67 class PointerUnionMembers;
68
69 template <typename Derived, typename ValTy, int I>
70 class PointerUnionMembers<Derived, ValTy, I> {
71 protected:
72 ValTy Val;
73 PointerUnionMembers() = default;
74 PointerUnionMembers(ValTy Val) : Val(Val) {}
75
76 friend struct PointerLikeTypeTraits<Derived>;
77 };
78
79 template <typename Derived, typename ValTy, int I, typename Type,
80 typename ...Types>
81 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
82 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
83 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
84 public:
85 using Base::Base;
86 PointerUnionMembers() = default;
87 PointerUnionMembers(Type V)
88 : Base(ValTy(const_cast<void *>(
89 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
90 I)) {}
91
92 using Base::operator=;
93 Derived &operator=(Type V) {
94 this->Val = ValTy(
95 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
96 I);
97 return static_cast<Derived &>(*this);
98 };
99 };
100}
101
102/// A discriminated union of two or more pointer types, with the discriminator
103/// in the low bit of the pointer.
104///
105/// This implementation is extremely efficient in space due to leveraging the
106/// low bits of the pointer, while exposing a natural and type-safe API.
107///
108/// Common use patterns would be something like this:
109/// PointerUnion<int*, float*> P;
110/// P = (int*)0;
111/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
112/// X = P.get<int*>(); // ok.
113/// Y = P.get<float*>(); // runtime assertion failure.
114/// Z = P.get<double*>(); // compile time failure.
115/// P = (float*)0;
116/// Y = P.get<float*>(); // ok.
117/// X = P.get<int*>(); // runtime assertion failure.
118template <typename... PTs>
119class PointerUnion
120 : public pointer_union_detail::PointerUnionMembers<
121 PointerUnion<PTs...>,
122 PointerIntPair<
123 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
124 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
125 0, PTs...> {
126 // The first type is special because we want to directly cast a pointer to a
127 // default-initialized union to a pointer to the first type. But we don't
128 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
129 // because it's much more convenient to have a name for the whole pack. So
130 // split off the first type here.
131 using First = typename pointer_union_detail::GetFirstType<PTs...>::type;
132 using Base = typename PointerUnion::PointerUnionMembers;
133
134public:
135 PointerUnion() = default;
136
137 PointerUnion(std::nullptr_t) : PointerUnion() {}
138 using Base::Base;
139
140 /// Test if the pointer held in the union is null, regardless of
141 /// which type it is.
142 bool isNull() const { return !this->Val.getPointer(); }
38
Assuming the condition is false
39
Returning zero, which participates in a condition later
48
Assuming the condition is false
49
Returning zero, which participates in a condition later
56
Assuming the condition is true
57
Returning the value 1, which participates in a condition later
143
144 explicit operator bool() const { return !isNull(); }
145
146 /// Test if the Union currently holds the type matching T.
147 template <typename T> bool is() const {
148 constexpr int Index = pointer_union_detail::TypeIndex<T, PTs...>::Index;
149 static_assert(Index < sizeof...(PTs),
150 "PointerUnion::is<T> given type not in the union");
151 return this->Val.getInt() == Index;
152 }
153
154 /// Returns the value of the specified pointer type.
155 ///
156 /// If the specified pointer type is incorrect, assert.
157 template <typename T> T get() const {
158 assert(is<T>() && "Invalid accessor called")(static_cast<void> (0));
159 return PointerLikeTypeTraits<T>::getFromVoidPointer(this->Val.getPointer());
160 }
161
162 /// Returns the current pointer if it is of the specified pointer type,
163 /// otherwise returns null.
164 template <typename T> T dyn_cast() const {
165 if (is<T>())
166 return get<T>();
167 return T();
168 }
169
170 /// If the union is set to the first pointer type get an address pointing to
171 /// it.
172 First const *getAddrOfPtr1() const {
173 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
174 }
175
176 /// If the union is set to the first pointer type get an address pointing to
177 /// it.
178 First *getAddrOfPtr1() {
179 assert(is<First>() && "Val is not the first pointer")(static_cast<void> (0));
180 assert((static_cast<void> (0))
181 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==(static_cast<void> (0))
182 this->Val.getPointer() &&(static_cast<void> (0))
183 "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast<void> (0));
184 return const_cast<First *>(
185 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
186 }
187
188 /// Assignment from nullptr which just clears the union.
189 const PointerUnion &operator=(std::nullptr_t) {
190 this->Val.initWithPointer(nullptr);
191 return *this;
192 }
193
194 /// Assignment from elements of the union.
195 using Base::operator=;
196
197 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
198 static inline PointerUnion getFromOpaqueValue(void *VP) {
199 PointerUnion V;
200 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
201 return V;
202 }
203};
204
205template <typename ...PTs>
206bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
207 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
208}
209
210template <typename ...PTs>
211bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
212 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
213}
214
215template <typename ...PTs>
216bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
217 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
218}
219
220// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
221// # low bits available = min(PT1bits,PT2bits)-1.
222template <typename ...PTs>
223struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
224 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
225 return P.getOpaqueValue();
226 }
227
228 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
229 return PointerUnion<PTs...>::getFromOpaqueValue(P);
230 }
231
232 // The number of bits available are the min of the pointer types minus the
233 // bits needed for the discriminator.
234 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
235 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
236};
237
238// Teach DenseMap how to use PointerUnions as keys.
239template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
240 using Union = PointerUnion<PTs...>;
241 using FirstInfo =
242 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
243
244 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
245
246 static inline Union getTombstoneKey() {
247 return Union(FirstInfo::getTombstoneKey());
248 }
249
250 static unsigned getHashValue(const Union &UnionVal) {
251 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
252 return DenseMapInfo<intptr_t>::getHashValue(key);
253 }
254
255 static bool isEqual(const Union &LHS, const Union &RHS) {
256 return LHS == RHS;
257 }
258};
259
260} // end namespace llvm
261
262#endif // LLVM_ADT_POINTERUNION_H

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/ASTContext.h

1//===- ASTContext.h - Context to hold long-lived AST nodes ------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::ASTContext interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_ASTCONTEXT_H
15#define LLVM_CLANG_AST_ASTCONTEXT_H
16
17#include "clang/AST/ASTContextAllocate.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/CanonicalType.h"
20#include "clang/AST/CommentCommandTraits.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/Decl.h"
23#include "clang/AST/DeclBase.h"
24#include "clang/AST/DeclarationName.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/NestedNameSpecifier.h"
27#include "clang/AST/PrettyPrinter.h"
28#include "clang/AST/RawCommentList.h"
29#include "clang/AST/TemplateName.h"
30#include "clang/AST/Type.h"
31#include "clang/Basic/AddressSpaces.h"
32#include "clang/Basic/AttrKinds.h"
33#include "clang/Basic/IdentifierTable.h"
34#include "clang/Basic/LLVM.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/Linkage.h"
37#include "clang/Basic/NoSanitizeList.h"
38#include "clang/Basic/OperatorKinds.h"
39#include "clang/Basic/PartialDiagnostic.h"
40#include "clang/Basic/ProfileList.h"
41#include "clang/Basic/SourceLocation.h"
42#include "clang/Basic/Specifiers.h"
43#include "clang/Basic/TargetCXXABI.h"
44#include "clang/Basic/XRayLists.h"
45#include "llvm/ADT/APSInt.h"
46#include "llvm/ADT/ArrayRef.h"
47#include "llvm/ADT/DenseMap.h"
48#include "llvm/ADT/DenseSet.h"
49#include "llvm/ADT/FoldingSet.h"
50#include "llvm/ADT/IntrusiveRefCntPtr.h"
51#include "llvm/ADT/MapVector.h"
52#include "llvm/ADT/None.h"
53#include "llvm/ADT/Optional.h"
54#include "llvm/ADT/PointerIntPair.h"
55#include "llvm/ADT/PointerUnion.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/StringMap.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/TinyPtrVector.h"
60#include "llvm/ADT/Triple.h"
61#include "llvm/ADT/iterator_range.h"
62#include "llvm/Support/AlignOf.h"
63#include "llvm/Support/Allocator.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/Compiler.h"
66#include "llvm/Support/TypeSize.h"
67#include <cassert>
68#include <cstddef>
69#include <cstdint>
70#include <iterator>
71#include <memory>
72#include <string>
73#include <type_traits>
74#include <utility>
75#include <vector>
76
77namespace llvm {
78
79class APFixedPoint;
80class FixedPointSemantics;
81struct fltSemantics;
82template <typename T, unsigned N> class SmallPtrSet;
83
84} // namespace llvm
85
86namespace clang {
87
88class APValue;
89class ASTMutationListener;
90class ASTRecordLayout;
91class AtomicExpr;
92class BlockExpr;
93class BuiltinTemplateDecl;
94class CharUnits;
95class ConceptDecl;
96class CXXABI;
97class CXXConstructorDecl;
98class CXXMethodDecl;
99class CXXRecordDecl;
100class DiagnosticsEngine;
101class ParentMapContext;
102class DynTypedNode;
103class DynTypedNodeList;
104class Expr;
105class GlobalDecl;
106class ItaniumMangleContext;
107class MangleContext;
108class MangleNumberingContext;
109class MaterializeTemporaryExpr;
110class MemberSpecializationInfo;
111class Module;
112struct MSGuidDeclParts;
113class ObjCCategoryDecl;
114class ObjCCategoryImplDecl;
115class ObjCContainerDecl;
116class ObjCImplDecl;
117class ObjCImplementationDecl;
118class ObjCInterfaceDecl;
119class ObjCIvarDecl;
120class ObjCMethodDecl;
121class ObjCPropertyDecl;
122class ObjCPropertyImplDecl;
123class ObjCProtocolDecl;
124class ObjCTypeParamDecl;
125class OMPTraitInfo;
126struct ParsedTargetAttr;
127class Preprocessor;
128class Stmt;
129class StoredDeclsMap;
130class TargetAttr;
131class TargetInfo;
132class TemplateDecl;
133class TemplateParameterList;
134class TemplateTemplateParmDecl;
135class TemplateTypeParmDecl;
136class UnresolvedSetIterator;
137class UsingShadowDecl;
138class VarTemplateDecl;
139class VTableContextBase;
140struct BlockVarCopyInit;
141
142namespace Builtin {
143
144class Context;
145
146} // namespace Builtin
147
148enum BuiltinTemplateKind : int;
149enum OpenCLTypeKind : uint8_t;
150
151namespace comments {
152
153class FullComment;
154
155} // namespace comments
156
157namespace interp {
158
159class Context;
160
161} // namespace interp
162
163namespace serialization {
164template <class> class AbstractTypeReader;
165} // namespace serialization
166
167enum class AlignRequirementKind {
168 /// The alignment was not explicit in code.
169 None,
170
171 /// The alignment comes from an alignment attribute on a typedef.
172 RequiredByTypedef,
173
174 /// The alignment comes from an alignment attribute on a record type.
175 RequiredByRecord,
176
177 /// The alignment comes from an alignment attribute on a enum type.
178 RequiredByEnum,
179};
180
181struct TypeInfo {
182 uint64_t Width = 0;
183 unsigned Align = 0;
184 AlignRequirementKind AlignRequirement;
185
186 TypeInfo() : AlignRequirement(AlignRequirementKind::None) {}
187 TypeInfo(uint64_t Width, unsigned Align,
188 AlignRequirementKind AlignRequirement)
189 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
190 bool isAlignRequired() {
191 return AlignRequirement != AlignRequirementKind::None;
192 }
193};
194
195struct TypeInfoChars {
196 CharUnits Width;
197 CharUnits Align;
198 AlignRequirementKind AlignRequirement;
199
200 TypeInfoChars() : AlignRequirement(AlignRequirementKind::None) {}
201 TypeInfoChars(CharUnits Width, CharUnits Align,
202 AlignRequirementKind AlignRequirement)
203 : Width(Width), Align(Align), AlignRequirement(AlignRequirement) {}
204 bool isAlignRequired() {
205 return AlignRequirement != AlignRequirementKind::None;
206 }
207};
208
209/// Holds long-lived AST nodes (such as types and decls) that can be
210/// referred to throughout the semantic analysis of a file.
211class ASTContext : public RefCountedBase<ASTContext> {
212 friend class NestedNameSpecifier;
213
214 mutable SmallVector<Type *, 0> Types;
215 mutable llvm::FoldingSet<ExtQuals> ExtQualNodes;
216 mutable llvm::FoldingSet<ComplexType> ComplexTypes;
217 mutable llvm::FoldingSet<PointerType> PointerTypes;
218 mutable llvm::FoldingSet<AdjustedType> AdjustedTypes;
219 mutable llvm::FoldingSet<BlockPointerType> BlockPointerTypes;
220 mutable llvm::FoldingSet<LValueReferenceType> LValueReferenceTypes;
221 mutable llvm::FoldingSet<RValueReferenceType> RValueReferenceTypes;
222 mutable llvm::FoldingSet<MemberPointerType> MemberPointerTypes;
223 mutable llvm::ContextualFoldingSet<ConstantArrayType, ASTContext &>
224 ConstantArrayTypes;
225 mutable llvm::FoldingSet<IncompleteArrayType> IncompleteArrayTypes;
226 mutable std::vector<VariableArrayType*> VariableArrayTypes;
227 mutable llvm::FoldingSet<DependentSizedArrayType> DependentSizedArrayTypes;
228 mutable llvm::FoldingSet<DependentSizedExtVectorType>
229 DependentSizedExtVectorTypes;
230 mutable llvm::FoldingSet<DependentAddressSpaceType>
231 DependentAddressSpaceTypes;
232 mutable llvm::FoldingSet<VectorType> VectorTypes;
233 mutable llvm::FoldingSet<DependentVectorType> DependentVectorTypes;
234 mutable llvm::FoldingSet<ConstantMatrixType> MatrixTypes;
235 mutable llvm::FoldingSet<DependentSizedMatrixType> DependentSizedMatrixTypes;
236 mutable llvm::FoldingSet<FunctionNoProtoType> FunctionNoProtoTypes;
237 mutable llvm::ContextualFoldingSet<FunctionProtoType, ASTContext&>
238 FunctionProtoTypes;
239 mutable llvm::FoldingSet<DependentTypeOfExprType> DependentTypeOfExprTypes;
240 mutable llvm::FoldingSet<DependentDecltypeType> DependentDecltypeTypes;
241 mutable llvm::FoldingSet<TemplateTypeParmType> TemplateTypeParmTypes;
242 mutable llvm::FoldingSet<ObjCTypeParamType> ObjCTypeParamTypes;
243 mutable llvm::FoldingSet<SubstTemplateTypeParmType>
244 SubstTemplateTypeParmTypes;
245 mutable llvm::FoldingSet<SubstTemplateTypeParmPackType>
246 SubstTemplateTypeParmPackTypes;
247 mutable llvm::ContextualFoldingSet<TemplateSpecializationType, ASTContext&>
248 TemplateSpecializationTypes;
249 mutable llvm::FoldingSet<ParenType> ParenTypes;
250 mutable llvm::FoldingSet<ElaboratedType> ElaboratedTypes;
251 mutable llvm::FoldingSet<DependentNameType> DependentNameTypes;
252 mutable llvm::ContextualFoldingSet<DependentTemplateSpecializationType,
253 ASTContext&>
254 DependentTemplateSpecializationTypes;
255 llvm::FoldingSet<PackExpansionType> PackExpansionTypes;
256 mutable llvm::FoldingSet<ObjCObjectTypeImpl> ObjCObjectTypes;
257 mutable llvm::FoldingSet<ObjCObjectPointerType> ObjCObjectPointerTypes;
258 mutable llvm::FoldingSet<DependentUnaryTransformType>
259 DependentUnaryTransformTypes;
260 mutable llvm::ContextualFoldingSet<AutoType, ASTContext&> AutoTypes;
261 mutable llvm::FoldingSet<DeducedTemplateSpecializationType>
262 DeducedTemplateSpecializationTypes;
263 mutable llvm::FoldingSet<AtomicType> AtomicTypes;
264 llvm::FoldingSet<AttributedType> AttributedTypes;
265 mutable llvm::FoldingSet<PipeType> PipeTypes;
266 mutable llvm::FoldingSet<ExtIntType> ExtIntTypes;
267 mutable llvm::FoldingSet<DependentExtIntType> DependentExtIntTypes;
268
269 mutable llvm::FoldingSet<QualifiedTemplateName> QualifiedTemplateNames;
270 mutable llvm::FoldingSet<DependentTemplateName> DependentTemplateNames;
271 mutable llvm::FoldingSet<SubstTemplateTemplateParmStorage>
272 SubstTemplateTemplateParms;
273 mutable llvm::ContextualFoldingSet<SubstTemplateTemplateParmPackStorage,
274 ASTContext&>
275 SubstTemplateTemplateParmPacks;
276
277 /// The set of nested name specifiers.
278 ///
279 /// This set is managed by the NestedNameSpecifier class.
280 mutable llvm::FoldingSet<NestedNameSpecifier> NestedNameSpecifiers;
281 mutable NestedNameSpecifier *GlobalNestedNameSpecifier = nullptr;
282
283 /// A cache mapping from RecordDecls to ASTRecordLayouts.
284 ///
285 /// This is lazily created. This is intentionally not serialized.
286 mutable llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>
287 ASTRecordLayouts;
288 mutable llvm::DenseMap<const ObjCContainerDecl*, const ASTRecordLayout*>
289 ObjCLayouts;
290
291 /// A cache from types to size and alignment information.
292 using TypeInfoMap = llvm::DenseMap<const Type *, struct TypeInfo>;
293 mutable TypeInfoMap MemoizedTypeInfo;
294
295 /// A cache from types to unadjusted alignment information. Only ARM and
296 /// AArch64 targets need this information, keeping it separate prevents
297 /// imposing overhead on TypeInfo size.
298 using UnadjustedAlignMap = llvm::DenseMap<const Type *, unsigned>;
299 mutable UnadjustedAlignMap MemoizedUnadjustedAlign;
300
301 /// A cache mapping from CXXRecordDecls to key functions.
302 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr> KeyFunctions;
303
304 /// Mapping from ObjCContainers to their ObjCImplementations.
305 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*> ObjCImpls;
306
307 /// Mapping from ObjCMethod to its duplicate declaration in the same
308 /// interface.
309 llvm::DenseMap<const ObjCMethodDecl*,const ObjCMethodDecl*> ObjCMethodRedecls;
310
311 /// Mapping from __block VarDecls to BlockVarCopyInit.
312 llvm::DenseMap<const VarDecl *, BlockVarCopyInit> BlockVarCopyInits;
313
314 /// Mapping from GUIDs to the corresponding MSGuidDecl.
315 mutable llvm::FoldingSet<MSGuidDecl> MSGuidDecls;
316
317 /// Mapping from APValues to the corresponding TemplateParamObjects.
318 mutable llvm::FoldingSet<TemplateParamObjectDecl> TemplateParamObjectDecls;
319
320 /// A cache mapping a string value to a StringLiteral object with the same
321 /// value.
322 ///
323 /// This is lazily created. This is intentionally not serialized.
324 mutable llvm::StringMap<StringLiteral *> StringLiteralCache;
325
326 /// MD5 hash of CUID. It is calculated when first used and cached by this
327 /// data member.
328 mutable std::string CUIDHash;
329
330 /// Representation of a "canonical" template template parameter that
331 /// is used in canonical template names.
332 class CanonicalTemplateTemplateParm : public llvm::FoldingSetNode {
333 TemplateTemplateParmDecl *Parm;
334
335 public:
336 CanonicalTemplateTemplateParm(TemplateTemplateParmDecl *Parm)
337 : Parm(Parm) {}
338
339 TemplateTemplateParmDecl *getParam() const { return Parm; }
340
341 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &C) {
342 Profile(ID, C, Parm);
343 }
344
345 static void Profile(llvm::FoldingSetNodeID &ID,
346 const ASTContext &C,
347 TemplateTemplateParmDecl *Parm);
348 };
349 mutable llvm::ContextualFoldingSet<CanonicalTemplateTemplateParm,
350 const ASTContext&>
351 CanonTemplateTemplateParms;
352
353 TemplateTemplateParmDecl *
354 getCanonicalTemplateTemplateParmDecl(TemplateTemplateParmDecl *TTP) const;
355
356 /// The typedef for the __int128_t type.
357 mutable TypedefDecl *Int128Decl = nullptr;
358
359 /// The typedef for the __uint128_t type.
360 mutable TypedefDecl *UInt128Decl = nullptr;
361
362 /// The typedef for the target specific predefined
363 /// __builtin_va_list type.
364 mutable TypedefDecl *BuiltinVaListDecl = nullptr;
365
366 /// The typedef for the predefined \c __builtin_ms_va_list type.
367 mutable TypedefDecl *BuiltinMSVaListDecl = nullptr;
368
369 /// The typedef for the predefined \c id type.
370 mutable TypedefDecl *ObjCIdDecl = nullptr;
371
372 /// The typedef for the predefined \c SEL type.
373 mutable TypedefDecl *ObjCSelDecl = nullptr;
374
375 /// The typedef for the predefined \c Class type.
376 mutable TypedefDecl *ObjCClassDecl = nullptr;
377
378 /// The typedef for the predefined \c Protocol class in Objective-C.
379 mutable ObjCInterfaceDecl *ObjCProtocolClassDecl = nullptr;
380
381 /// The typedef for the predefined 'BOOL' type.
382 mutable TypedefDecl *BOOLDecl = nullptr;
383
384 // Typedefs which may be provided defining the structure of Objective-C
385 // pseudo-builtins
386 QualType ObjCIdRedefinitionType;
387 QualType ObjCClassRedefinitionType;
388 QualType ObjCSelRedefinitionType;
389
390 /// The identifier 'bool'.
391 mutable IdentifierInfo *BoolName = nullptr;
392
393 /// The identifier 'NSObject'.
394 mutable IdentifierInfo *NSObjectName = nullptr;
395
396 /// The identifier 'NSCopying'.
397 IdentifierInfo *NSCopyingName = nullptr;
398
399 /// The identifier '__make_integer_seq'.
400 mutable IdentifierInfo *MakeIntegerSeqName = nullptr;
401
402 /// The identifier '__type_pack_element'.
403 mutable IdentifierInfo *TypePackElementName = nullptr;
404
405 QualType ObjCConstantStringType;
406 mutable RecordDecl *CFConstantStringTagDecl = nullptr;
407 mutable TypedefDecl *CFConstantStringTypeDecl = nullptr;
408
409 mutable QualType ObjCSuperType;
410
411 QualType ObjCNSStringType;
412
413 /// The typedef declaration for the Objective-C "instancetype" type.
414 TypedefDecl *ObjCInstanceTypeDecl = nullptr;
415
416 /// The type for the C FILE type.
417 TypeDecl *FILEDecl = nullptr;
418
419 /// The type for the C jmp_buf type.
420 TypeDecl *jmp_bufDecl = nullptr;
421
422 /// The type for the C sigjmp_buf type.
423 TypeDecl *sigjmp_bufDecl = nullptr;
424
425 /// The type for the C ucontext_t type.
426 TypeDecl *ucontext_tDecl = nullptr;
427
428 /// Type for the Block descriptor for Blocks CodeGen.
429 ///
430 /// Since this is only used for generation of debug info, it is not
431 /// serialized.
432 mutable RecordDecl *BlockDescriptorType = nullptr;
433
434 /// Type for the Block descriptor for Blocks CodeGen.
435 ///
436 /// Since this is only used for generation of debug info, it is not
437 /// serialized.
438 mutable RecordDecl *BlockDescriptorExtendedType = nullptr;
439
440 /// Declaration for the CUDA cudaConfigureCall function.
441 FunctionDecl *cudaConfigureCallDecl = nullptr;
442
443 /// Keeps track of all declaration attributes.
444 ///
445 /// Since so few decls have attrs, we keep them in a hash map instead of
446 /// wasting space in the Decl class.
447 llvm::DenseMap<const Decl*, AttrVec*> DeclAttrs;
448
449 /// A mapping from non-redeclarable declarations in modules that were
450 /// merged with other declarations to the canonical declaration that they were
451 /// merged into.
452 llvm::DenseMap<Decl*, Decl*> MergedDecls;
453
454 /// A mapping from a defining declaration to a list of modules (other
455 /// than the owning module of the declaration) that contain merged
456 /// definitions of that entity.
457 llvm::DenseMap<NamedDecl*, llvm::TinyPtrVector<Module*>> MergedDefModules;
458
459 /// Initializers for a module, in order. Each Decl will be either
460 /// something that has a semantic effect on startup (such as a variable with
461 /// a non-constant initializer), or an ImportDecl (which recursively triggers
462 /// initialization of another module).
463 struct PerModuleInitializers {
464 llvm::SmallVector<Decl*, 4> Initializers;
465 llvm::SmallVector<uint32_t, 4> LazyInitializers;
466
467 void resolve(ASTContext &Ctx);
468 };
469 llvm::DenseMap<Module*, PerModuleInitializers*> ModuleInitializers;
470
471 ASTContext &this_() { return *this; }
472
473public:
474 /// A type synonym for the TemplateOrInstantiation mapping.
475 using TemplateOrSpecializationInfo =
476 llvm::PointerUnion<VarTemplateDecl *, MemberSpecializationInfo *>;
477
478private:
479 friend class ASTDeclReader;
480 friend class ASTReader;
481 friend class ASTWriter;
482 template <class> friend class serialization::AbstractTypeReader;
483 friend class CXXRecordDecl;
484 friend class IncrementalParser;
485
486 /// A mapping to contain the template or declaration that
487 /// a variable declaration describes or was instantiated from,
488 /// respectively.
489 ///
490 /// For non-templates, this value will be NULL. For variable
491 /// declarations that describe a variable template, this will be a
492 /// pointer to a VarTemplateDecl. For static data members
493 /// of class template specializations, this will be the
494 /// MemberSpecializationInfo referring to the member variable that was
495 /// instantiated or specialized. Thus, the mapping will keep track of
496 /// the static data member templates from which static data members of
497 /// class template specializations were instantiated.
498 ///
499 /// Given the following example:
500 ///
501 /// \code
502 /// template<typename T>
503 /// struct X {
504 /// static T value;
505 /// };
506 ///
507 /// template<typename T>
508 /// T X<T>::value = T(17);
509 ///
510 /// int *x = &X<int>::value;
511 /// \endcode
512 ///
513 /// This mapping will contain an entry that maps from the VarDecl for
514 /// X<int>::value to the corresponding VarDecl for X<T>::value (within the
515 /// class template X) and will be marked TSK_ImplicitInstantiation.
516 llvm::DenseMap<const VarDecl *, TemplateOrSpecializationInfo>
517 TemplateOrInstantiation;
518
519 /// Keeps track of the declaration from which a using declaration was
520 /// created during instantiation.
521 ///
522 /// The source and target declarations are always a UsingDecl, an
523 /// UnresolvedUsingValueDecl, or an UnresolvedUsingTypenameDecl.
524 ///
525 /// For example:
526 /// \code
527 /// template<typename T>
528 /// struct A {
529 /// void f();
530 /// };
531 ///
532 /// template<typename T>
533 /// struct B : A<T> {
534 /// using A<T>::f;
535 /// };
536 ///
537 /// template struct B<int>;
538 /// \endcode
539 ///
540 /// This mapping will contain an entry that maps from the UsingDecl in
541 /// B<int> to the UnresolvedUsingDecl in B<T>.
542 llvm::DenseMap<NamedDecl *, NamedDecl *> InstantiatedFromUsingDecl;
543
544 /// Like InstantiatedFromUsingDecl, but for using-enum-declarations. Maps
545 /// from the instantiated using-enum to the templated decl from whence it
546 /// came.
547 /// Note that using-enum-declarations cannot be dependent and
548 /// thus will never be instantiated from an "unresolved"
549 /// version thereof (as with using-declarations), so each mapping is from
550 /// a (resolved) UsingEnumDecl to a (resolved) UsingEnumDecl.
551 llvm::DenseMap<UsingEnumDecl *, UsingEnumDecl *>
552 InstantiatedFromUsingEnumDecl;
553
554 /// Simlarly maps instantiated UsingShadowDecls to their origin.
555 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>
556 InstantiatedFromUsingShadowDecl;
557
558 llvm::DenseMap<FieldDecl *, FieldDecl *> InstantiatedFromUnnamedFieldDecl;
559
560 /// Mapping that stores the methods overridden by a given C++
561 /// member function.
562 ///
563 /// Since most C++ member functions aren't virtual and therefore
564 /// don't override anything, we store the overridden functions in
565 /// this map on the side rather than within the CXXMethodDecl structure.
566 using CXXMethodVector = llvm::TinyPtrVector<const CXXMethodDecl *>;
567 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector> OverriddenMethods;
568
569 /// Mapping from each declaration context to its corresponding
570 /// mangling numbering context (used for constructs like lambdas which
571 /// need to be consistently numbered for the mangler).
572 llvm::DenseMap<const DeclContext *, std::unique_ptr<MangleNumberingContext>>
573 MangleNumberingContexts;
574 llvm::DenseMap<const Decl *, std::unique_ptr<MangleNumberingContext>>
575 ExtraMangleNumberingContexts;
576
577 /// Side-table of mangling numbers for declarations which rarely
578 /// need them (like static local vars).
579 llvm::MapVector<const NamedDecl *, unsigned> MangleNumbers;
580 llvm::MapVector<const VarDecl *, unsigned> StaticLocalNumbers;
581 /// Mapping the associated device lambda mangling number if present.
582 mutable llvm::DenseMap<const CXXRecordDecl *, unsigned>
583 DeviceLambdaManglingNumbers;
584
585 /// Mapping that stores parameterIndex values for ParmVarDecls when
586 /// that value exceeds the bitfield size of ParmVarDeclBits.ParameterIndex.
587 using ParameterIndexTable = llvm::DenseMap<const VarDecl *, unsigned>;
588 ParameterIndexTable ParamIndices;
589
590 ImportDecl *FirstLocalImport = nullptr;
591 ImportDecl *LastLocalImport = nullptr;
592
593 TranslationUnitDecl *TUDecl = nullptr;
594 mutable ExternCContextDecl *ExternCContext = nullptr;
595 mutable BuiltinTemplateDecl *MakeIntegerSeqDecl = nullptr;
596 mutable BuiltinTemplateDecl *TypePackElementDecl = nullptr;
597
598 /// The associated SourceManager object.
599 SourceManager &SourceMgr;
600
601 /// The language options used to create the AST associated with
602 /// this ASTContext object.
603 LangOptions &LangOpts;
604
605 /// NoSanitizeList object that is used by sanitizers to decide which
606 /// entities should not be instrumented.
607 std::unique_ptr<NoSanitizeList> NoSanitizeL;
608
609 /// Function filtering mechanism to determine whether a given function
610 /// should be imbued with the XRay "always" or "never" attributes.
611 std::unique_ptr<XRayFunctionFilter> XRayFilter;
612
613 /// ProfileList object that is used by the profile instrumentation
614 /// to decide which entities should be instrumented.
615 std::unique_ptr<ProfileList> ProfList;
616
617 /// The allocator used to create AST objects.
618 ///
619 /// AST objects are never destructed; rather, all memory associated with the
620 /// AST objects will be released when the ASTContext itself is destroyed.
621 mutable llvm::BumpPtrAllocator BumpAlloc;
622
623 /// Allocator for partial diagnostics.
624 PartialDiagnostic::DiagStorageAllocator DiagAllocator;
625
626 /// The current C++ ABI.
627 std::unique_ptr<CXXABI> ABI;
628 CXXABI *createCXXABI(const TargetInfo &T);
629
630 /// The logical -> physical address space map.
631 const LangASMap *AddrSpaceMap = nullptr;
632
633 /// Address space map mangling must be used with language specific
634 /// address spaces (e.g. OpenCL/CUDA)
635 bool AddrSpaceMapMangling;
636
637 const TargetInfo *Target = nullptr;
638 const TargetInfo *AuxTarget = nullptr;
639 clang::PrintingPolicy PrintingPolicy;
640 std::unique_ptr<interp::Context> InterpContext;
641 std::unique_ptr<ParentMapContext> ParentMapCtx;
642
643 /// Keeps track of the deallocated DeclListNodes for future reuse.
644 DeclListNode *ListNodeFreeList = nullptr;
645
646public:
647 IdentifierTable &Idents;
648 SelectorTable &Selectors;
649 Builtin::Context &BuiltinInfo;
650 const TranslationUnitKind TUKind;
651 mutable DeclarationNameTable DeclarationNames;
652 IntrusiveRefCntPtr<ExternalASTSource> ExternalSource;
653 ASTMutationListener *Listener = nullptr;
654
655 /// Returns the clang bytecode interpreter context.
656 interp::Context &getInterpContext();
657
658 /// Returns the dynamic AST node parent map context.
659 ParentMapContext &getParentMapContext();
660
661 // A traversal scope limits the parts of the AST visible to certain analyses.
662 // RecursiveASTVisitor only visits specified children of TranslationUnitDecl.
663 // getParents() will only observe reachable parent edges.
664 //
665 // The scope is defined by a set of "top-level" declarations which will be
666 // visible under the TranslationUnitDecl.
667 // Initially, it is the entire TU, represented by {getTranslationUnitDecl()}.
668 //
669 // After setTraversalScope({foo, bar}), the exposed AST looks like:
670 // TranslationUnitDecl
671 // - foo
672 // - ...
673 // - bar
674 // - ...
675 // All other siblings of foo and bar are pruned from the tree.
676 // (However they are still accessible via TranslationUnitDecl->decls())
677 //
678 // Changing the scope clears the parent cache, which is expensive to rebuild.
679 std::vector<Decl *> getTraversalScope() const { return TraversalScope; }
680 void setTraversalScope(const std::vector<Decl *> &);
681
682 /// Forwards to get node parents from the ParentMapContext. New callers should
683 /// use ParentMapContext::getParents() directly.
684 template <typename NodeT> DynTypedNodeList getParents(const NodeT &Node);
685
686 const clang::PrintingPolicy &getPrintingPolicy() const {
687 return PrintingPolicy;
688 }
689
690 void setPrintingPolicy(const clang::PrintingPolicy &Policy) {
691 PrintingPolicy = Policy;
692 }
693
694 SourceManager& getSourceManager() { return SourceMgr; }
695 const SourceManager& getSourceManager() const { return SourceMgr; }
696
697 llvm::BumpPtrAllocator &getAllocator() const {
698 return BumpAlloc;
699 }
700
701 void *Allocate(size_t Size, unsigned Align = 8) const {
702 return BumpAlloc.Allocate(Size, Align);
703 }
704 template <typename T> T *Allocate(size_t Num = 1) const {
705 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
706 }
707 void Deallocate(void *Ptr) const {}
708
709 /// Allocates a \c DeclListNode or returns one from the \c ListNodeFreeList
710 /// pool.
711 DeclListNode *AllocateDeclListNode(clang::NamedDecl *ND) {
712 if (DeclListNode *Alloc = ListNodeFreeList) {
713 ListNodeFreeList = Alloc->Rest.dyn_cast<DeclListNode*>();
714 Alloc->D = ND;
715 Alloc->Rest = nullptr;
716 return Alloc;
717 }
718 return new (*this) DeclListNode(ND);
719 }
720 /// Deallcates a \c DeclListNode by returning it to the \c ListNodeFreeList
721 /// pool.
722 void DeallocateDeclListNode(DeclListNode *N) {
723 N->Rest = ListNodeFreeList;
724 ListNodeFreeList = N;
725 }
726
727 /// Return the total amount of physical memory allocated for representing
728 /// AST nodes and type information.
729 size_t getASTAllocatedMemory() const {
730 return BumpAlloc.getTotalMemory();
731 }
732
733 /// Return the total memory used for various side tables.
734 size_t getSideTableAllocatedMemory() const;
735
736 PartialDiagnostic::DiagStorageAllocator &getDiagAllocator() {
737 return DiagAllocator;
738 }
739
740 const TargetInfo &getTargetInfo() const { return *Target; }
741 const TargetInfo *getAuxTargetInfo() const { return AuxTarget; }
742
743 /// getIntTypeForBitwidth -
744 /// sets integer QualTy according to specified details:
745 /// bitwidth, signed/unsigned.
746 /// Returns empty type if there is no appropriate target types.
747 QualType getIntTypeForBitwidth(unsigned DestWidth,
748 unsigned Signed) const;
749
750 /// getRealTypeForBitwidth -
751 /// sets floating point QualTy according to specified bitwidth.
752 /// Returns empty type if there is no appropriate target types.
753 QualType getRealTypeForBitwidth(unsigned DestWidth, bool ExplicitIEEE) const;
754
755 bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const;
756
757 const LangOptions& getLangOpts() const { return LangOpts; }
758
759 // If this condition is false, typo correction must be performed eagerly
760 // rather than delayed in many places, as it makes use of dependent types.
761 // the condition is false for clang's C-only codepath, as it doesn't support
762 // dependent types yet.
763 bool isDependenceAllowed() const {
764 return LangOpts.CPlusPlus || LangOpts.RecoveryAST;
765 }
766
767 const NoSanitizeList &getNoSanitizeList() const { return *NoSanitizeL; }
768
769 const XRayFunctionFilter &getXRayFilter() const {
770 return *XRayFilter;
771 }
772
773 const ProfileList &getProfileList() const { return *ProfList; }
774
775 DiagnosticsEngine &getDiagnostics() const;
776
777 FullSourceLoc getFullLoc(SourceLocation Loc) const {
778 return FullSourceLoc(Loc,SourceMgr);
779 }
780
781 /// Return the C++ ABI kind that should be used. The C++ ABI can be overriden
782 /// at compile time with `-fc++-abi=`. If this is not provided, we instead use
783 /// the default ABI set by the target.
784 TargetCXXABI::Kind getCXXABIKind() const;
785
786 /// All comments in this translation unit.
787 RawCommentList Comments;
788
789 /// True if comments are already loaded from ExternalASTSource.
790 mutable bool CommentsLoaded = false;
791
792 /// Mapping from declaration to directly attached comment.
793 ///
794 /// Raw comments are owned by Comments list. This mapping is populated
795 /// lazily.
796 mutable llvm::DenseMap<const Decl *, const RawComment *> DeclRawComments;
797
798 /// Mapping from canonical declaration to the first redeclaration in chain
799 /// that has a comment attached.
800 ///
801 /// Raw comments are owned by Comments list. This mapping is populated
802 /// lazily.
803 mutable llvm::DenseMap<const Decl *, const Decl *> RedeclChainComments;
804
805 /// Keeps track of redeclaration chains that don't have any comment attached.
806 /// Mapping from canonical declaration to redeclaration chain that has no
807 /// comments attached to any redeclaration. Specifically it's mapping to
808 /// the last redeclaration we've checked.
809 ///
810 /// Shall not contain declarations that have comments attached to any
811 /// redeclaration in their chain.
812 mutable llvm::DenseMap<const Decl *, const Decl *> CommentlessRedeclChains;
813
814 /// Mapping from declarations to parsed comments attached to any
815 /// redeclaration.
816 mutable llvm::DenseMap<const Decl *, comments::FullComment *> ParsedComments;
817
818 /// Attaches \p Comment to \p OriginalD and to its redeclaration chain
819 /// and removes the redeclaration chain from the set of commentless chains.
820 ///
821 /// Don't do anything if a comment has already been attached to \p OriginalD
822 /// or its redeclaration chain.
823 void cacheRawCommentForDecl(const Decl &OriginalD,
824 const RawComment &Comment) const;
825
826 /// \returns searches \p CommentsInFile for doc comment for \p D.
827 ///
828 /// \p RepresentativeLocForDecl is used as a location for searching doc
829 /// comments. \p CommentsInFile is a mapping offset -> comment of files in the
830 /// same file where \p RepresentativeLocForDecl is.
831 RawComment *getRawCommentForDeclNoCacheImpl(
832 const Decl *D, const SourceLocation RepresentativeLocForDecl,
833 const std::map<unsigned, RawComment *> &CommentsInFile) const;
834
835 /// Return the documentation comment attached to a given declaration,
836 /// without looking into cache.
837 RawComment *getRawCommentForDeclNoCache(const Decl *D) const;
838
839public:
840 void addComment(const RawComment &RC);
841
842 /// Return the documentation comment attached to a given declaration.
843 /// Returns nullptr if no comment is attached.
844 ///
845 /// \param OriginalDecl if not nullptr, is set to declaration AST node that
846 /// had the comment, if the comment we found comes from a redeclaration.
847 const RawComment *
848 getRawCommentForAnyRedecl(const Decl *D,
849 const Decl **OriginalDecl = nullptr) const;
850
851 /// Searches existing comments for doc comments that should be attached to \p
852 /// Decls. If any doc comment is found, it is parsed.
853 ///
854 /// Requirement: All \p Decls are in the same file.
855 ///
856 /// If the last comment in the file is already attached we assume
857 /// there are not comments left to be attached to \p Decls.
858 void attachCommentsToJustParsedDecls(ArrayRef<Decl *> Decls,
859 const Preprocessor *PP);
860
861 /// Return parsed documentation comment attached to a given declaration.
862 /// Returns nullptr if no comment is attached.
863 ///
864 /// \param PP the Preprocessor used with this TU. Could be nullptr if
865 /// preprocessor is not available.
866 comments::FullComment *getCommentForDecl(const Decl *D,
867 const Preprocessor *PP) const;
868
869 /// Return parsed documentation comment attached to a given declaration.
870 /// Returns nullptr if no comment is attached. Does not look at any
871 /// redeclarations of the declaration.
872 comments::FullComment *getLocalCommentForDeclUncached(const Decl *D) const;
873
874 comments::FullComment *cloneFullComment(comments::FullComment *FC,
875 const Decl *D) const;
876
877private:
878 mutable comments::CommandTraits CommentCommandTraits;
879
880 /// Iterator that visits import declarations.
881 class import_iterator {
882 ImportDecl *Import = nullptr;
883
884 public:
885 using value_type = ImportDecl *;
886 using reference = ImportDecl *;
887 using pointer = ImportDecl *;
888 using difference_type = int;
889 using iterator_category = std::forward_iterator_tag;
890
891 import_iterator() = default;
892 explicit import_iterator(ImportDecl *Import) : Import(Import) {}
893
894 reference operator*() const { return Import; }
895 pointer operator->() const { return Import; }
896
897 import_iterator &operator++() {
898 Import = ASTContext::getNextLocalImport(Import);
899 return *this;
900 }
901
902 import_iterator operator++(int) {
903 import_iterator Other(*this);
904 ++(*this);
905 return Other;
906 }
907
908 friend bool operator==(import_iterator X, import_iterator Y) {
909 return X.Import == Y.Import;
910 }
911
912 friend bool operator!=(import_iterator X, import_iterator Y) {
913 return X.Import != Y.Import;
914 }
915 };
916
917public:
918 comments::CommandTraits &getCommentCommandTraits() const {
919 return CommentCommandTraits;
920 }
921
922 /// Retrieve the attributes for the given declaration.
923 AttrVec& getDeclAttrs(const Decl *D);
924
925 /// Erase the attributes corresponding to the given declaration.
926 void eraseDeclAttrs(const Decl *D);
927
928 /// If this variable is an instantiated static data member of a
929 /// class template specialization, returns the templated static data member
930 /// from which it was instantiated.
931 // FIXME: Remove ?
932 MemberSpecializationInfo *getInstantiatedFromStaticDataMember(
933 const VarDecl *Var);
934
935 /// Note that the static data member \p Inst is an instantiation of
936 /// the static data member template \p Tmpl of a class template.
937 void setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl,
938 TemplateSpecializationKind TSK,
939 SourceLocation PointOfInstantiation = SourceLocation());
940
941 TemplateOrSpecializationInfo
942 getTemplateOrSpecializationInfo(const VarDecl *Var);
943
944 void setTemplateOrSpecializationInfo(VarDecl *Inst,
945 TemplateOrSpecializationInfo TSI);
946
947 /// If the given using decl \p Inst is an instantiation of
948 /// another (possibly unresolved) using decl, return it.
949 NamedDecl *getInstantiatedFromUsingDecl(NamedDecl *Inst);
950
951 /// Remember that the using decl \p Inst is an instantiation
952 /// of the using decl \p Pattern of a class template.
953 void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern);
954
955 /// If the given using-enum decl \p Inst is an instantiation of
956 /// another using-enum decl, return it.
957 UsingEnumDecl *getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst);
958
959 /// Remember that the using enum decl \p Inst is an instantiation
960 /// of the using enum decl \p Pattern of a class template.
961 void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst,
962 UsingEnumDecl *Pattern);
963
964 UsingShadowDecl *getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst);
965 void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst,
966 UsingShadowDecl *Pattern);
967
968 FieldDecl *getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field);
969
970 void setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, FieldDecl *Tmpl);
971
972 // Access to the set of methods overridden by the given C++ method.
973 using overridden_cxx_method_iterator = CXXMethodVector::const_iterator;
974 overridden_cxx_method_iterator
975 overridden_methods_begin(const CXXMethodDecl *Method) const;
976
977 overridden_cxx_method_iterator
978 overridden_methods_end(const CXXMethodDecl *Method) const;
979
980 unsigned overridden_methods_size(const CXXMethodDecl *Method) const;
981
982 using overridden_method_range =
983 llvm::iterator_range<overridden_cxx_method_iterator>;
984
985 overridden_method_range overridden_methods(const CXXMethodDecl *Method) const;
986
987 /// Note that the given C++ \p Method overrides the given \p
988 /// Overridden method.
989 void addOverriddenMethod(const CXXMethodDecl *Method,
990 const CXXMethodDecl *Overridden);
991
992 /// Return C++ or ObjC overridden methods for the given \p Method.
993 ///
994 /// An ObjC method is considered to override any method in the class's
995 /// base classes, its protocols, or its categories' protocols, that has
996 /// the same selector and is of the same kind (class or instance).
997 /// A method in an implementation is not considered as overriding the same
998 /// method in the interface or its categories.
999 void getOverriddenMethods(
1000 const NamedDecl *Method,
1001 SmallVectorImpl<const NamedDecl *> &Overridden) const;
1002
1003 /// Notify the AST context that a new import declaration has been
1004 /// parsed or implicitly created within this translation unit.
1005 void addedLocalImportDecl(ImportDecl *Import);
1006
1007 static ImportDecl *getNextLocalImport(ImportDecl *Import) {
1008 return Import->getNextLocalImport();
1009 }
1010
1011 using import_range = llvm::iterator_range<import_iterator>;
1012
1013 import_range local_imports() const {
1014 return import_range(import_iterator(FirstLocalImport), import_iterator());
1015 }
1016
1017 Decl *getPrimaryMergedDecl(Decl *D) {
1018 Decl *Result = MergedDecls.lookup(D);
1019 return Result ? Result : D;
1020 }
1021 void setPrimaryMergedDecl(Decl *D, Decl *Primary) {
1022 MergedDecls[D] = Primary;
1023 }
1024
1025 /// Note that the definition \p ND has been merged into module \p M,
1026 /// and should be visible whenever \p M is visible.
1027 void mergeDefinitionIntoModule(NamedDecl *ND, Module *M,
1028 bool NotifyListeners = true);
1029
1030 /// Clean up the merged definition list. Call this if you might have
1031 /// added duplicates into the list.
1032 void deduplicateMergedDefinitonsFor(NamedDecl *ND);
1033
1034 /// Get the additional modules in which the definition \p Def has
1035 /// been merged.
1036 ArrayRef<Module*> getModulesWithMergedDefinition(const NamedDecl *Def);
1037
1038 /// Add a declaration to the list of declarations that are initialized
1039 /// for a module. This will typically be a global variable (with internal
1040 /// linkage) that runs module initializers, such as the iostream initializer,
1041 /// or an ImportDecl nominating another module that has initializers.
1042 void addModuleInitializer(Module *M, Decl *Init);
1043
1044 void addLazyModuleInitializers(Module *M, ArrayRef<uint32_t> IDs);
1045
1046 /// Get the initializations to perform when importing a module, if any.
1047 ArrayRef<Decl*> getModuleInitializers(Module *M);
1048
1049 TranslationUnitDecl *getTranslationUnitDecl() const {
1050 return TUDecl->getMostRecentDecl();
1051 }
1052 void addTranslationUnitDecl() {
1053 assert(!TUDecl || TUKind == TU_Incremental)(static_cast<void> (0));
1054 TranslationUnitDecl *NewTUDecl = TranslationUnitDecl::Create(*this);
1055 if (TraversalScope.empty() || TraversalScope.back() == TUDecl)
1056 TraversalScope = {NewTUDecl};
1057 if (TUDecl)
1058 NewTUDecl->setPreviousDecl(TUDecl);
1059 TUDecl = NewTUDecl;
1060 }
1061
1062 ExternCContextDecl *getExternCContextDecl() const;
1063 BuiltinTemplateDecl *getMakeIntegerSeqDecl() const;
1064 BuiltinTemplateDecl *getTypePackElementDecl() const;
1065
1066 // Builtin Types.
1067 CanQualType VoidTy;
1068 CanQualType BoolTy;
1069 CanQualType CharTy;
1070 CanQualType WCharTy; // [C++ 3.9.1p5].
1071 CanQualType WideCharTy; // Same as WCharTy in C++, integer type in C99.
1072 CanQualType WIntTy; // [C99 7.24.1], integer type unchanged by default promotions.
1073 CanQualType Char8Ty; // [C++20 proposal]
1074 CanQualType Char16Ty; // [C++0x 3.9.1p5], integer type in C99.
1075 CanQualType Char32Ty; // [C++0x 3.9.1p5], integer type in C99.
1076 CanQualType SignedCharTy, ShortTy, IntTy, LongTy, LongLongTy, Int128Ty;
1077 CanQualType UnsignedCharTy, UnsignedShortTy, UnsignedIntTy, UnsignedLongTy;
1078 CanQualType UnsignedLongLongTy, UnsignedInt128Ty;
1079 CanQualType FloatTy, DoubleTy, LongDoubleTy, Float128Ty;
1080 CanQualType ShortAccumTy, AccumTy,
1081 LongAccumTy; // ISO/IEC JTC1 SC22 WG14 N1169 Extension
1082 CanQualType UnsignedShortAccumTy, UnsignedAccumTy, UnsignedLongAccumTy;
1083 CanQualType ShortFractTy, FractTy, LongFractTy;
1084 CanQualType UnsignedShortFractTy, UnsignedFractTy, UnsignedLongFractTy;
1085 CanQualType SatShortAccumTy, SatAccumTy, SatLongAccumTy;
1086 CanQualType SatUnsignedShortAccumTy, SatUnsignedAccumTy,
1087 SatUnsignedLongAccumTy;
1088 CanQualType SatShortFractTy, SatFractTy, SatLongFractTy;
1089 CanQualType SatUnsignedShortFractTy, SatUnsignedFractTy,
1090 SatUnsignedLongFractTy;
1091 CanQualType HalfTy; // [OpenCL 6.1.1.1], ARM NEON
1092 CanQualType BFloat16Ty;
1093 CanQualType Float16Ty; // C11 extension ISO/IEC TS 18661-3
1094 CanQualType FloatComplexTy, DoubleComplexTy, LongDoubleComplexTy;
1095 CanQualType Float128ComplexTy;
1096 CanQualType VoidPtrTy, NullPtrTy;
1097 CanQualType DependentTy, OverloadTy, BoundMemberTy, UnknownAnyTy;
1098 CanQualType BuiltinFnTy;
1099 CanQualType PseudoObjectTy, ARCUnbridgedCastTy;
1100 CanQualType ObjCBuiltinIdTy, ObjCBuiltinClassTy, ObjCBuiltinSelTy;
1101 CanQualType ObjCBuiltinBoolTy;
1102#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1103 CanQualType SingletonId;
1104#include "clang/Basic/OpenCLImageTypes.def"
1105 CanQualType OCLSamplerTy, OCLEventTy, OCLClkEventTy;
1106 CanQualType OCLQueueTy, OCLReserveIDTy;
1107 CanQualType IncompleteMatrixIdxTy;
1108 CanQualType OMPArraySectionTy, OMPArrayShapingTy, OMPIteratorTy;
1109#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1110 CanQualType Id##Ty;
1111#include "clang/Basic/OpenCLExtensionTypes.def"
1112#define SVE_TYPE(Name, Id, SingletonId) \
1113 CanQualType SingletonId;
1114#include "clang/Basic/AArch64SVEACLETypes.def"
1115#define PPC_VECTOR_TYPE(Name, Id, Size) \
1116 CanQualType Id##Ty;
1117#include "clang/Basic/PPCTypes.def"
1118#define RVV_TYPE(Name, Id, SingletonId) \
1119 CanQualType SingletonId;
1120#include "clang/Basic/RISCVVTypes.def"
1121
1122 // Types for deductions in C++0x [stmt.ranged]'s desugaring. Built on demand.
1123 mutable QualType AutoDeductTy; // Deduction against 'auto'.
1124 mutable QualType AutoRRefDeductTy; // Deduction against 'auto &&'.
1125
1126 // Decl used to help define __builtin_va_list for some targets.
1127 // The decl is built when constructing 'BuiltinVaListDecl'.
1128 mutable Decl *VaListTagDecl = nullptr;
1129
1130 // Implicitly-declared type 'struct _GUID'.
1131 mutable TagDecl *MSGuidTagDecl = nullptr;
1132
1133 /// Keep track of CUDA/HIP device-side variables ODR-used by host code.
1134 llvm::DenseSet<const VarDecl *> CUDADeviceVarODRUsedByHost;
1135
1136 ASTContext(LangOptions &LOpts, SourceManager &SM, IdentifierTable &idents,
1137 SelectorTable &sels, Builtin::Context &builtins,
1138 TranslationUnitKind TUKind);
1139 ASTContext(const ASTContext &) = delete;
1140 ASTContext &operator=(const ASTContext &) = delete;
1141 ~ASTContext();
1142
1143 /// Attach an external AST source to the AST context.
1144 ///
1145 /// The external AST source provides the ability to load parts of
1146 /// the abstract syntax tree as needed from some external storage,
1147 /// e.g., a precompiled header.
1148 void setExternalSource(IntrusiveRefCntPtr<ExternalASTSource> Source);
1149
1150 /// Retrieve a pointer to the external AST source associated
1151 /// with this AST context, if any.
1152 ExternalASTSource *getExternalSource() const {
1153 return ExternalSource.get();
1154 }
1155
1156 /// Attach an AST mutation listener to the AST context.
1157 ///
1158 /// The AST mutation listener provides the ability to track modifications to
1159 /// the abstract syntax tree entities committed after they were initially
1160 /// created.
1161 void setASTMutationListener(ASTMutationListener *Listener) {
1162 this->Listener = Listener;
1163 }
1164
1165 /// Retrieve a pointer to the AST mutation listener associated
1166 /// with this AST context, if any.
1167 ASTMutationListener *getASTMutationListener() const { return Listener; }
1168
1169 void PrintStats() const;
1170 const SmallVectorImpl<Type *>& getTypes() const { return Types; }
1171
1172 BuiltinTemplateDecl *buildBuiltinTemplateDecl(BuiltinTemplateKind BTK,
1173 const IdentifierInfo *II) const;
1174
1175 /// Create a new implicit TU-level CXXRecordDecl or RecordDecl
1176 /// declaration.
1177 RecordDecl *buildImplicitRecord(StringRef Name,
1178 RecordDecl::TagKind TK = TTK_Struct) const;
1179
1180 /// Create a new implicit TU-level typedef declaration.
1181 TypedefDecl *buildImplicitTypedef(QualType T, StringRef Name) const;
1182
1183 /// Retrieve the declaration for the 128-bit signed integer type.
1184 TypedefDecl *getInt128Decl() const;
1185
1186 /// Retrieve the declaration for the 128-bit unsigned integer type.
1187 TypedefDecl *getUInt128Decl() const;
1188
1189 //===--------------------------------------------------------------------===//
1190 // Type Constructors
1191 //===--------------------------------------------------------------------===//
1192
1193private:
1194 /// Return a type with extended qualifiers.
1195 QualType getExtQualType(const Type *Base, Qualifiers Quals) const;
1196
1197 QualType getTypeDeclTypeSlow(const TypeDecl *Decl) const;
1198
1199 QualType getPipeType(QualType T, bool ReadOnly) const;
1200
1201public:
1202 /// Return the uniqued reference to the type for an address space
1203 /// qualified type with the specified type and address space.
1204 ///
1205 /// The resulting type has a union of the qualifiers from T and the address
1206 /// space. If T already has an address space specifier, it is silently
1207 /// replaced.
1208 QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const;
1209
1210 /// Remove any existing address space on the type and returns the type
1211 /// with qualifiers intact (or that's the idea anyway)
1212 ///
1213 /// The return type should be T with all prior qualifiers minus the address
1214 /// space.
1215 QualType removeAddrSpaceQualType(QualType T) const;
1216
1217 /// Apply Objective-C protocol qualifiers to the given type.
1218 /// \param allowOnPointerType specifies if we can apply protocol
1219 /// qualifiers on ObjCObjectPointerType. It can be set to true when
1220 /// constructing the canonical type of a Objective-C type parameter.
1221 QualType applyObjCProtocolQualifiers(QualType type,
1222 ArrayRef<ObjCProtocolDecl *> protocols, bool &hasError,
1223 bool allowOnPointerType = false) const;
1224
1225 /// Return the uniqued reference to the type for an Objective-C
1226 /// gc-qualified type.
1227 ///
1228 /// The resulting type has a union of the qualifiers from T and the gc
1229 /// attribute.
1230 QualType getObjCGCQualType(QualType T, Qualifiers::GC gcAttr) const;
1231
1232 /// Remove the existing address space on the type if it is a pointer size
1233 /// address space and return the type with qualifiers intact.
1234 QualType removePtrSizeAddrSpace(QualType T) const;
1235
1236 /// Return the uniqued reference to the type for a \c restrict
1237 /// qualified type.
1238 ///
1239 /// The resulting type has a union of the qualifiers from \p T and
1240 /// \c restrict.
1241 QualType getRestrictType(QualType T) const {
1242 return T.withFastQualifiers(Qualifiers::Restrict);
1243 }
1244
1245 /// Return the uniqued reference to the type for a \c volatile
1246 /// qualified type.
1247 ///
1248 /// The resulting type has a union of the qualifiers from \p T and
1249 /// \c volatile.
1250 QualType getVolatileType(QualType T) const {
1251 return T.withFastQualifiers(Qualifiers::Volatile);
1252 }
1253
1254 /// Return the uniqued reference to the type for a \c const
1255 /// qualified type.
1256 ///
1257 /// The resulting type has a union of the qualifiers from \p T and \c const.
1258 ///
1259 /// It can be reasonably expected that this will always be equivalent to
1260 /// calling T.withConst().
1261 QualType getConstType(QualType T) const { return T.withConst(); }
1262
1263 /// Change the ExtInfo on a function type.
1264 const FunctionType *adjustFunctionType(const FunctionType *Fn,
1265 FunctionType::ExtInfo EInfo);
1266
1267 /// Adjust the given function result type.
1268 CanQualType getCanonicalFunctionResultType(QualType ResultType) const;
1269
1270 /// Change the result type of a function type once it is deduced.
1271 void adjustDeducedFunctionResultType(FunctionDecl *FD, QualType ResultType);
1272
1273 /// Get a function type and produce the equivalent function type with the
1274 /// specified exception specification. Type sugar that can be present on a
1275 /// declaration of a function with an exception specification is permitted
1276 /// and preserved. Other type sugar (for instance, typedefs) is not.
1277 QualType getFunctionTypeWithExceptionSpec(
1278 QualType Orig, const FunctionProtoType::ExceptionSpecInfo &ESI);
1279
1280 /// Determine whether two function types are the same, ignoring
1281 /// exception specifications in cases where they're part of the type.
1282 bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U);
1283
1284 /// Change the exception specification on a function once it is
1285 /// delay-parsed, instantiated, or computed.
1286 void adjustExceptionSpec(FunctionDecl *FD,
1287 const FunctionProtoType::ExceptionSpecInfo &ESI,
1288 bool AsWritten = false);
1289
1290 /// Get a function type and produce the equivalent function type where
1291 /// pointer size address spaces in the return type and parameter tyeps are
1292 /// replaced with the default address space.
1293 QualType getFunctionTypeWithoutPtrSizes(QualType T);
1294
1295 /// Determine whether two function types are the same, ignoring pointer sizes
1296 /// in the return type and parameter types.
1297 bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U);
1298
1299 /// Return the uniqued reference to the type for a complex
1300 /// number with the specified element type.
1301 QualType getComplexType(QualType T) const;
1302 CanQualType getComplexType(CanQualType T) const {
1303 return CanQualType::CreateUnsafe(getComplexType((QualType) T));
1304 }
1305
1306 /// Return the uniqued reference to the type for a pointer to
1307 /// the specified type.
1308 QualType getPointerType(QualType T) const;
1309 CanQualType getPointerType(CanQualType T) const {
1310 return CanQualType::CreateUnsafe(getPointerType((QualType) T));
1311 }
1312
1313 /// Return the uniqued reference to a type adjusted from the original
1314 /// type to a new type.
1315 QualType getAdjustedType(QualType Orig, QualType New) const;
1316 CanQualType getAdjustedType(CanQualType Orig, CanQualType New) const {
1317 return CanQualType::CreateUnsafe(
1318 getAdjustedType((QualType)Orig, (QualType)New));
1319 }
1320
1321 /// Return the uniqued reference to the decayed version of the given
1322 /// type. Can only be called on array and function types which decay to
1323 /// pointer types.
1324 QualType getDecayedType(QualType T) const;
1325 CanQualType getDecayedType(CanQualType T) const {
1326 return CanQualType::CreateUnsafe(getDecayedType((QualType) T));
1327 }
1328
1329 /// Return the uniqued reference to the atomic type for the specified
1330 /// type.
1331 QualType getAtomicType(QualType T) const;
1332
1333 /// Return the uniqued reference to the type for a block of the
1334 /// specified type.
1335 QualType getBlockPointerType(QualType T) const;
1336
1337 /// Gets the struct used to keep track of the descriptor for pointer to
1338 /// blocks.
1339 QualType getBlockDescriptorType() const;
1340
1341 /// Return a read_only pipe type for the specified type.
1342 QualType getReadPipeType(QualType T) const;
1343
1344 /// Return a write_only pipe type for the specified type.
1345 QualType getWritePipeType(QualType T) const;
1346
1347 /// Return an extended integer type with the specified signedness and bit
1348 /// count.
1349 QualType getExtIntType(bool Unsigned, unsigned NumBits) const;
1350
1351 /// Return a dependent extended integer type with the specified signedness and
1352 /// bit count.
1353 QualType getDependentExtIntType(bool Unsigned, Expr *BitsExpr) const;
1354
1355 /// Gets the struct used to keep track of the extended descriptor for
1356 /// pointer to blocks.
1357 QualType getBlockDescriptorExtendedType() const;
1358
1359 /// Map an AST Type to an OpenCLTypeKind enum value.
1360 OpenCLTypeKind getOpenCLTypeKind(const Type *T) const;
1361
1362 /// Get address space for OpenCL type.
1363 LangAS getOpenCLTypeAddrSpace(const Type *T) const;
1364
1365 void setcudaConfigureCallDecl(FunctionDecl *FD) {
1366 cudaConfigureCallDecl = FD;
1367 }
1368
1369 FunctionDecl *getcudaConfigureCallDecl() {
1370 return cudaConfigureCallDecl;
1371 }
1372
1373 /// Returns true iff we need copy/dispose helpers for the given type.
1374 bool BlockRequiresCopying(QualType Ty, const VarDecl *D);
1375
1376 /// Returns true, if given type has a known lifetime. HasByrefExtendedLayout
1377 /// is set to false in this case. If HasByrefExtendedLayout returns true,
1378 /// byref variable has extended lifetime.
1379 bool getByrefLifetime(QualType Ty,
1380 Qualifiers::ObjCLifetime &Lifetime,
1381 bool &HasByrefExtendedLayout) const;
1382
1383 /// Return the uniqued reference to the type for an lvalue reference
1384 /// to the specified type.
1385 QualType getLValueReferenceType(QualType T, bool SpelledAsLValue = true)
1386 const;
1387
1388 /// Return the uniqued reference to the type for an rvalue reference
1389 /// to the specified type.
1390 QualType getRValueReferenceType(QualType T) const;
1391
1392 /// Return the uniqued reference to the type for a member pointer to
1393 /// the specified type in the specified class.
1394 ///
1395 /// The class \p Cls is a \c Type because it could be a dependent name.
1396 QualType getMemberPointerType(QualType T, const Type *Cls) const;
1397
1398 /// Return a non-unique reference to the type for a variable array of
1399 /// the specified element type.
1400 QualType getVariableArrayType(QualType EltTy, Expr *NumElts,
1401 ArrayType::ArraySizeModifier ASM,
1402 unsigned IndexTypeQuals,
1403 SourceRange Brackets) const;
1404
1405 /// Return a non-unique reference to the type for a dependently-sized
1406 /// array of the specified element type.
1407 ///
1408 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1409 /// point.
1410 QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts,
1411 ArrayType::ArraySizeModifier ASM,
1412 unsigned IndexTypeQuals,
1413 SourceRange Brackets) const;
1414
1415 /// Return a unique reference to the type for an incomplete array of
1416 /// the specified element type.
1417 QualType getIncompleteArrayType(QualType EltTy,
1418 ArrayType::ArraySizeModifier ASM,
1419 unsigned IndexTypeQuals) const;
1420
1421 /// Return the unique reference to the type for a constant array of
1422 /// the specified element type.
1423 QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize,
1424 const Expr *SizeExpr,
1425 ArrayType::ArraySizeModifier ASM,
1426 unsigned IndexTypeQuals) const;
1427
1428 /// Return a type for a constant array for a string literal of the
1429 /// specified element type and length.
1430 QualType getStringLiteralArrayType(QualType EltTy, unsigned Length) const;
1431
1432 /// Returns a vla type where known sizes are replaced with [*].
1433 QualType getVariableArrayDecayedType(QualType Ty) const;
1434
1435 // Convenience struct to return information about a builtin vector type.
1436 struct BuiltinVectorTypeInfo {
1437 QualType ElementType;
1438 llvm::ElementCount EC;
1439 unsigned NumVectors;
1440 BuiltinVectorTypeInfo(QualType ElementType, llvm::ElementCount EC,
1441 unsigned NumVectors)
1442 : ElementType(ElementType), EC(EC), NumVectors(NumVectors) {}
1443 };
1444
1445 /// Returns the element type, element count and number of vectors
1446 /// (in case of tuple) for a builtin vector type.
1447 BuiltinVectorTypeInfo
1448 getBuiltinVectorTypeInfo(const BuiltinType *VecTy) const;
1449
1450 /// Return the unique reference to a scalable vector type of the specified
1451 /// element type and scalable number of elements.
1452 ///
1453 /// \pre \p EltTy must be a built-in type.
1454 QualType getScalableVectorType(QualType EltTy, unsigned NumElts) const;
1455
1456 /// Return the unique reference to a vector type of the specified
1457 /// element type and size.
1458 ///
1459 /// \pre \p VectorType must be a built-in type.
1460 QualType getVectorType(QualType VectorType, unsigned NumElts,
1461 VectorType::VectorKind VecKind) const;
1462 /// Return the unique reference to the type for a dependently sized vector of
1463 /// the specified element type.
1464 QualType getDependentVectorType(QualType VectorType, Expr *SizeExpr,
1465 SourceLocation AttrLoc,
1466 VectorType::VectorKind VecKind) const;
1467
1468 /// Return the unique reference to an extended vector type
1469 /// of the specified element type and size.
1470 ///
1471 /// \pre \p VectorType must be a built-in type.
1472 QualType getExtVectorType(QualType VectorType, unsigned NumElts) const;
1473
1474 /// \pre Return a non-unique reference to the type for a dependently-sized
1475 /// vector of the specified element type.
1476 ///
1477 /// FIXME: We will need these to be uniqued, or at least comparable, at some
1478 /// point.
1479 QualType getDependentSizedExtVectorType(QualType VectorType,
1480 Expr *SizeExpr,
1481 SourceLocation AttrLoc) const;
1482
1483 /// Return the unique reference to the matrix type of the specified element
1484 /// type and size
1485 ///
1486 /// \pre \p ElementType must be a valid matrix element type (see
1487 /// MatrixType::isValidElementType).
1488 QualType getConstantMatrixType(QualType ElementType, unsigned NumRows,
1489 unsigned NumColumns) const;
1490
1491 /// Return the unique reference to the matrix type of the specified element
1492 /// type and size
1493 QualType getDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
1494 Expr *ColumnExpr,
1495 SourceLocation AttrLoc) const;
1496
1497 QualType getDependentAddressSpaceType(QualType PointeeType,
1498 Expr *AddrSpaceExpr,
1499 SourceLocation AttrLoc) const;
1500
1501 /// Return a K&R style C function type like 'int()'.
1502 QualType getFunctionNoProtoType(QualType ResultTy,
1503 const FunctionType::ExtInfo &Info) const;
1504
1505 QualType getFunctionNoProtoType(QualType ResultTy) const {
1506 return getFunctionNoProtoType(ResultTy, FunctionType::ExtInfo());
1507 }
1508
1509 /// Return a normal function type with a typed argument list.
1510 QualType getFunctionType(QualType ResultTy, ArrayRef<QualType> Args,
1511 const FunctionProtoType::ExtProtoInfo &EPI) const {
1512 return getFunctionTypeInternal(ResultTy, Args, EPI, false);
1513 }
1514
1515 QualType adjustStringLiteralBaseType(QualType StrLTy) const;
1516
1517private:
1518 /// Return a normal function type with a typed argument list.
1519 QualType getFunctionTypeInternal(QualType ResultTy, ArrayRef<QualType> Args,
1520 const FunctionProtoType::ExtProtoInfo &EPI,
1521 bool OnlyWantCanonical) const;
1522
1523public:
1524 /// Return the unique reference to the type for the specified type
1525 /// declaration.
1526 QualType getTypeDeclType(const TypeDecl *Decl,
1527 const TypeDecl *PrevDecl = nullptr) const {
1528 assert(Decl && "Passed null for Decl param")(static_cast<void> (0));
1529 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0);
64
Access to field 'TypeForDecl' results in a dereference of a null pointer (loaded from variable 'Decl')
1530
1531 if (PrevDecl) {
1532 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl")(static_cast<void> (0));
1533 Decl->TypeForDecl = PrevDecl->TypeForDecl;
1534 return QualType(PrevDecl->TypeForDecl, 0);
1535 }
1536
1537 return getTypeDeclTypeSlow(Decl);
1538 }
1539
1540 /// Return the unique reference to the type for the specified
1541 /// typedef-name decl.
1542 QualType getTypedefType(const TypedefNameDecl *Decl,
1543 QualType Underlying = QualType()) const;
1544
1545 QualType getRecordType(const RecordDecl *Decl) const;
1546
1547 QualType getEnumType(const EnumDecl *Decl) const;
1548
1549 QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const;
1550
1551 QualType getAttributedType(attr::Kind attrKind,
1552 QualType modifiedType,
1553 QualType equivalentType);
1554
1555 QualType getSubstTemplateTypeParmType(const TemplateTypeParmType *Replaced,
1556 QualType Replacement) const;
1557 QualType getSubstTemplateTypeParmPackType(
1558 const TemplateTypeParmType *Replaced,
1559 const TemplateArgument &ArgPack);
1560
1561 QualType
1562 getTemplateTypeParmType(unsigned Depth, unsigned Index,
1563 bool ParameterPack,
1564 TemplateTypeParmDecl *ParmDecl = nullptr) const;
1565
1566 QualType getTemplateSpecializationType(TemplateName T,
1567 ArrayRef<TemplateArgument> Args,
1568 QualType Canon = QualType()) const;
1569
1570 QualType
1571 getCanonicalTemplateSpecializationType(TemplateName T,
1572 ArrayRef<TemplateArgument> Args) const;
1573
1574 QualType getTemplateSpecializationType(TemplateName T,
1575 const TemplateArgumentListInfo &Args,
1576 QualType Canon = QualType()) const;
1577
1578 TypeSourceInfo *
1579 getTemplateSpecializationTypeInfo(TemplateName T, SourceLocation TLoc,
1580 const TemplateArgumentListInfo &Args,
1581 QualType Canon = QualType()) const;
1582
1583 QualType getParenType(QualType NamedType) const;
1584
1585 QualType getMacroQualifiedType(QualType UnderlyingTy,
1586 const IdentifierInfo *MacroII) const;
1587
1588 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
1589 NestedNameSpecifier *NNS, QualType NamedType,
1590 TagDecl *OwnedTagDecl = nullptr) const;
1591 QualType getDependentNameType(ElaboratedTypeKeyword Keyword,
1592 NestedNameSpecifier *NNS,
1593 const IdentifierInfo *Name,
1594 QualType Canon = QualType()) const;
1595
1596 QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
1597 NestedNameSpecifier *NNS,
1598 const IdentifierInfo *Name,
1599 const TemplateArgumentListInfo &Args) const;
1600 QualType getDependentTemplateSpecializationType(
1601 ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
1602 const IdentifierInfo *Name, ArrayRef<TemplateArgument> Args) const;
1603
1604 TemplateArgument getInjectedTemplateArg(NamedDecl *ParamDecl);
1605
1606 /// Get a template argument list with one argument per template parameter
1607 /// in a template parameter list, such as for the injected class name of
1608 /// a class template.
1609 void getInjectedTemplateArgs(const TemplateParameterList *Params,
1610 SmallVectorImpl<TemplateArgument> &Args);
1611
1612 /// Form a pack expansion type with the given pattern.
1613 /// \param NumExpansions The number of expansions for the pack, if known.
1614 /// \param ExpectPackInType If \c false, we should not expect \p Pattern to
1615 /// contain an unexpanded pack. This only makes sense if the pack
1616 /// expansion is used in a context where the arity is inferred from
1617 /// elsewhere, such as if the pattern contains a placeholder type or
1618 /// if this is the canonical type of another pack expansion type.
1619 QualType getPackExpansionType(QualType Pattern,
1620 Optional<unsigned> NumExpansions,
1621 bool ExpectPackInType = true);
1622
1623 QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl,
1624 ObjCInterfaceDecl *PrevDecl = nullptr) const;
1625
1626 /// Legacy interface: cannot provide type arguments or __kindof.
1627 QualType getObjCObjectType(QualType Base,
1628 ObjCProtocolDecl * const *Protocols,
1629 unsigned NumProtocols) const;
1630
1631 QualType getObjCObjectType(QualType Base,
1632 ArrayRef<QualType> typeArgs,
1633 ArrayRef<ObjCProtocolDecl *> protocols,
1634 bool isKindOf) const;
1635
1636 QualType getObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1637 ArrayRef<ObjCProtocolDecl *> protocols) const;
1638 void adjustObjCTypeParamBoundType(const ObjCTypeParamDecl *Orig,
1639 ObjCTypeParamDecl *New) const;
1640
1641 bool ObjCObjectAdoptsQTypeProtocols(QualType QT, ObjCInterfaceDecl *Decl);
1642
1643 /// QIdProtocolsAdoptObjCObjectProtocols - Checks that protocols in
1644 /// QT's qualified-id protocol list adopt all protocols in IDecl's list
1645 /// of protocols.
1646 bool QIdProtocolsAdoptObjCObjectProtocols(QualType QT,
1647 ObjCInterfaceDecl *IDecl);
1648
1649 /// Return a ObjCObjectPointerType type for the given ObjCObjectType.
1650 QualType getObjCObjectPointerType(QualType OIT) const;
1651
1652 /// GCC extension.
1653 QualType getTypeOfExprType(Expr *e) const;
1654 QualType getTypeOfType(QualType t) const;
1655
1656 QualType getReferenceQualifiedType(const Expr *e) const;
1657
1658 /// C++11 decltype.
1659 QualType getDecltypeType(Expr *e, QualType UnderlyingType) const;
1660
1661 /// Unary type transforms
1662 QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType,
1663 UnaryTransformType::UTTKind UKind) const;
1664
1665 /// C++11 deduced auto type.
1666 QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword,
1667 bool IsDependent, bool IsPack = false,
1668 ConceptDecl *TypeConstraintConcept = nullptr,
1669 ArrayRef<TemplateArgument> TypeConstraintArgs ={}) const;
1670
1671 /// C++11 deduction pattern for 'auto' type.
1672 QualType getAutoDeductType() const;
1673
1674 /// C++11 deduction pattern for 'auto &&' type.
1675 QualType getAutoRRefDeductType() const;
1676
1677 /// C++17 deduced class template specialization type.
1678 QualType getDeducedTemplateSpecializationType(TemplateName Template,
1679 QualType DeducedType,
1680 bool IsDependent) const;
1681
1682 /// Return the unique reference to the type for the specified TagDecl
1683 /// (struct/union/class/enum) decl.
1684 QualType getTagDeclType(const TagDecl *Decl) const;
1685
1686 /// Return the unique type for "size_t" (C99 7.17), defined in
1687 /// <stddef.h>.
1688 ///
1689 /// The sizeof operator requires this (C99 6.5.3.4p4).
1690 CanQualType getSizeType() const;
1691
1692 /// Return the unique signed counterpart of
1693 /// the integer type corresponding to size_t.
1694 CanQualType getSignedSizeType() const;
1695
1696 /// Return the unique type for "intmax_t" (C99 7.18.1.5), defined in
1697 /// <stdint.h>.
1698 CanQualType getIntMaxType() const;
1699
1700 /// Return the unique type for "uintmax_t" (C99 7.18.1.5), defined in
1701 /// <stdint.h>.
1702 CanQualType getUIntMaxType() const;
1703
1704 /// Return the unique wchar_t type available in C++ (and available as
1705 /// __wchar_t as a Microsoft extension).
1706 QualType getWCharType() const { return WCharTy; }
1707
1708 /// Return the type of wide characters. In C++, this returns the
1709 /// unique wchar_t type. In C99, this returns a type compatible with the type
1710 /// defined in <stddef.h> as defined by the target.
1711 QualType getWideCharType() const { return WideCharTy; }
1712
1713 /// Return the type of "signed wchar_t".
1714 ///
1715 /// Used when in C++, as a GCC extension.
1716 QualType getSignedWCharType() const;
1717
1718 /// Return the type of "unsigned wchar_t".
1719 ///
1720 /// Used when in C++, as a GCC extension.
1721 QualType getUnsignedWCharType() const;
1722
1723 /// In C99, this returns a type compatible with the type
1724 /// defined in <stddef.h> as defined by the target.
1725 QualType getWIntType() const { return WIntTy; }
1726
1727 /// Return a type compatible with "intptr_t" (C99 7.18.1.4),
1728 /// as defined by the target.
1729 QualType getIntPtrType() const;
1730
1731 /// Return a type compatible with "uintptr_t" (C99 7.18.1.4),
1732 /// as defined by the target.
1733 QualType getUIntPtrType() const;
1734
1735 /// Return the unique type for "ptrdiff_t" (C99 7.17) defined in
1736 /// <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9).
1737 QualType getPointerDiffType() const;
1738
1739 /// Return the unique unsigned counterpart of "ptrdiff_t"
1740 /// integer type. The standard (C11 7.21.6.1p7) refers to this type
1741 /// in the definition of %tu format specifier.
1742 QualType getUnsignedPointerDiffType() const;
1743
1744 /// Return the unique type for "pid_t" defined in
1745 /// <sys/types.h>. We need this to compute the correct type for vfork().
1746 QualType getProcessIDType() const;
1747
1748 /// Return the C structure type used to represent constant CFStrings.
1749 QualType getCFConstantStringType() const;
1750
1751 /// Returns the C struct type for objc_super
1752 QualType getObjCSuperType() const;
1753 void setObjCSuperType(QualType ST) { ObjCSuperType = ST; }
1754
1755 /// Get the structure type used to representation CFStrings, or NULL
1756 /// if it hasn't yet been built.
1757 QualType getRawCFConstantStringType() const {
1758 if (CFConstantStringTypeDecl)
1759 return getTypedefType(CFConstantStringTypeDecl);
1760 return QualType();
1761 }
1762 void setCFConstantStringType(QualType T);
1763 TypedefDecl *getCFConstantStringDecl() const;
1764 RecordDecl *getCFConstantStringTagDecl() const;
1765
1766 // This setter/getter represents the ObjC type for an NSConstantString.
1767 void setObjCConstantStringInterface(ObjCInterfaceDecl *Decl);
1768 QualType getObjCConstantStringInterface() const {
1769 return ObjCConstantStringType;
1770 }
1771
1772 QualType getObjCNSStringType() const {
1773 return ObjCNSStringType;
1774 }
1775
1776 void setObjCNSStringType(QualType T) {
1777 ObjCNSStringType = T;
1778 }
1779
1780 /// Retrieve the type that \c id has been defined to, which may be
1781 /// different from the built-in \c id if \c id has been typedef'd.
1782 QualType getObjCIdRedefinitionType() const {
1783 if (ObjCIdRedefinitionType.isNull())
1784 return getObjCIdType();
1785 return ObjCIdRedefinitionType;
1786 }
1787
1788 /// Set the user-written type that redefines \c id.
1789 void setObjCIdRedefinitionType(QualType RedefType) {
1790 ObjCIdRedefinitionType = RedefType;
1791 }
1792
1793 /// Retrieve the type that \c Class has been defined to, which may be
1794 /// different from the built-in \c Class if \c Class has been typedef'd.
1795 QualType getObjCClassRedefinitionType() const {
1796 if (ObjCClassRedefinitionType.isNull())
1797 return getObjCClassType();
1798 return ObjCClassRedefinitionType;
1799 }
1800
1801 /// Set the user-written type that redefines 'SEL'.
1802 void setObjCClassRedefinitionType(QualType RedefType) {
1803 ObjCClassRedefinitionType = RedefType;
1804 }
1805
1806 /// Retrieve the type that 'SEL' has been defined to, which may be
1807 /// different from the built-in 'SEL' if 'SEL' has been typedef'd.
1808 QualType getObjCSelRedefinitionType() const {
1809 if (ObjCSelRedefinitionType.isNull())
1810 return getObjCSelType();
1811 return ObjCSelRedefinitionType;
1812 }
1813
1814 /// Set the user-written type that redefines 'SEL'.
1815 void setObjCSelRedefinitionType(QualType RedefType) {
1816 ObjCSelRedefinitionType = RedefType;
1817 }
1818
1819 /// Retrieve the identifier 'NSObject'.
1820 IdentifierInfo *getNSObjectName() const {
1821 if (!NSObjectName) {
1822 NSObjectName = &Idents.get("NSObject");
1823 }
1824
1825 return NSObjectName;
1826 }
1827
1828 /// Retrieve the identifier 'NSCopying'.
1829 IdentifierInfo *getNSCopyingName() {
1830 if (!NSCopyingName) {
1831 NSCopyingName = &Idents.get("NSCopying");
1832 }
1833
1834 return NSCopyingName;
1835 }
1836
1837 CanQualType getNSUIntegerType() const;
1838
1839 CanQualType getNSIntegerType() const;
1840
1841 /// Retrieve the identifier 'bool'.
1842 IdentifierInfo *getBoolName() const {
1843 if (!BoolName)
1844 BoolName = &Idents.get("bool");
1845 return BoolName;
1846 }
1847
1848 IdentifierInfo *getMakeIntegerSeqName() const {
1849 if (!MakeIntegerSeqName)
1850 MakeIntegerSeqName = &Idents.get("__make_integer_seq");
1851 return MakeIntegerSeqName;
1852 }
1853
1854 IdentifierInfo *getTypePackElementName() const {
1855 if (!TypePackElementName)
1856 TypePackElementName = &Idents.get("__type_pack_element");
1857 return TypePackElementName;
1858 }
1859
1860 /// Retrieve the Objective-C "instancetype" type, if already known;
1861 /// otherwise, returns a NULL type;
1862 QualType getObjCInstanceType() {
1863 return getTypeDeclType(getObjCInstanceTypeDecl());
1864 }
1865
1866 /// Retrieve the typedef declaration corresponding to the Objective-C
1867 /// "instancetype" type.
1868 TypedefDecl *getObjCInstanceTypeDecl();
1869
1870 /// Set the type for the C FILE type.
1871 void setFILEDecl(TypeDecl *FILEDecl) { this->FILEDecl = FILEDecl; }
1872
1873 /// Retrieve the C FILE type.
1874 QualType getFILEType() const {
1875 if (FILEDecl)
1876 return getTypeDeclType(FILEDecl);
1877 return QualType();
1878 }
1879
1880 /// Set the type for the C jmp_buf type.
1881 void setjmp_bufDecl(TypeDecl *jmp_bufDecl) {
1882 this->jmp_bufDecl = jmp_bufDecl;
1883 }
1884
1885 /// Retrieve the C jmp_buf type.
1886 QualType getjmp_bufType() const {
1887 if (jmp_bufDecl)
1888 return getTypeDeclType(jmp_bufDecl);
1889 return QualType();
1890 }
1891
1892 /// Set the type for the C sigjmp_buf type.
1893 void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl) {
1894 this->sigjmp_bufDecl = sigjmp_bufDecl;
1895 }
1896
1897 /// Retrieve the C sigjmp_buf type.
1898 QualType getsigjmp_bufType() const {
1899 if (sigjmp_bufDecl)
1900 return getTypeDeclType(sigjmp_bufDecl);
1901 return QualType();
1902 }
1903
1904 /// Set the type for the C ucontext_t type.
1905 void setucontext_tDecl(TypeDecl *ucontext_tDecl) {
1906 this->ucontext_tDecl = ucontext_tDecl;
1907 }
1908
1909 /// Retrieve the C ucontext_t type.
1910 QualType getucontext_tType() const {
1911 if (ucontext_tDecl)
1912 return getTypeDeclType(ucontext_tDecl);
1913 return QualType();
1914 }
1915
1916 /// The result type of logical operations, '<', '>', '!=', etc.
1917 QualType getLogicalOperationType() const {
1918 return getLangOpts().CPlusPlus ? BoolTy : IntTy;
1919 }
1920
1921 /// Emit the Objective-CC type encoding for the given type \p T into
1922 /// \p S.
1923 ///
1924 /// If \p Field is specified then record field names are also encoded.
1925 void getObjCEncodingForType(QualType T, std::string &S,
1926 const FieldDecl *Field=nullptr,
1927 QualType *NotEncodedT=nullptr) const;
1928
1929 /// Emit the Objective-C property type encoding for the given
1930 /// type \p T into \p S.
1931 void getObjCEncodingForPropertyType(QualType T, std::string &S) const;
1932
1933 void getLegacyIntegralTypeEncoding(QualType &t) const;
1934
1935 /// Put the string version of the type qualifiers \p QT into \p S.
1936 void getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT,
1937 std::string &S) const;
1938
1939 /// Emit the encoded type for the function \p Decl into \p S.
1940 ///
1941 /// This is in the same format as Objective-C method encodings.
1942 ///
1943 /// \returns true if an error occurred (e.g., because one of the parameter
1944 /// types is incomplete), false otherwise.
1945 std::string getObjCEncodingForFunctionDecl(const FunctionDecl *Decl) const;
1946
1947 /// Emit the encoded type for the method declaration \p Decl into
1948 /// \p S.
1949 std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl,
1950 bool Extended = false) const;
1951
1952 /// Return the encoded type for this block declaration.
1953 std::string getObjCEncodingForBlock(const BlockExpr *blockExpr) const;
1954
1955 /// getObjCEncodingForPropertyDecl - Return the encoded type for
1956 /// this method declaration. If non-NULL, Container must be either
1957 /// an ObjCCategoryImplDecl or ObjCImplementationDecl; it should
1958 /// only be NULL when getting encodings for protocol properties.
1959 std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD,
1960 const Decl *Container) const;
1961
1962 bool ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto,
1963 ObjCProtocolDecl *rProto) const;
1964
1965 ObjCPropertyImplDecl *getObjCPropertyImplDeclForPropertyDecl(
1966 const ObjCPropertyDecl *PD,
1967 const Decl *Container) const;
1968
1969 /// Return the size of type \p T for Objective-C encoding purpose,
1970 /// in characters.
1971 CharUnits getObjCEncodingTypeSize(QualType T) const;
1972
1973 /// Retrieve the typedef corresponding to the predefined \c id type
1974 /// in Objective-C.
1975 TypedefDecl *getObjCIdDecl() const;
1976
1977 /// Represents the Objective-CC \c id type.
1978 ///
1979 /// This is set up lazily, by Sema. \c id is always a (typedef for a)
1980 /// pointer type, a pointer to a struct.
1981 QualType getObjCIdType() const {
1982 return getTypeDeclType(getObjCIdDecl());
1983 }
1984
1985 /// Retrieve the typedef corresponding to the predefined 'SEL' type
1986 /// in Objective-C.
1987 TypedefDecl *getObjCSelDecl() const;
1988
1989 /// Retrieve the type that corresponds to the predefined Objective-C
1990 /// 'SEL' type.
1991 QualType getObjCSelType() const {
1992 return getTypeDeclType(getObjCSelDecl());
1993 }
1994
1995 /// Retrieve the typedef declaration corresponding to the predefined
1996 /// Objective-C 'Class' type.
1997 TypedefDecl *getObjCClassDecl() const;
1998
1999 /// Represents the Objective-C \c Class type.
2000 ///
2001 /// This is set up lazily, by Sema. \c Class is always a (typedef for a)
2002 /// pointer type, a pointer to a struct.
2003 QualType getObjCClassType() const {
2004 return getTypeDeclType(getObjCClassDecl());
2005 }
2006
2007 /// Retrieve the Objective-C class declaration corresponding to
2008 /// the predefined \c Protocol class.
2009 ObjCInterfaceDecl *getObjCProtocolDecl() const;
2010
2011 /// Retrieve declaration of 'BOOL' typedef
2012 TypedefDecl *getBOOLDecl() const {
2013 return BOOLDecl;
2014 }
2015
2016 /// Save declaration of 'BOOL' typedef
2017 void setBOOLDecl(TypedefDecl *TD) {
2018 BOOLDecl = TD;
2019 }
2020
2021 /// type of 'BOOL' type.
2022 QualType getBOOLType() const {
2023 return getTypeDeclType(getBOOLDecl());
2024 }
2025
2026 /// Retrieve the type of the Objective-C \c Protocol class.
2027 QualType getObjCProtoType() const {
2028 return getObjCInterfaceType(getObjCProtocolDecl());
2029 }
2030
2031 /// Retrieve the C type declaration corresponding to the predefined
2032 /// \c __builtin_va_list type.
2033 TypedefDecl *getBuiltinVaListDecl() const;
2034
2035 /// Retrieve the type of the \c __builtin_va_list type.
2036 QualType getBuiltinVaListType() const {
2037 return getTypeDeclType(getBuiltinVaListDecl());
2038 }
2039
2040 /// Retrieve the C type declaration corresponding to the predefined
2041 /// \c __va_list_tag type used to help define the \c __builtin_va_list type
2042 /// for some targets.
2043 Decl *getVaListTagDecl() const;
2044
2045 /// Retrieve the C type declaration corresponding to the predefined
2046 /// \c __builtin_ms_va_list type.
2047 TypedefDecl *getBuiltinMSVaListDecl() const;
2048
2049 /// Retrieve the type of the \c __builtin_ms_va_list type.
2050 QualType getBuiltinMSVaListType() const {
2051 return getTypeDeclType(getBuiltinMSVaListDecl());
2052 }
2053
2054 /// Retrieve the implicitly-predeclared 'struct _GUID' declaration.
2055 TagDecl *getMSGuidTagDecl() const { return MSGuidTagDecl; }
2056
2057 /// Retrieve the implicitly-predeclared 'struct _GUID' type.
2058 QualType getMSGuidType() const {
2059 assert(MSGuidTagDecl && "asked for GUID type but MS extensions disabled")(static_cast<void> (0));
2060 return getTagDeclType(MSGuidTagDecl);
2061 }
2062
2063 /// Return whether a declaration to a builtin is allowed to be
2064 /// overloaded/redeclared.
2065 bool canBuiltinBeRedeclared(const FunctionDecl *) const;
2066
2067 /// Return a type with additional \c const, \c volatile, or
2068 /// \c restrict qualifiers.
2069 QualType getCVRQualifiedType(QualType T, unsigned CVR) const {
2070 return getQualifiedType(T, Qualifiers::fromCVRMask(CVR));
2071 }
2072
2073 /// Un-split a SplitQualType.
2074 QualType getQualifiedType(SplitQualType split) const {
2075 return getQualifiedType(split.Ty, split.Quals);
2076 }
2077
2078 /// Return a type with additional qualifiers.
2079 QualType getQualifiedType(QualType T, Qualifiers Qs) const {
2080 if (!Qs.hasNonFastQualifiers())
2081 return T.withFastQualifiers(Qs.getFastQualifiers());
2082 QualifierCollector Qc(Qs);
2083 const Type *Ptr = Qc.strip(T);
2084 return getExtQualType(Ptr, Qc);
2085 }
2086
2087 /// Return a type with additional qualifiers.
2088 QualType getQualifiedType(const Type *T, Qualifiers Qs) const {
2089 if (!Qs.hasNonFastQualifiers())
2090 return QualType(T, Qs.getFastQualifiers());
2091 return getExtQualType(T, Qs);
2092 }
2093
2094 /// Return a type with the given lifetime qualifier.
2095 ///
2096 /// \pre Neither type.ObjCLifetime() nor \p lifetime may be \c OCL_None.
2097 QualType getLifetimeQualifiedType(QualType type,
2098 Qualifiers::ObjCLifetime lifetime) {
2099 assert(type.getObjCLifetime() == Qualifiers::OCL_None)(static_cast<void> (0));
2100 assert(lifetime != Qualifiers::OCL_None)(static_cast<void> (0));
2101
2102 Qualifiers qs;
2103 qs.addObjCLifetime(lifetime);
2104 return getQualifiedType(type, qs);
2105 }
2106
2107 /// getUnqualifiedObjCPointerType - Returns version of
2108 /// Objective-C pointer type with lifetime qualifier removed.
2109 QualType getUnqualifiedObjCPointerType(QualType type) const {
2110 if (!type.getTypePtr()->isObjCObjectPointerType() ||
2111 !type.getQualifiers().hasObjCLifetime())
2112 return type;
2113 Qualifiers Qs = type.getQualifiers();
2114 Qs.removeObjCLifetime();
2115 return getQualifiedType(type.getUnqualifiedType(), Qs);
2116 }
2117
2118 unsigned char getFixedPointScale(QualType Ty) const;
2119 unsigned char getFixedPointIBits(QualType Ty) const;
2120 llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const;
2121 llvm::APFixedPoint getFixedPointMax(QualType Ty) const;
2122 llvm::APFixedPoint getFixedPointMin(QualType Ty) const;
2123
2124 DeclarationNameInfo getNameForTemplate(TemplateName Name,
2125 SourceLocation NameLoc) const;
2126
2127 TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin,
2128 UnresolvedSetIterator End) const;
2129 TemplateName getAssumedTemplateName(DeclarationName Name) const;
2130
2131 TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS,
2132 bool TemplateKeyword,
2133 TemplateDecl *Template) const;
2134
2135 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2136 const IdentifierInfo *Name) const;
2137 TemplateName getDependentTemplateName(NestedNameSpecifier *NNS,
2138 OverloadedOperatorKind Operator) const;
2139 TemplateName getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param,
2140 TemplateName replacement) const;
2141 TemplateName getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param,
2142 const TemplateArgument &ArgPack) const;
2143
2144 enum GetBuiltinTypeError {
2145 /// No error
2146 GE_None,
2147
2148 /// Missing a type
2149 GE_Missing_type,
2150
2151 /// Missing a type from <stdio.h>
2152 GE_Missing_stdio,
2153
2154 /// Missing a type from <setjmp.h>
2155 GE_Missing_setjmp,
2156
2157 /// Missing a type from <ucontext.h>
2158 GE_Missing_ucontext
2159 };
2160
2161 QualType DecodeTypeStr(const char *&Str, const ASTContext &Context,
2162 ASTContext::GetBuiltinTypeError &Error,
2163 bool &RequireICE, bool AllowTypeModifiers) const;
2164
2165 /// Return the type for the specified builtin.
2166 ///
2167 /// If \p IntegerConstantArgs is non-null, it is filled in with a bitmask of
2168 /// arguments to the builtin that are required to be integer constant
2169 /// expressions.
2170 QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error,
2171 unsigned *IntegerConstantArgs = nullptr) const;
2172
2173 /// Types and expressions required to build C++2a three-way comparisons
2174 /// using operator<=>, including the values return by builtin <=> operators.
2175 ComparisonCategories CompCategories;
2176
2177private:
2178 CanQualType getFromTargetType(unsigned Type) const;
2179 TypeInfo getTypeInfoImpl(const Type *T) const;
2180
2181 //===--------------------------------------------------------------------===//
2182 // Type Predicates.
2183 //===--------------------------------------------------------------------===//
2184
2185public:
2186 /// Return one of the GCNone, Weak or Strong Objective-C garbage
2187 /// collection attributes.
2188 Qualifiers::GC getObjCGCAttrKind(QualType Ty) const;
2189
2190 /// Return true if the given vector types are of the same unqualified
2191 /// type or if they are equivalent to the same GCC vector type.
2192 ///
2193 /// \note This ignores whether they are target-specific (AltiVec or Neon)
2194 /// types.
2195 bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec);
2196
2197 /// Return true if the given types are an SVE builtin and a VectorType that
2198 /// is a fixed-length representation of the SVE builtin for a specific
2199 /// vector-length.
2200 bool areCompatibleSveTypes(QualType FirstType, QualType SecondType);
2201
2202 /// Return true if the given vector types are lax-compatible SVE vector types,
2203 /// false otherwise.
2204 bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType);
2205
2206 /// Return true if the type has been explicitly qualified with ObjC ownership.
2207 /// A type may be implicitly qualified with ownership under ObjC ARC, and in
2208 /// some cases the compiler treats these differently.
2209 bool hasDirectOwnershipQualifier(QualType Ty) const;
2210
2211 /// Return true if this is an \c NSObject object with its \c NSObject
2212 /// attribute set.
2213 static bool isObjCNSObjectType(QualType Ty) {
2214 return Ty->isObjCNSObjectType();
2215 }
2216
2217 //===--------------------------------------------------------------------===//
2218 // Type Sizing and Analysis
2219 //===--------------------------------------------------------------------===//
2220
2221 /// Return the APFloat 'semantics' for the specified scalar floating
2222 /// point type.
2223 const llvm::fltSemantics &getFloatTypeSemantics(QualType T) const;
2224
2225 /// Get the size and alignment of the specified complete type in bits.
2226 TypeInfo getTypeInfo(const Type *T) const;
2227 TypeInfo getTypeInfo(QualType T) const { return getTypeInfo(T.getTypePtr()); }
2228
2229 /// Get default simd alignment of the specified complete type in bits.
2230 unsigned getOpenMPDefaultSimdAlign(QualType T) const;
2231
2232 /// Return the size of the specified (complete) type \p T, in bits.
2233 uint64_t getTypeSize(QualType T) const { return getTypeInfo(T).Width; }
2234 uint64_t getTypeSize(const Type *T) const { return getTypeInfo(T).Width; }
2235
2236 /// Return the size of the character type, in bits.
2237 uint64_t getCharWidth() const {
2238 return getTypeSize(CharTy);
2239 }
2240
2241 /// Convert a size in bits to a size in characters.
2242 CharUnits toCharUnitsFromBits(int64_t BitSize) const;
2243
2244 /// Convert a size in characters to a size in bits.
2245 int64_t toBits(CharUnits CharSize) const;
2246
2247 /// Return the size of the specified (complete) type \p T, in
2248 /// characters.
2249 CharUnits getTypeSizeInChars(QualType T) const;
2250 CharUnits getTypeSizeInChars(const Type *T) const;
2251
2252 Optional<CharUnits> getTypeSizeInCharsIfKnown(QualType Ty) const {
2253 if (Ty->isIncompleteType() || Ty->isDependentType())
2254 return None;
2255 return getTypeSizeInChars(Ty);
2256 }
2257
2258 Optional<CharUnits> getTypeSizeInCharsIfKnown(const Type *Ty) const {
2259 return getTypeSizeInCharsIfKnown(QualType(Ty, 0));
2260 }
2261
2262 /// Return the ABI-specified alignment of a (complete) type \p T, in
2263 /// bits.
2264 unsigned getTypeAlign(QualType T) const { return getTypeInfo(T).Align; }
2265 unsigned getTypeAlign(const Type *T) const { return getTypeInfo(T).Align; }
2266
2267 /// Return the ABI-specified natural alignment of a (complete) type \p T,
2268 /// before alignment adjustments, in bits.
2269 ///
2270 /// This alignment is curently used only by ARM and AArch64 when passing
2271 /// arguments of a composite type.
2272 unsigned getTypeUnadjustedAlign(QualType T) const {
2273 return getTypeUnadjustedAlign(T.getTypePtr());
2274 }
2275 unsigned getTypeUnadjustedAlign(const Type *T) const;
2276
2277 /// Return the alignment of a type, in bits, or 0 if
2278 /// the type is incomplete and we cannot determine the alignment (for
2279 /// example, from alignment attributes). The returned alignment is the
2280 /// Preferred alignment if NeedsPreferredAlignment is true, otherwise is the
2281 /// ABI alignment.
2282 unsigned getTypeAlignIfKnown(QualType T,
2283 bool NeedsPreferredAlignment = false) const;
2284
2285 /// Return the ABI-specified alignment of a (complete) type \p T, in
2286 /// characters.
2287 CharUnits getTypeAlignInChars(QualType T) const;
2288 CharUnits getTypeAlignInChars(const Type *T) const;
2289
2290 /// Return the PreferredAlignment of a (complete) type \p T, in
2291 /// characters.
2292 CharUnits getPreferredTypeAlignInChars(QualType T) const {
2293 return toCharUnitsFromBits(getPreferredTypeAlign(T));
2294 }
2295
2296 /// getTypeUnadjustedAlignInChars - Return the ABI-specified alignment of a type,
2297 /// in characters, before alignment adjustments. This method does not work on
2298 /// incomplete types.
2299 CharUnits getTypeUnadjustedAlignInChars(QualType T) const;
2300 CharUnits getTypeUnadjustedAlignInChars(const Type *T) const;
2301
2302 // getTypeInfoDataSizeInChars - Return the size of a type, in chars. If the
2303 // type is a record, its data size is returned.
2304 TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const;
2305
2306 TypeInfoChars getTypeInfoInChars(const Type *T) const;
2307 TypeInfoChars getTypeInfoInChars(QualType T) const;
2308
2309 /// Determine if the alignment the type has was required using an
2310 /// alignment attribute.
2311 bool isAlignmentRequired(const Type *T) const;
2312 bool isAlignmentRequired(QualType T) const;
2313
2314 /// Return the "preferred" alignment of the specified type \p T for
2315 /// the current target, in bits.
2316 ///
2317 /// This can be different than the ABI alignment in cases where it is
2318 /// beneficial for performance or backwards compatibility preserving to
2319 /// overalign a data type. (Note: despite the name, the preferred alignment
2320 /// is ABI-impacting, and not an optimization.)
2321 unsigned getPreferredTypeAlign(QualType T) const {
2322 return getPreferredTypeAlign(T.getTypePtr());
2323 }
2324 unsigned getPreferredTypeAlign(const Type *T) const;
2325
2326 /// Return the default alignment for __attribute__((aligned)) on
2327 /// this target, to be used if no alignment value is specified.
2328 unsigned getTargetDefaultAlignForAttributeAligned() const;
2329
2330 /// Return the alignment in bits that should be given to a
2331 /// global variable with type \p T.
2332 unsigned getAlignOfGlobalVar(QualType T) const;
2333
2334 /// Return the alignment in characters that should be given to a
2335 /// global variable with type \p T.
2336 CharUnits getAlignOfGlobalVarInChars(QualType T) const;
2337
2338 /// Return a conservative estimate of the alignment of the specified
2339 /// decl \p D.
2340 ///
2341 /// \pre \p D must not be a bitfield type, as bitfields do not have a valid
2342 /// alignment.
2343 ///
2344 /// If \p ForAlignof, references are treated like their underlying type
2345 /// and large arrays don't get any special treatment. If not \p ForAlignof
2346 /// it computes the value expected by CodeGen: references are treated like
2347 /// pointers and large arrays get extra alignment.
2348 CharUnits getDeclAlign(const Decl *D, bool ForAlignof = false) const;
2349
2350 /// Return the alignment (in bytes) of the thrown exception object. This is
2351 /// only meaningful for targets that allocate C++ exceptions in a system
2352 /// runtime, such as those using the Itanium C++ ABI.
2353 CharUnits getExnObjectAlignment() const;
2354
2355 /// Get or compute information about the layout of the specified
2356 /// record (struct/union/class) \p D, which indicates its size and field
2357 /// position information.
2358 const ASTRecordLayout &getASTRecordLayout(const RecordDecl *D) const;
2359
2360 /// Get or compute information about the layout of the specified
2361 /// Objective-C interface.
2362 const ASTRecordLayout &getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D)
2363 const;
2364
2365 void DumpRecordLayout(const RecordDecl *RD, raw_ostream &OS,
2366 bool Simple = false) const;
2367
2368 /// Get or compute information about the layout of the specified
2369 /// Objective-C implementation.
2370 ///
2371 /// This may differ from the interface if synthesized ivars are present.
2372 const ASTRecordLayout &
2373 getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const;
2374
2375 /// Get our current best idea for the key function of the
2376 /// given record decl, or nullptr if there isn't one.
2377 ///
2378 /// The key function is, according to the Itanium C++ ABI section 5.2.3:
2379 /// ...the first non-pure virtual function that is not inline at the
2380 /// point of class definition.
2381 ///
2382 /// Other ABIs use the same idea. However, the ARM C++ ABI ignores
2383 /// virtual functions that are defined 'inline', which means that
2384 /// the result of this computation can change.
2385 const CXXMethodDecl *getCurrentKeyFunction(const CXXRecordDecl *RD);
2386
2387 /// Observe that the given method cannot be a key function.
2388 /// Checks the key-function cache for the method's class and clears it
2389 /// if matches the given declaration.
2390 ///
2391 /// This is used in ABIs where out-of-line definitions marked
2392 /// inline are not considered to be key functions.
2393 ///
2394 /// \param method should be the declaration from the class definition
2395 void setNonKeyFunction(const CXXMethodDecl *method);
2396
2397 /// Loading virtual member pointers using the virtual inheritance model
2398 /// always results in an adjustment using the vbtable even if the index is
2399 /// zero.
2400 ///
2401 /// This is usually OK because the first slot in the vbtable points
2402 /// backwards to the top of the MDC. However, the MDC might be reusing a
2403 /// vbptr from an nv-base. In this case, the first slot in the vbtable
2404 /// points to the start of the nv-base which introduced the vbptr and *not*
2405 /// the MDC. Modify the NonVirtualBaseAdjustment to account for this.
2406 CharUnits getOffsetOfBaseWithVBPtr(const CXXRecordDecl *RD) const;
2407
2408 /// Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
2409 uint64_t getFieldOffset(const ValueDecl *FD) const;
2410
2411 /// Get the offset of an ObjCIvarDecl in bits.
2412 uint64_t lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
2413 const ObjCImplementationDecl *ID,
2414 const ObjCIvarDecl *Ivar) const;
2415
2416 /// Find the 'this' offset for the member path in a pointer-to-member
2417 /// APValue.
2418 CharUnits getMemberPointerPathAdjustment(const APValue &MP) const;
2419
2420 bool isNearlyEmpty(const CXXRecordDecl *RD) const;
2421
2422 VTableContextBase *getVTableContext();
2423
2424 /// If \p T is null pointer, assume the target in ASTContext.
2425 MangleContext *createMangleContext(const TargetInfo *T = nullptr);
2426
2427 /// Creates a device mangle context to correctly mangle lambdas in a mixed
2428 /// architecture compile by setting the lambda mangling number source to the
2429 /// DeviceLambdaManglingNumber. Currently this asserts that the TargetInfo
2430 /// (from the AuxTargetInfo) is a an itanium target.
2431 MangleContext *createDeviceMangleContext(const TargetInfo &T);
2432
2433 void DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, bool leafClass,
2434 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const;
2435
2436 unsigned CountNonClassIvars(const ObjCInterfaceDecl *OI) const;
2437 void CollectInheritedProtocols(const Decl *CDecl,
2438 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols);
2439
2440 /// Return true if the specified type has unique object representations
2441 /// according to (C++17 [meta.unary.prop]p9)
2442 bool hasUniqueObjectRepresentations(QualType Ty) const;
2443
2444 //===--------------------------------------------------------------------===//
2445 // Type Operators
2446 //===--------------------------------------------------------------------===//
2447
2448 /// Return the canonical (structural) type corresponding to the
2449 /// specified potentially non-canonical type \p T.
2450 ///
2451 /// The non-canonical version of a type may have many "decorated" versions of
2452 /// types. Decorators can include typedefs, 'typeof' operators, etc. The
2453 /// returned type is guaranteed to be free of any of these, allowing two
2454 /// canonical types to be compared for exact equality with a simple pointer
2455 /// comparison.
2456 CanQualType getCanonicalType(QualType T) const {
2457 return CanQualType::CreateUnsafe(T.getCanonicalType());
2458 }
2459
2460 const Type *getCanonicalType(const Type *T) const {
2461 return T->getCanonicalTypeInternal().getTypePtr();
2462 }
2463
2464 /// Return the canonical parameter type corresponding to the specific
2465 /// potentially non-canonical one.
2466 ///
2467 /// Qualifiers are stripped off, functions are turned into function
2468 /// pointers, and arrays decay one level into pointers.
2469 CanQualType getCanonicalParamType(QualType T) const;
2470
2471 /// Determine whether the given types \p T1 and \p T2 are equivalent.
2472 bool hasSameType(QualType T1, QualType T2) const {
2473 return getCanonicalType(T1) == getCanonicalType(T2);
2474 }
2475 bool hasSameType(const Type *T1, const Type *T2) const {
2476 return getCanonicalType(T1) == getCanonicalType(T2);
2477 }
2478
2479 /// Return this type as a completely-unqualified array type,
2480 /// capturing the qualifiers in \p Quals.
2481 ///
2482 /// This will remove the minimal amount of sugaring from the types, similar
2483 /// to the behavior of QualType::getUnqualifiedType().
2484 ///
2485 /// \param T is the qualified type, which may be an ArrayType
2486 ///
2487 /// \param Quals will receive the full set of qualifiers that were
2488 /// applied to the array.
2489 ///
2490 /// \returns if this is an array type, the completely unqualified array type
2491 /// that corresponds to it. Otherwise, returns T.getUnqualifiedType().
2492 QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals);
2493
2494 /// Determine whether the given types are equivalent after
2495 /// cvr-qualifiers have been removed.
2496 bool hasSameUnqualifiedType(QualType T1, QualType T2) const {
2497 return getCanonicalType(T1).getTypePtr() ==
2498 getCanonicalType(T2).getTypePtr();
2499 }
2500
2501 bool hasSameNullabilityTypeQualifier(QualType SubT, QualType SuperT,
2502 bool IsParam) const {
2503 auto SubTnullability = SubT->getNullability(*this);
2504 auto SuperTnullability = SuperT->getNullability(*this);
2505 if (SubTnullability.hasValue() == SuperTnullability.hasValue()) {
2506 // Neither has nullability; return true
2507 if (!SubTnullability)
2508 return true;
2509 // Both have nullability qualifier.
2510 if (*SubTnullability == *SuperTnullability ||
2511 *SubTnullability == NullabilityKind::Unspecified ||
2512 *SuperTnullability == NullabilityKind::Unspecified)
2513 return true;
2514
2515 if (IsParam) {
2516 // Ok for the superclass method parameter to be "nonnull" and the subclass
2517 // method parameter to be "nullable"
2518 return (*SuperTnullability == NullabilityKind::NonNull &&
2519 *SubTnullability == NullabilityKind::Nullable);
2520 }
2521 // For the return type, it's okay for the superclass method to specify
2522 // "nullable" and the subclass method specify "nonnull"
2523 return (*SuperTnullability == NullabilityKind::Nullable &&
2524 *SubTnullability == NullabilityKind::NonNull);
2525 }
2526 return true;
2527 }
2528
2529 bool ObjCMethodsAreEqual(const ObjCMethodDecl *MethodDecl,
2530 const ObjCMethodDecl *MethodImp);
2531
2532 bool UnwrapSimilarTypes(QualType &T1, QualType &T2);
2533 void UnwrapSimilarArrayTypes(QualType &T1, QualType &T2);
2534
2535 /// Determine if two types are similar, according to the C++ rules. That is,
2536 /// determine if they are the same other than qualifiers on the initial
2537 /// sequence of pointer / pointer-to-member / array (and in Clang, object
2538 /// pointer) types and their element types.
2539 ///
2540 /// Clang offers a number of qualifiers in addition to the C++ qualifiers;
2541 /// those qualifiers are also ignored in the 'similarity' check.
2542 bool hasSimilarType(QualType T1, QualType T2);
2543
2544 /// Determine if two types are similar, ignoring only CVR qualifiers.
2545 bool hasCvrSimilarType(QualType T1, QualType T2);
2546
2547 /// Retrieves the "canonical" nested name specifier for a
2548 /// given nested name specifier.
2549 ///
2550 /// The canonical nested name specifier is a nested name specifier
2551 /// that uniquely identifies a type or namespace within the type
2552 /// system. For example, given:
2553 ///
2554 /// \code
2555 /// namespace N {
2556 /// struct S {
2557 /// template<typename T> struct X { typename T* type; };
2558 /// };
2559 /// }
2560 ///
2561 /// template<typename T> struct Y {
2562 /// typename N::S::X<T>::type member;
2563 /// };
2564 /// \endcode
2565 ///
2566 /// Here, the nested-name-specifier for N::S::X<T>:: will be
2567 /// S::X<template-param-0-0>, since 'S' and 'X' are uniquely defined
2568 /// by declarations in the type system and the canonical type for
2569 /// the template type parameter 'T' is template-param-0-0.
2570 NestedNameSpecifier *
2571 getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const;
2572
2573 /// Retrieves the default calling convention for the current target.
2574 CallingConv getDefaultCallingConvention(bool IsVariadic,
2575 bool IsCXXMethod,
2576 bool IsBuiltin = false) const;
2577
2578 /// Retrieves the "canonical" template name that refers to a
2579 /// given template.
2580 ///
2581 /// The canonical template name is the simplest expression that can
2582 /// be used to refer to a given template. For most templates, this
2583 /// expression is just the template declaration itself. For example,
2584 /// the template std::vector can be referred to via a variety of
2585 /// names---std::vector, \::std::vector, vector (if vector is in
2586 /// scope), etc.---but all of these names map down to the same
2587 /// TemplateDecl, which is used to form the canonical template name.
2588 ///
2589 /// Dependent template names are more interesting. Here, the
2590 /// template name could be something like T::template apply or
2591 /// std::allocator<T>::template rebind, where the nested name
2592 /// specifier itself is dependent. In this case, the canonical
2593 /// template name uses the shortest form of the dependent
2594 /// nested-name-specifier, which itself contains all canonical
2595 /// types, values, and templates.
2596 TemplateName getCanonicalTemplateName(TemplateName Name) const;
2597
2598 /// Determine whether the given template names refer to the same
2599 /// template.
2600 bool hasSameTemplateName(TemplateName X, TemplateName Y);
2601
2602 /// Retrieve the "canonical" template argument.
2603 ///
2604 /// The canonical template argument is the simplest template argument
2605 /// (which may be a type, value, expression, or declaration) that
2606 /// expresses the value of the argument.
2607 TemplateArgument getCanonicalTemplateArgument(const TemplateArgument &Arg)
2608 const;
2609
2610 /// Type Query functions. If the type is an instance of the specified class,
2611 /// return the Type pointer for the underlying maximally pretty type. This
2612 /// is a member of ASTContext because this may need to do some amount of
2613 /// canonicalization, e.g. to move type qualifiers into the element type.
2614 const ArrayType *getAsArrayType(QualType T) const;
2615 const ConstantArrayType *getAsConstantArrayType(QualType T) const {
2616 return dyn_cast_or_null<ConstantArrayType>(getAsArrayType(T));
2617 }
2618 const VariableArrayType *getAsVariableArrayType(QualType T) const {
2619 return dyn_cast_or_null<VariableArrayType>(getAsArrayType(T));
2620 }
2621 const IncompleteArrayType *getAsIncompleteArrayType(QualType T) const {
2622 return dyn_cast_or_null<IncompleteArrayType>(getAsArrayType(T));
2623 }
2624 const DependentSizedArrayType *getAsDependentSizedArrayType(QualType T)
2625 const {
2626 return dyn_cast_or_null<DependentSizedArrayType>(getAsArrayType(T));
2627 }
2628
2629 /// Return the innermost element type of an array type.
2630 ///
2631 /// For example, will return "int" for int[m][n]
2632 QualType getBaseElementType(const ArrayType *VAT) const;
2633
2634 /// Return the innermost element type of a type (which needn't
2635 /// actually be an array type).
2636 QualType getBaseElementType(QualType QT) const;
2637
2638 /// Return number of constant array elements.
2639 uint64_t getConstantArrayElementCount(const ConstantArrayType *CA) const;
2640
2641 /// Perform adjustment on the parameter type of a function.
2642 ///
2643 /// This routine adjusts the given parameter type @p T to the actual
2644 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
2645 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
2646 QualType getAdjustedParameterType(QualType T) const;
2647
2648 /// Retrieve the parameter type as adjusted for use in the signature
2649 /// of a function, decaying array and function types and removing top-level
2650 /// cv-qualifiers.
2651 QualType getSignatureParameterType(QualType T) const;
2652
2653 QualType getExceptionObjectType(QualType T) const;
2654
2655 /// Return the properly qualified result of decaying the specified
2656 /// array type to a pointer.
2657 ///
2658 /// This operation is non-trivial when handling typedefs etc. The canonical
2659 /// type of \p T must be an array type, this returns a pointer to a properly
2660 /// qualified element of the array.
2661 ///
2662 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3.
2663 QualType getArrayDecayedType(QualType T) const;
2664
2665 /// Return the type that \p PromotableType will promote to: C99
2666 /// 6.3.1.1p2, assuming that \p PromotableType is a promotable integer type.
2667 QualType getPromotedIntegerType(QualType PromotableType) const;
2668
2669 /// Recurses in pointer/array types until it finds an Objective-C
2670 /// retainable type and returns its ownership.
2671 Qualifiers::ObjCLifetime getInnerObjCOwnership(QualType T) const;
2672
2673 /// Whether this is a promotable bitfield reference according
2674 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions).
2675 ///
2676 /// \returns the type this bit-field will promote to, or NULL if no
2677 /// promotion occurs.
2678 QualType isPromotableBitField(Expr *E) const;
2679
2680 /// Return the highest ranked integer type, see C99 6.3.1.8p1.
2681 ///
2682 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2683 /// \p LHS < \p RHS, return -1.
2684 int getIntegerTypeOrder(QualType LHS, QualType RHS) const;
2685
2686 /// Compare the rank of the two specified floating point types,
2687 /// ignoring the domain of the type (i.e. 'double' == '_Complex double').
2688 ///
2689 /// If \p LHS > \p RHS, returns 1. If \p LHS == \p RHS, returns 0. If
2690 /// \p LHS < \p RHS, return -1.
2691 int getFloatingTypeOrder(QualType LHS, QualType RHS) const;
2692
2693 /// Compare the rank of two floating point types as above, but compare equal
2694 /// if both types have the same floating-point semantics on the target (i.e.
2695 /// long double and double on AArch64 will return 0).
2696 int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const;
2697
2698 /// Return a real floating point or a complex type (based on
2699 /// \p typeDomain/\p typeSize).
2700 ///
2701 /// \param typeDomain a real floating point or complex type.
2702 /// \param typeSize a real floating point or complex type.
2703 QualType getFloatingTypeOfSizeWithinDomain(QualType typeSize,
2704 QualType typeDomain) const;
2705
2706 unsigned getTargetAddressSpace(QualType T) const {
2707 return getTargetAddressSpace(T.getQualifiers());
2708 }
2709
2710 unsigned getTargetAddressSpace(Qualifiers Q) const {
2711 return getTargetAddressSpace(Q.getAddressSpace());
2712 }
2713
2714 unsigned getTargetAddressSpace(LangAS AS) const;
2715
2716 LangAS getLangASForBuiltinAddressSpace(unsigned AS) const;
2717
2718 /// Get target-dependent integer value for null pointer which is used for
2719 /// constant folding.
2720 uint64_t getTargetNullPointerValue(QualType QT) const;
2721
2722 bool addressSpaceMapManglingFor(LangAS AS) const {
2723 return AddrSpaceMapMangling || isTargetAddressSpace(AS);
2724 }
2725
2726private:
2727 // Helper for integer ordering
2728 unsigned getIntegerRank(const Type *T) const;
2729
2730public:
2731 //===--------------------------------------------------------------------===//
2732 // Type Compatibility Predicates
2733 //===--------------------------------------------------------------------===//
2734
2735 /// Compatibility predicates used to check assignment expressions.
2736 bool typesAreCompatible(QualType T1, QualType T2,
2737 bool CompareUnqualified = false); // C99 6.2.7p1
2738
2739 bool propertyTypesAreCompatible(QualType, QualType);
2740 bool typesAreBlockPointerCompatible(QualType, QualType);
2741
2742 bool isObjCIdType(QualType T) const {
2743 return T == getObjCIdType();
2744 }
2745
2746 bool isObjCClassType(QualType T) const {
2747 return T == getObjCClassType();
2748 }
2749
2750 bool isObjCSelType(QualType T) const {
2751 return T == getObjCSelType();
2752 }
2753
2754 bool ObjCQualifiedIdTypesAreCompatible(const ObjCObjectPointerType *LHS,
2755 const ObjCObjectPointerType *RHS,
2756 bool ForCompare);
2757
2758 bool ObjCQualifiedClassTypesAreCompatible(const ObjCObjectPointerType *LHS,
2759 const ObjCObjectPointerType *RHS);
2760
2761 // Check the safety of assignment from LHS to RHS
2762 bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT,
2763 const ObjCObjectPointerType *RHSOPT);
2764 bool canAssignObjCInterfaces(const ObjCObjectType *LHS,
2765 const ObjCObjectType *RHS);
2766 bool canAssignObjCInterfacesInBlockPointer(
2767 const ObjCObjectPointerType *LHSOPT,
2768 const ObjCObjectPointerType *RHSOPT,
2769 bool BlockReturnType);
2770 bool areComparableObjCPointerTypes(QualType LHS, QualType RHS);
2771 QualType areCommonBaseCompatible(const ObjCObjectPointerType *LHSOPT,
2772 const ObjCObjectPointerType *RHSOPT);
2773 bool canBindObjCObjectType(QualType To, QualType From);
2774
2775 // Functions for calculating composite types
2776 QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false,
2777 bool Unqualified = false, bool BlockReturnType = false);
2778 QualType mergeFunctionTypes(QualType, QualType, bool OfBlockPointer=false,
2779 bool Unqualified = false, bool AllowCXX = false);
2780 QualType mergeFunctionParameterTypes(QualType, QualType,
2781 bool OfBlockPointer = false,
2782 bool Unqualified = false);
2783 QualType mergeTransparentUnionType(QualType, QualType,
2784 bool OfBlockPointer=false,
2785 bool Unqualified = false);
2786
2787 QualType mergeObjCGCQualifiers(QualType, QualType);
2788
2789 /// This function merges the ExtParameterInfo lists of two functions. It
2790 /// returns true if the lists are compatible. The merged list is returned in
2791 /// NewParamInfos.
2792 ///
2793 /// \param FirstFnType The type of the first function.
2794 ///
2795 /// \param SecondFnType The type of the second function.
2796 ///
2797 /// \param CanUseFirst This flag is set to true if the first function's
2798 /// ExtParameterInfo list can be used as the composite list of
2799 /// ExtParameterInfo.
2800 ///
2801 /// \param CanUseSecond This flag is set to true if the second function's
2802 /// ExtParameterInfo list can be used as the composite list of
2803 /// ExtParameterInfo.
2804 ///
2805 /// \param NewParamInfos The composite list of ExtParameterInfo. The list is
2806 /// empty if none of the flags are set.
2807 ///
2808 bool mergeExtParameterInfo(
2809 const FunctionProtoType *FirstFnType,
2810 const FunctionProtoType *SecondFnType,
2811 bool &CanUseFirst, bool &CanUseSecond,
2812 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &NewParamInfos);
2813
2814 void ResetObjCLayout(const ObjCContainerDecl *CD);
2815
2816 //===--------------------------------------------------------------------===//
2817 // Integer Predicates
2818 //===--------------------------------------------------------------------===//
2819
2820 // The width of an integer, as defined in C99 6.2.6.2. This is the number
2821 // of bits in an integer type excluding any padding bits.
2822 unsigned getIntWidth(QualType T) const;
2823
2824 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2825 // unsigned integer type. This method takes a signed type, and returns the
2826 // corresponding unsigned integer type.
2827 // With the introduction of fixed point types in ISO N1169, this method also
2828 // accepts fixed point types and returns the corresponding unsigned type for
2829 // a given fixed point type.
2830 QualType getCorrespondingUnsignedType(QualType T) const;
2831
2832 // Per C99 6.2.5p6, for every signed integer type, there is a corresponding
2833 // unsigned integer type. This method takes an unsigned type, and returns the
2834 // corresponding signed integer type.
2835 // With the introduction of fixed point types in ISO N1169, this method also
2836 // accepts fixed point types and returns the corresponding signed type for
2837 // a given fixed point type.
2838 QualType getCorrespondingSignedType(QualType T) const;
2839
2840 // Per ISO N1169, this method accepts fixed point types and returns the
2841 // corresponding saturated type for a given fixed point type.
2842 QualType getCorrespondingSaturatedType(QualType Ty) const;
2843
2844 // This method accepts fixed point types and returns the corresponding signed
2845 // type. Unlike getCorrespondingUnsignedType(), this only accepts unsigned
2846 // fixed point types because there are unsigned integer types like bool and
2847 // char8_t that don't have signed equivalents.
2848 QualType getCorrespondingSignedFixedPointType(QualType Ty) const;
2849
2850 //===--------------------------------------------------------------------===//
2851 // Integer Values
2852 //===--------------------------------------------------------------------===//
2853
2854 /// Make an APSInt of the appropriate width and signedness for the
2855 /// given \p Value and integer \p Type.
2856 llvm::APSInt MakeIntValue(uint64_t Value, QualType Type) const {
2857 // If Type is a signed integer type larger than 64 bits, we need to be sure
2858 // to sign extend Res appropriately.
2859 llvm::APSInt Res(64, !Type->isSignedIntegerOrEnumerationType());
2860 Res = Value;
2861 unsigned Width = getIntWidth(Type);
2862 if (Width != Res.getBitWidth())
2863 return Res.extOrTrunc(Width);
2864 return Res;
2865 }
2866
2867 bool isSentinelNullExpr(const Expr *E);
2868
2869 /// Get the implementation of the ObjCInterfaceDecl \p D, or nullptr if
2870 /// none exists.
2871 ObjCImplementationDecl *getObjCImplementation(ObjCInterfaceDecl *D);
2872
2873 /// Get the implementation of the ObjCCategoryDecl \p D, or nullptr if
2874 /// none exists.
2875 ObjCCategoryImplDecl *getObjCImplementation(ObjCCategoryDecl *D);
2876
2877 /// Return true if there is at least one \@implementation in the TU.
2878 bool AnyObjCImplementation() {
2879 return !ObjCImpls.empty();
2880 }
2881
2882 /// Set the implementation of ObjCInterfaceDecl.
2883 void setObjCImplementation(ObjCInterfaceDecl *IFaceD,
2884 ObjCImplementationDecl *ImplD);
2885
2886 /// Set the implementation of ObjCCategoryDecl.
2887 void setObjCImplementation(ObjCCategoryDecl *CatD,
2888 ObjCCategoryImplDecl *ImplD);
2889
2890 /// Get the duplicate declaration of a ObjCMethod in the same
2891 /// interface, or null if none exists.
2892 const ObjCMethodDecl *
2893 getObjCMethodRedeclaration(const ObjCMethodDecl *MD) const;
2894
2895 void setObjCMethodRedeclaration(const ObjCMethodDecl *MD,
2896 const ObjCMethodDecl *Redecl);
2897
2898 /// Returns the Objective-C interface that \p ND belongs to if it is
2899 /// an Objective-C method/property/ivar etc. that is part of an interface,
2900 /// otherwise returns null.
2901 const ObjCInterfaceDecl *getObjContainingInterface(const NamedDecl *ND) const;
2902
2903 /// Set the copy initialization expression of a block var decl. \p CanThrow
2904 /// indicates whether the copy expression can throw or not.
2905 void setBlockVarCopyInit(const VarDecl* VD, Expr *CopyExpr, bool CanThrow);
2906
2907 /// Get the copy initialization expression of the VarDecl \p VD, or
2908 /// nullptr if none exists.
2909 BlockVarCopyInit getBlockVarCopyInit(const VarDecl* VD) const;
2910
2911 /// Allocate an uninitialized TypeSourceInfo.
2912 ///
2913 /// The caller should initialize the memory held by TypeSourceInfo using
2914 /// the TypeLoc wrappers.
2915 ///
2916 /// \param T the type that will be the basis for type source info. This type
2917 /// should refer to how the declarator was written in source code, not to
2918 /// what type semantic analysis resolved the declarator to.
2919 ///
2920 /// \param Size the size of the type info to create, or 0 if the size
2921 /// should be calculated based on the type.
2922 TypeSourceInfo *CreateTypeSourceInfo(QualType T, unsigned Size = 0) const;
2923
2924 /// Allocate a TypeSourceInfo where all locations have been
2925 /// initialized to a given location, which defaults to the empty
2926 /// location.
2927 TypeSourceInfo *
2928 getTrivialTypeSourceInfo(QualType T,
2929 SourceLocation Loc = SourceLocation()) const;
2930
2931 /// Add a deallocation callback that will be invoked when the
2932 /// ASTContext is destroyed.
2933 ///
2934 /// \param Callback A callback function that will be invoked on destruction.
2935 ///
2936 /// \param Data Pointer data that will be provided to the callback function
2937 /// when it is called.
2938 void AddDeallocation(void (*Callback)(void *), void *Data) const;
2939
2940 /// If T isn't trivially destructible, calls AddDeallocation to register it
2941 /// for destruction.
2942 template <typename T> void addDestruction(T *Ptr) const {
2943 if (!std::is_trivially_destructible<T>::value) {
2944 auto DestroyPtr = [](void *V) { static_cast<T *>(V)->~T(); };
2945 AddDeallocation(DestroyPtr, Ptr);
2946 }
2947 }
2948
2949 GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const;
2950 GVALinkage GetGVALinkageForVariable(const VarDecl *VD);
2951
2952 /// Determines if the decl can be CodeGen'ed or deserialized from PCH
2953 /// lazily, only when used; this is only relevant for function or file scoped
2954 /// var definitions.
2955 ///
2956 /// \returns true if the function/var must be CodeGen'ed/deserialized even if
2957 /// it is not used.
2958 bool DeclMustBeEmitted(const Decl *D);
2959
2960 /// Visits all versions of a multiversioned function with the passed
2961 /// predicate.
2962 void forEachMultiversionedFunctionVersion(
2963 const FunctionDecl *FD,
2964 llvm::function_ref<void(FunctionDecl *)> Pred) const;
2965
2966 const CXXConstructorDecl *
2967 getCopyConstructorForExceptionObject(CXXRecordDecl *RD);
2968
2969 void addCopyConstructorForExceptionObject(CXXRecordDecl *RD,
2970 CXXConstructorDecl *CD);
2971
2972 void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND);
2973
2974 TypedefNameDecl *getTypedefNameForUnnamedTagDecl(const TagDecl *TD);
2975
2976 void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD);
2977
2978 DeclaratorDecl *getDeclaratorForUnnamedTagDecl(const TagDecl *TD);
2979
2980 void setManglingNumber(const NamedDecl *ND, unsigned Number);
2981 unsigned getManglingNumber(const NamedDecl *ND) const;
2982
2983 void setStaticLocalNumber(const VarDecl *VD, unsigned Number);
2984 unsigned getStaticLocalNumber(const VarDecl *VD) const;
2985
2986 /// Retrieve the context for computing mangling numbers in the given
2987 /// DeclContext.
2988 MangleNumberingContext &getManglingNumberContext(const DeclContext *DC);
2989 enum NeedExtraManglingDecl_t { NeedExtraManglingDecl };
2990 MangleNumberingContext &getManglingNumberContext(NeedExtraManglingDecl_t,
2991 const Decl *D);
2992
2993 std::unique_ptr<MangleNumberingContext> createMangleNumberingContext() const;
2994
2995 /// Used by ParmVarDecl to store on the side the
2996 /// index of the parameter when it exceeds the size of the normal bitfield.
2997 void setParameterIndex(const ParmVarDecl *D, unsigned index);
2998
2999 /// Used by ParmVarDecl to retrieve on the side the
3000 /// index of the parameter when it exceeds the size of the normal bitfield.
3001 unsigned getParameterIndex(const ParmVarDecl *D) const;
3002
3003 /// Return a string representing the human readable name for the specified
3004 /// function declaration or file name. Used by SourceLocExpr and
3005 /// PredefinedExpr to cache evaluated results.
3006 StringLiteral *getPredefinedStringLiteralFromCache(StringRef Key) const;
3007
3008 /// Return a declaration for the global GUID object representing the given
3009 /// GUID value.
3010 MSGuidDecl *getMSGuidDecl(MSGuidDeclParts Parts) const;
3011
3012 /// Return the template parameter object of the given type with the given
3013 /// value.
3014 TemplateParamObjectDecl *getTemplateParamObjectDecl(QualType T,
3015 const APValue &V) const;
3016
3017 /// Parses the target attributes passed in, and returns only the ones that are
3018 /// valid feature names.
3019 ParsedTargetAttr filterFunctionTargetAttrs(const TargetAttr *TD) const;
3020
3021 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3022 const FunctionDecl *) const;
3023 void getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3024 GlobalDecl GD) const;
3025
3026 //===--------------------------------------------------------------------===//
3027 // Statistics
3028 //===--------------------------------------------------------------------===//
3029
3030 /// The number of implicitly-declared default constructors.
3031 unsigned NumImplicitDefaultConstructors = 0;
3032
3033 /// The number of implicitly-declared default constructors for
3034 /// which declarations were built.
3035 unsigned NumImplicitDefaultConstructorsDeclared = 0;
3036
3037 /// The number of implicitly-declared copy constructors.
3038 unsigned NumImplicitCopyConstructors = 0;
3039
3040 /// The number of implicitly-declared copy constructors for
3041 /// which declarations were built.
3042 unsigned NumImplicitCopyConstructorsDeclared = 0;
3043
3044 /// The number of implicitly-declared move constructors.
3045 unsigned NumImplicitMoveConstructors = 0;
3046
3047 /// The number of implicitly-declared move constructors for
3048 /// which declarations were built.
3049 unsigned NumImplicitMoveConstructorsDeclared = 0;
3050
3051 /// The number of implicitly-declared copy assignment operators.
3052 unsigned NumImplicitCopyAssignmentOperators = 0;
3053
3054 /// The number of implicitly-declared copy assignment operators for
3055 /// which declarations were built.
3056 unsigned NumImplicitCopyAssignmentOperatorsDeclared = 0;
3057
3058 /// The number of implicitly-declared move assignment operators.
3059 unsigned NumImplicitMoveAssignmentOperators = 0;
3060
3061 /// The number of implicitly-declared move assignment operators for
3062 /// which declarations were built.
3063 unsigned NumImplicitMoveAssignmentOperatorsDeclared = 0;
3064
3065 /// The number of implicitly-declared destructors.
3066 unsigned NumImplicitDestructors = 0;
3067
3068 /// The number of implicitly-declared destructors for which
3069 /// declarations were built.
3070 unsigned NumImplicitDestructorsDeclared = 0;
3071
3072public:
3073 /// Initialize built-in types.
3074 ///
3075 /// This routine may only be invoked once for a given ASTContext object.
3076 /// It is normally invoked after ASTContext construction.
3077 ///
3078 /// \param Target The target
3079 void InitBuiltinTypes(const TargetInfo &Target,
3080 const TargetInfo *AuxTarget = nullptr);
3081
3082private:
3083 void InitBuiltinType(CanQualType &R, BuiltinType::Kind K);
3084
3085 class ObjCEncOptions {
3086 unsigned Bits;
3087
3088 ObjCEncOptions(unsigned Bits) : Bits(Bits) {}
3089
3090 public:
3091 ObjCEncOptions() : Bits(0) {}
3092 ObjCEncOptions(const ObjCEncOptions &RHS) : Bits(RHS.Bits) {}
3093
3094#define OPT_LIST(V) \
3095 V(ExpandPointedToStructures, 0) \
3096 V(ExpandStructures, 1) \
3097 V(IsOutermostType, 2) \
3098 V(EncodingProperty, 3) \
3099 V(IsStructField, 4) \
3100 V(EncodeBlockParameters, 5) \
3101 V(EncodeClassNames, 6) \
3102
3103#define V(N,I) ObjCEncOptions& set##N() { Bits |= 1 << I; return *this; }
3104OPT_LIST(V)
3105#undef V
3106
3107#define V(N,I) bool N() const { return Bits & 1 << I; }
3108OPT_LIST(V)
3109#undef V
3110
3111#undef OPT_LIST
3112
3113 LLVM_NODISCARD[[clang::warn_unused_result]] ObjCEncOptions keepingOnly(ObjCEncOptions Mask) const {
3114 return Bits & Mask.Bits;
3115 }
3116
3117 LLVM_NODISCARD[[clang::warn_unused_result]] ObjCEncOptions forComponentType() const {
3118 ObjCEncOptions Mask = ObjCEncOptions()
3119 .setIsOutermostType()
3120 .setIsStructField();
3121 return Bits & ~Mask.Bits;
3122 }
3123 };
3124
3125 // Return the Objective-C type encoding for a given type.
3126 void getObjCEncodingForTypeImpl(QualType t, std::string &S,
3127 ObjCEncOptions Options,
3128 const FieldDecl *Field,
3129 QualType *NotEncodedT = nullptr) const;
3130
3131 // Adds the encoding of the structure's members.
3132 void getObjCEncodingForStructureImpl(RecordDecl *RD, std::string &S,
3133 const FieldDecl *Field,
3134 bool includeVBases = true,
3135 QualType *NotEncodedT=nullptr) const;
3136
3137public:
3138 // Adds the encoding of a method parameter or return type.
3139 void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT,
3140 QualType T, std::string& S,
3141 bool Extended) const;
3142
3143 /// Returns true if this is an inline-initialized static data member
3144 /// which is treated as a definition for MSVC compatibility.
3145 bool isMSStaticDataMemberInlineDefinition(const VarDecl *VD) const;
3146
3147 enum class InlineVariableDefinitionKind {
3148 /// Not an inline variable.
3149 None,
3150
3151 /// Weak definition of inline variable.
3152 Weak,
3153
3154 /// Weak for now, might become strong later in this TU.
3155 WeakUnknown,
3156
3157 /// Strong definition.
3158 Strong
3159 };
3160
3161 /// Determine whether a definition of this inline variable should
3162 /// be treated as a weak or strong definition. For compatibility with
3163 /// C++14 and before, for a constexpr static data member, if there is an
3164 /// out-of-line declaration of the member, we may promote it from weak to
3165 /// strong.
3166 InlineVariableDefinitionKind
3167 getInlineVariableDefinitionKind(const VarDecl *VD) const;
3168
3169private:
3170 friend class DeclarationNameTable;
3171 friend class DeclContext;
3172
3173 const ASTRecordLayout &
3174 getObjCLayout(const ObjCInterfaceDecl *D,
3175 const ObjCImplementationDecl *Impl) const;
3176
3177 /// A set of deallocations that should be performed when the
3178 /// ASTContext is destroyed.
3179 // FIXME: We really should have a better mechanism in the ASTContext to
3180 // manage running destructors for types which do variable sized allocation
3181 // within the AST. In some places we thread the AST bump pointer allocator
3182 // into the datastructures which avoids this mess during deallocation but is
3183 // wasteful of memory, and here we require a lot of error prone book keeping
3184 // in order to track and run destructors while we're tearing things down.
3185 using DeallocationFunctionsAndArguments =
3186 llvm::SmallVector<std::pair<void (*)(void *), void *>, 16>;
3187 mutable DeallocationFunctionsAndArguments Deallocations;
3188
3189 // FIXME: This currently contains the set of StoredDeclMaps used
3190 // by DeclContext objects. This probably should not be in ASTContext,
3191 // but we include it here so that ASTContext can quickly deallocate them.
3192 llvm::PointerIntPair<StoredDeclsMap *, 1> LastSDM;
3193
3194 std::vector<Decl *> TraversalScope;
3195
3196 std::unique_ptr<VTableContextBase> VTContext;
3197
3198 void ReleaseDeclContextMaps();
3199
3200public:
3201 enum PragmaSectionFlag : unsigned {
3202 PSF_None = 0,
3203 PSF_Read = 0x1,
3204 PSF_Write = 0x2,
3205 PSF_Execute = 0x4,
3206 PSF_Implicit = 0x8,
3207 PSF_ZeroInit = 0x10,
3208 PSF_Invalid = 0x80000000U,
3209 };
3210
3211 struct SectionInfo {
3212 NamedDecl *Decl;
3213 SourceLocation PragmaSectionLocation;
3214 int SectionFlags;
3215
3216 SectionInfo() = default;
3217 SectionInfo(NamedDecl *Decl, SourceLocation PragmaSectionLocation,
3218 int SectionFlags)
3219 : Decl(Decl), PragmaSectionLocation(PragmaSectionLocation),
3220 SectionFlags(SectionFlags) {}
3221 };
3222
3223 llvm::StringMap<SectionInfo> SectionInfos;
3224
3225 /// Return a new OMPTraitInfo object owned by this context.
3226 OMPTraitInfo &getNewOMPTraitInfo();
3227
3228 /// Whether a C++ static variable may be externalized.
3229 bool mayExternalizeStaticVar(const Decl *D) const;
3230
3231 /// Whether a C++ static variable should be externalized.
3232 bool shouldExternalizeStaticVar(const Decl *D) const;
3233
3234 StringRef getCUIDHash() const;
3235
3236 void AddSYCLKernelNamingDecl(const CXXRecordDecl *RD);
3237 bool IsSYCLKernelNamingDecl(const NamedDecl *RD) const;
3238 unsigned GetSYCLKernelNamingIndex(const NamedDecl *RD);
3239 /// A SourceLocation to store whether we have evaluated a kernel name already,
3240 /// and where it happened. If so, we need to diagnose an illegal use of the
3241 /// builtin.
3242 llvm::MapVector<const SYCLUniqueStableNameExpr *, std::string>
3243 SYCLUniqueStableNameEvaluatedValues;
3244
3245private:
3246 /// All OMPTraitInfo objects live in this collection, one per
3247 /// `pragma omp [begin] declare variant` directive.
3248 SmallVector<std::unique_ptr<OMPTraitInfo>, 4> OMPTraitInfoVector;
3249
3250 /// A list of the (right now just lambda decls) declarations required to
3251 /// name all the SYCL kernels in the translation unit, so that we can get the
3252 /// correct kernel name, as well as implement
3253 /// __builtin_sycl_unique_stable_name.
3254 llvm::DenseMap<const DeclContext *,
3255 llvm::SmallPtrSet<const CXXRecordDecl *, 4>>
3256 SYCLKernelNamingTypes;
3257 std::unique_ptr<ItaniumMangleContext> SYCLKernelFilterContext;
3258 void FilterSYCLKernelNamingDecls(
3259 const CXXRecordDecl *RD,
3260 llvm::SmallVectorImpl<const CXXRecordDecl *> &Decls);
3261};
3262
3263/// Insertion operator for diagnostics.
3264const StreamingDiagnostic &operator<<(const StreamingDiagnostic &DB,
3265 const ASTContext::SectionInfo &Section);
3266
3267/// Utility function for constructing a nullary selector.
3268inline Selector GetNullarySelector(StringRef name, ASTContext &Ctx) {
3269 IdentifierInfo* II = &Ctx.Idents.get(name);
3270 return Ctx.Selectors.getSelector(0, &II);
3271}
3272
3273/// Utility function for constructing an unary selector.
3274inline Selector GetUnarySelector(StringRef name, ASTContext &Ctx) {
3275 IdentifierInfo* II = &Ctx.Idents.get(name);
3276 return Ctx.Selectors.getSelector(1, &II);
3277}
3278
3279} // namespace clang
3280
3281// operator new and delete aren't allowed inside namespaces.
3282
3283/// Placement new for using the ASTContext's allocator.
3284///
3285/// This placement form of operator new uses the ASTContext's allocator for
3286/// obtaining memory.
3287///
3288/// IMPORTANT: These are also declared in clang/AST/ASTContextAllocate.h!
3289/// Any changes here need to also be made there.
3290///
3291/// We intentionally avoid using a nothrow specification here so that the calls
3292/// to this operator will not perform a null check on the result -- the
3293/// underlying allocator never returns null pointers.
3294///
3295/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3296/// @code
3297/// // Default alignment (8)
3298/// IntegerLiteral *Ex = new (Context) IntegerLiteral(arguments);
3299/// // Specific alignment
3300/// IntegerLiteral *Ex2 = new (Context, 4) IntegerLiteral(arguments);
3301/// @endcode
3302/// Memory allocated through this placement new operator does not need to be
3303/// explicitly freed, as ASTContext will free all of this memory when it gets
3304/// destroyed. Please note that you cannot use delete on the pointer.
3305///
3306/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3307/// @param C The ASTContext that provides the allocator.
3308/// @param Alignment The alignment of the allocated memory (if the underlying
3309/// allocator supports it).
3310/// @return The allocated memory. Could be nullptr.
3311inline void *operator new(size_t Bytes, const clang::ASTContext &C,
3312 size_t Alignment /* = 8 */) {
3313 return C.Allocate(Bytes, Alignment);
3314}
3315
3316/// Placement delete companion to the new above.
3317///
3318/// This operator is just a companion to the new above. There is no way of
3319/// invoking it directly; see the new operator for more details. This operator
3320/// is called implicitly by the compiler if a placement new expression using
3321/// the ASTContext throws in the object constructor.
3322inline void operator delete(void *Ptr, const clang::ASTContext &C, size_t) {
3323 C.Deallocate(Ptr);
3324}
3325
3326/// This placement form of operator new[] uses the ASTContext's allocator for
3327/// obtaining memory.
3328///
3329/// We intentionally avoid using a nothrow specification here so that the calls
3330/// to this operator will not perform a null check on the result -- the
3331/// underlying allocator never returns null pointers.
3332///
3333/// Usage looks like this (assuming there's an ASTContext 'Context' in scope):
3334/// @code
3335/// // Default alignment (8)
3336/// char *data = new (Context) char[10];
3337/// // Specific alignment
3338/// char *data = new (Context, 4) char[10];
3339/// @endcode
3340/// Memory allocated through this placement new[] operator does not need to be
3341/// explicitly freed, as ASTContext will free all of this memory when it gets
3342/// destroyed. Please note that you cannot use delete on the pointer.
3343///
3344/// @param Bytes The number of bytes to allocate. Calculated by the compiler.
3345/// @param C The ASTContext that provides the allocator.
3346/// @param Alignment The alignment of the allocated memory (if the underlying
3347/// allocator supports it).
3348/// @return The allocated memory. Could be nullptr.
3349inline void *operator new[](size_t Bytes, const clang::ASTContext& C,
3350 size_t Alignment /* = 8 */) {
3351 return C.Allocate(Bytes, Alignment);
3352}
3353
3354/// Placement delete[] companion to the new[] above.
3355///
3356/// This operator is just a companion to the new[] above. There is no way of
3357/// invoking it directly; see the new[] operator for more details. This operator
3358/// is called implicitly by the compiler if a placement new[] expression using
3359/// the ASTContext throws in the object constructor.
3360inline void operator delete[](void *Ptr, const clang::ASTContext &C, size_t) {
3361 C.Deallocate(Ptr);
3362}
3363
3364/// Create the representation of a LazyGenerationalUpdatePtr.
3365template <typename Owner, typename T,
3366 void (clang::ExternalASTSource::*Update)(Owner)>
3367typename clang::LazyGenerationalUpdatePtr<Owner, T, Update>::ValueType
3368 clang::LazyGenerationalUpdatePtr<Owner, T, Update>::makeValue(
3369 const clang::ASTContext &Ctx, T Value) {
3370 // Note, this is implemented here so that ExternalASTSource.h doesn't need to
3371 // include ASTContext.h. We explicitly instantiate it for all relevant types
3372 // in ASTContext.cpp.
3373 if (auto *Source = Ctx.getExternalSource())
3374 return new (Ctx) LazyData(Source, Value);
3375 return Value;
3376}
3377
3378#endif // LLVM_CLANG_AST_ASTCONTEXT_H