Bug Summary

File:tools/clang/lib/Sema/SemaCoroutine.cpp
Warning:line 86, column 20
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaCoroutine.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 -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp

1//===-- SemaCoroutine.cpp - Semantic Analysis for Coroutines --------------===//
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++ Coroutines.
10//
11// This file contains references to sections of the Coroutines TS, which
12// can be found at http://wg21.link/coroutines.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CoroutineStmtBuilder.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/StmtCXX.h"
21#include "clang/Lex/Preprocessor.h"
22#include "clang/Sema/Initialization.h"
23#include "clang/Sema/Overload.h"
24#include "clang/Sema/ScopeInfo.h"
25#include "clang/Sema/SemaInternal.h"
26
27using namespace clang;
28using namespace sema;
29
30static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
31 SourceLocation Loc, bool &Res) {
32 DeclarationName DN = S.PP.getIdentifierInfo(Name);
33 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
34 // Suppress diagnostics when a private member is selected. The same warnings
35 // will be produced again when building the call.
36 LR.suppressDiagnostics();
37 Res = S.LookupQualifiedName(LR, RD);
38 return LR;
39}
40
41static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
42 SourceLocation Loc) {
43 bool Res;
44 lookupMember(S, Name, RD, Loc, Res);
45 return Res;
46}
47
48/// Look up the std::coroutine_traits<...>::promise_type for the given
49/// function type.
50static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
51 SourceLocation KwLoc) {
52 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
18
The object is a 'FunctionProtoType'
53 const SourceLocation FuncLoc = FD->getLocation();
54 // FIXME: Cache std::coroutine_traits once we've found it.
55 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
56 if (!StdExp) {
19
Assuming 'StdExp' is non-null
20
Taking false branch
57 S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
58 << "std::experimental::coroutine_traits";
59 return QualType();
60 }
61
62 ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
63 if (!CoroTraits) {
21
Assuming 'CoroTraits' is non-null
22
Taking false branch
64 return QualType();
65 }
66
67 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
68 // to [dcl.fct.def.coroutine]3
69 TemplateArgumentListInfo Args(KwLoc, KwLoc);
70 auto AddArg = [&](QualType T) {
71 Args.addArgument(TemplateArgumentLoc(
72 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
73 };
74 AddArg(FnType->getReturnType());
75 // If the function is a non-static member function, add the type
76 // of the implicit object parameter before the formal parameters.
77 if (auto *MD
23.1
'MD' is non-null
23.1
'MD' is non-null
= dyn_cast<CXXMethodDecl>(FD)) {
23
Assuming 'FD' is a 'CXXMethodDecl'
24
Taking true branch
78 if (MD->isInstance()) {
25
Calling 'CXXMethodDecl::isInstance'
28
Returning from 'CXXMethodDecl::isInstance'
29
Taking true branch
79 // [over.match.funcs]4
80 // For non-static member functions, the type of the implicit object
81 // parameter is
82 // -- "lvalue reference to cv X" for functions declared without a
83 // ref-qualifier or with the & ref-qualifier
84 // -- "rvalue reference to cv X" for functions declared with the &&
85 // ref-qualifier
86 QualType T = MD->getThisType()->getAs<PointerType>()->getPointeeType();
30
Assuming the object is not a 'PointerType'
31
Called C++ object pointer is null
87 T = FnType->getRefQualifier() == RQ_RValue
88 ? S.Context.getRValueReferenceType(T)
89 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
90 AddArg(T);
91 }
92 }
93 for (QualType T : FnType->getParamTypes())
94 AddArg(T);
95
96 // Build the template-id.
97 QualType CoroTrait =
98 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
99 if (CoroTrait.isNull())
100 return QualType();
101 if (S.RequireCompleteType(KwLoc, CoroTrait,
102 diag::err_coroutine_type_missing_specialization))
103 return QualType();
104
105 auto *RD = CoroTrait->getAsCXXRecordDecl();
106 assert(RD && "specialization of class template is not a class?")((RD && "specialization of class template is not a class?"
) ? static_cast<void> (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 106, __PRETTY_FUNCTION__))
;
107
108 // Look up the ::promise_type member.
109 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
110 Sema::LookupOrdinaryName);
111 S.LookupQualifiedName(R, RD);
112 auto *Promise = R.getAsSingle<TypeDecl>();
113 if (!Promise) {
114 S.Diag(FuncLoc,
115 diag::err_implied_std_coroutine_traits_promise_type_not_found)
116 << RD;
117 return QualType();
118 }
119 // The promise type is required to be a class type.
120 QualType PromiseType = S.Context.getTypeDeclType(Promise);
121
122 auto buildElaboratedType = [&]() {
123 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
124 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
125 CoroTrait.getTypePtr());
126 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
127 };
128
129 if (!PromiseType->getAsCXXRecordDecl()) {
130 S.Diag(FuncLoc,
131 diag::err_implied_std_coroutine_traits_promise_type_not_class)
132 << buildElaboratedType();
133 return QualType();
134 }
135 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
136 diag::err_coroutine_promise_type_incomplete))
137 return QualType();
138
139 return PromiseType;
140}
141
142/// Look up the std::experimental::coroutine_handle<PromiseType>.
143static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
144 SourceLocation Loc) {
145 if (PromiseType.isNull())
146 return QualType();
147
148 NamespaceDecl *StdExp = S.lookupStdExperimentalNamespace();
149 assert(StdExp && "Should already be diagnosed")((StdExp && "Should already be diagnosed") ? static_cast
<void> (0) : __assert_fail ("StdExp && \"Should already be diagnosed\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 149, __PRETTY_FUNCTION__))
;
150
151 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
152 Loc, Sema::LookupOrdinaryName);
153 if (!S.LookupQualifiedName(Result, StdExp)) {
154 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
155 << "std::experimental::coroutine_handle";
156 return QualType();
157 }
158
159 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
160 if (!CoroHandle) {
161 Result.suppressDiagnostics();
162 // We found something weird. Complain about the first thing we found.
163 NamedDecl *Found = *Result.begin();
164 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
165 return QualType();
166 }
167
168 // Form template argument list for coroutine_handle<Promise>.
169 TemplateArgumentListInfo Args(Loc, Loc);
170 Args.addArgument(TemplateArgumentLoc(
171 TemplateArgument(PromiseType),
172 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
173
174 // Build the template-id.
175 QualType CoroHandleType =
176 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
177 if (CoroHandleType.isNull())
178 return QualType();
179 if (S.RequireCompleteType(Loc, CoroHandleType,
180 diag::err_coroutine_type_missing_specialization))
181 return QualType();
182
183 return CoroHandleType;
184}
185
186static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
187 StringRef Keyword) {
188 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
189 // a function body.
190 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
191 // appear in a default argument." But the diagnostic QoI here could be
192 // improved to inform the user that default arguments specifically are not
193 // allowed.
194 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
195 if (!FD) {
196 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
197 ? diag::err_coroutine_objc_method
198 : diag::err_coroutine_outside_function) << Keyword;
199 return false;
200 }
201
202 // An enumeration for mapping the diagnostic type to the correct diagnostic
203 // selection index.
204 enum InvalidFuncDiag {
205 DiagCtor = 0,
206 DiagDtor,
207 DiagMain,
208 DiagConstexpr,
209 DiagAutoRet,
210 DiagVarargs,
211 DiagConsteval,
212 };
213 bool Diagnosed = false;
214 auto DiagInvalid = [&](InvalidFuncDiag ID) {
215 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
216 Diagnosed = true;
217 return false;
218 };
219
220 // Diagnose when a constructor, destructor
221 // or the function 'main' are declared as a coroutine.
222 auto *MD = dyn_cast<CXXMethodDecl>(FD);
223 // [class.ctor]p11: "A constructor shall not be a coroutine."
224 if (MD && isa<CXXConstructorDecl>(MD))
225 return DiagInvalid(DiagCtor);
226 // [class.dtor]p17: "A destructor shall not be a coroutine."
227 else if (MD && isa<CXXDestructorDecl>(MD))
228 return DiagInvalid(DiagDtor);
229 // [basic.start.main]p3: "The function main shall not be a coroutine."
230 else if (FD->isMain())
231 return DiagInvalid(DiagMain);
232
233 // Emit a diagnostics for each of the following conditions which is not met.
234 // [expr.const]p2: "An expression e is a core constant expression unless the
235 // evaluation of e [...] would evaluate one of the following expressions:
236 // [...] an await-expression [...] a yield-expression."
237 if (FD->isConstexpr())
238 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
239 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
240 // placeholder type shall not be a coroutine."
241 if (FD->getReturnType()->isUndeducedType())
242 DiagInvalid(DiagAutoRet);
243 // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
244 // coroutine shall not terminate with an ellipsis that is not part of a
245 // parameter-declaration."
246 if (FD->isVariadic())
247 DiagInvalid(DiagVarargs);
248
249 return !Diagnosed;
250}
251
252static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S,
253 SourceLocation Loc) {
254 DeclarationName OpName =
255 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
256 LookupResult Operators(SemaRef, OpName, SourceLocation(),
257 Sema::LookupOperatorName);
258 SemaRef.LookupName(Operators, S);
259
260 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous")((!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!Operators.isAmbiguous() && \"Operator lookup cannot be ambiguous\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 260, __PRETTY_FUNCTION__))
;
261 const auto &Functions = Operators.asUnresolvedSet();
262 bool IsOverloaded =
263 Functions.size() > 1 ||
264 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
265 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
266 SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
267 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
268 Functions.begin(), Functions.end());
269 assert(CoawaitOp)((CoawaitOp) ? static_cast<void> (0) : __assert_fail ("CoawaitOp"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 269, __PRETTY_FUNCTION__))
;
270 return CoawaitOp;
271}
272
273/// Build a call to 'operator co_await' if there is a suitable operator for
274/// the given expression.
275static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc,
276 Expr *E,
277 UnresolvedLookupExpr *Lookup) {
278 UnresolvedSet<16> Functions;
279 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
280 return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
281}
282
283static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
284 SourceLocation Loc, Expr *E) {
285 ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
286 if (R.isInvalid())
287 return ExprError();
288 return buildOperatorCoawaitCall(SemaRef, Loc, E,
289 cast<UnresolvedLookupExpr>(R.get()));
290}
291
292static Expr *buildBuiltinCall(Sema &S, SourceLocation Loc, Builtin::ID Id,
293 MultiExprArg CallArgs) {
294 StringRef Name = S.Context.BuiltinInfo.getName(Id);
295 LookupResult R(S, &S.Context.Idents.get(Name), Loc, Sema::LookupOrdinaryName);
296 S.LookupName(R, S.TUScope, /*AllowBuiltinCreation=*/true);
297
298 auto *BuiltInDecl = R.getAsSingle<FunctionDecl>();
299 assert(BuiltInDecl && "failed to find builtin declaration")((BuiltInDecl && "failed to find builtin declaration"
) ? static_cast<void> (0) : __assert_fail ("BuiltInDecl && \"failed to find builtin declaration\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 299, __PRETTY_FUNCTION__))
;
300
301 ExprResult DeclRef =
302 S.BuildDeclRefExpr(BuiltInDecl, BuiltInDecl->getType(), VK_LValue, Loc);
303 assert(DeclRef.isUsable() && "Builtin reference cannot fail")((DeclRef.isUsable() && "Builtin reference cannot fail"
) ? static_cast<void> (0) : __assert_fail ("DeclRef.isUsable() && \"Builtin reference cannot fail\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 303, __PRETTY_FUNCTION__))
;
304
305 ExprResult Call =
306 S.BuildCallExpr(/*Scope=*/nullptr, DeclRef.get(), Loc, CallArgs, Loc);
307
308 assert(!Call.isInvalid() && "Call to builtin cannot fail!")((!Call.isInvalid() && "Call to builtin cannot fail!"
) ? static_cast<void> (0) : __assert_fail ("!Call.isInvalid() && \"Call to builtin cannot fail!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 308, __PRETTY_FUNCTION__))
;
309 return Call.get();
310}
311
312static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
313 SourceLocation Loc) {
314 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
315 if (CoroHandleType.isNull())
316 return ExprError();
317
318 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
319 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
320 Sema::LookupOrdinaryName);
321 if (!S.LookupQualifiedName(Found, LookupCtx)) {
322 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
323 << "from_address";
324 return ExprError();
325 }
326
327 Expr *FramePtr =
328 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {});
329
330 CXXScopeSpec SS;
331 ExprResult FromAddr =
332 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
333 if (FromAddr.isInvalid())
334 return ExprError();
335
336 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
337}
338
339struct ReadySuspendResumeResult {
340 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
341 Expr *Results[3];
342 OpaqueValueExpr *OpaqueValue;
343 bool IsInvalid;
344};
345
346static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
347 StringRef Name, MultiExprArg Args) {
348 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
349
350 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
351 CXXScopeSpec SS;
352 ExprResult Result = S.BuildMemberReferenceExpr(
353 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
354 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
355 /*Scope=*/nullptr);
356 if (Result.isInvalid())
357 return ExprError();
358
359 // We meant exactly what we asked for. No need for typo correction.
360 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
361 S.clearDelayedTypo(TE);
362 S.Diag(Loc, diag::err_no_member)
363 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
364 << Base->getSourceRange();
365 return ExprError();
366 }
367
368 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
369}
370
371// See if return type is coroutine-handle and if so, invoke builtin coro-resume
372// on its address. This is to enable experimental support for coroutine-handle
373// returning await_suspend that results in a guaranteed tail call to the target
374// coroutine.
375static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
376 SourceLocation Loc) {
377 if (RetType->isReferenceType())
378 return nullptr;
379 Type const *T = RetType.getTypePtr();
380 if (!T->isClassType() && !T->isStructureType())
381 return nullptr;
382
383 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
384 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
385 // a private function in SemaExprCXX.cpp
386
387 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
388 if (AddressExpr.isInvalid())
389 return nullptr;
390
391 Expr *JustAddress = AddressExpr.get();
392 // FIXME: Check that the type of AddressExpr is void*
393 return buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_resume,
394 JustAddress);
395}
396
397/// Build calls to await_ready, await_suspend, and await_resume for a co_await
398/// expression.
399static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
400 SourceLocation Loc, Expr *E) {
401 OpaqueValueExpr *Operand = new (S.Context)
402 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
403
404 // Assume invalid until we see otherwise.
405 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/true};
406
407 ExprResult CoroHandleRes = buildCoroutineHandle(S, CoroPromise->getType(), Loc);
408 if (CoroHandleRes.isInvalid())
409 return Calls;
410 Expr *CoroHandle = CoroHandleRes.get();
411
412 const StringRef Funcs[] = {"await_ready", "await_suspend", "await_resume"};
413 MultiExprArg Args[] = {None, CoroHandle, None};
414 for (size_t I = 0, N = llvm::array_lengthof(Funcs); I != N; ++I) {
415 ExprResult Result = buildMemberCall(S, Operand, Loc, Funcs[I], Args[I]);
416 if (Result.isInvalid())
417 return Calls;
418 Calls.Results[I] = Result.get();
419 }
420
421 // Assume the calls are valid; all further checking should make them invalid.
422 Calls.IsInvalid = false;
423
424 using ACT = ReadySuspendResumeResult::AwaitCallType;
425 CallExpr *AwaitReady = cast<CallExpr>(Calls.Results[ACT::ACT_Ready]);
426 if (!AwaitReady->getType()->isDependentType()) {
427 // [expr.await]p3 [...]
428 // — await-ready is the expression e.await_ready(), contextually converted
429 // to bool.
430 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
431 if (Conv.isInvalid()) {
432 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
433 diag::note_await_ready_no_bool_conversion);
434 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
435 << AwaitReady->getDirectCallee() << E->getSourceRange();
436 Calls.IsInvalid = true;
437 }
438 Calls.Results[ACT::ACT_Ready] = Conv.get();
439 }
440 CallExpr *AwaitSuspend = cast<CallExpr>(Calls.Results[ACT::ACT_Suspend]);
441 if (!AwaitSuspend->getType()->isDependentType()) {
442 // [expr.await]p3 [...]
443 // - await-suspend is the expression e.await_suspend(h), which shall be
444 // a prvalue of type void or bool.
445 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
446
447 // Experimental support for coroutine_handle returning await_suspend.
448 if (Expr *TailCallSuspend = maybeTailCall(S, RetType, AwaitSuspend, Loc))
449 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
450 else {
451 // non-class prvalues always have cv-unqualified types
452 if (RetType->isReferenceType() ||
453 (!RetType->isBooleanType() && !RetType->isVoidType())) {
454 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
455 diag::err_await_suspend_invalid_return_type)
456 << RetType;
457 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
458 << AwaitSuspend->getDirectCallee();
459 Calls.IsInvalid = true;
460 }
461 }
462 }
463
464 return Calls;
465}
466
467static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
468 SourceLocation Loc, StringRef Name,
469 MultiExprArg Args) {
470
471 // Form a reference to the promise.
472 ExprResult PromiseRef = S.BuildDeclRefExpr(
473 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
474 if (PromiseRef.isInvalid())
475 return ExprError();
476
477 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
478}
479
480VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
481 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")((isa<FunctionDecl>(CurContext) && "not in a function scope"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 481, __PRETTY_FUNCTION__))
;
12
Field 'CurContext' is a 'FunctionDecl'
13
'?' condition is true
482 auto *FD = cast<FunctionDecl>(CurContext);
14
Field 'CurContext' is a 'FunctionDecl'
483 bool IsThisDependentType = [&] {
484 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
485 return MD->isInstance() && MD->getThisType()->isDependentType();
486 else
487 return false;
488 }();
489
490 QualType T = FD->getType()->isDependentType() || IsThisDependentType
15.1
'IsThisDependentType' is false
15.1
'IsThisDependentType' is false
15
Assuming the condition is false
16
'?' condition is false
491 ? Context.DependentTy 492 : lookupPromiseType(*this, FD, Loc);
17
Calling 'lookupPromiseType'
493 if (T.isNull()) 494 return nullptr; 495 496 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(), 497 &PP.getIdentifierTable().get("__promise"), T, 498 Context.getTrivialTypeSourceInfo(T, Loc), SC_None); 499 CheckVariableDeclarationType(VD); 500 if (VD->isInvalidDecl()) 501 return nullptr; 502 503 auto *ScopeInfo = getCurFunction(); 504 // Build a list of arguments, based on the coroutine functions arguments, 505 // that will be passed to the promise type's constructor. 506 llvm::SmallVector<Expr *, 4> CtorArgExprs; 507 508 // Add implicit object parameter. 509 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) { 510 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 511 ExprResult ThisExpr = ActOnCXXThis(Loc); 512 if (ThisExpr.isInvalid()) 513 return nullptr; 514 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 515 if (ThisExpr.isInvalid()) 516 return nullptr; 517 CtorArgExprs.push_back(ThisExpr.get()); 518 } 519 } 520 521 auto &Moves = ScopeInfo->CoroutineParameterMoves; 522 for (auto *PD : FD->parameters()) { 523 if (PD->getType()->isDependentType()) 524 continue; 525 526 auto RefExpr = ExprEmpty(); 527 auto Move = Moves.find(PD); 528 assert(Move != Moves.end() &&((Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? static_cast<void> (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 529, __PRETTY_FUNCTION__))
529 "Coroutine function parameter not inserted into move map")((Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? static_cast<void> (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 529, __PRETTY_FUNCTION__))
; 530 // If a reference to the function parameter exists in the coroutine 531 // frame, use that reference. 532 auto *MoveDecl = 533 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl()); 534 RefExpr = 535 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(), 536 ExprValueKind::VK_LValue, FD->getLocation()); 537 if (RefExpr.isInvalid()) 538 return nullptr; 539 CtorArgExprs.push_back(RefExpr.get()); 540 } 541 542 // Create an initialization sequence for the promise type using the 543 // constructor arguments, wrapped in a parenthesized list expression. 544 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(), 545 CtorArgExprs, FD->getLocation()); 546 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD); 547 InitializationKind Kind = InitializationKind::CreateForInit( 548 VD->getLocation(), /*DirectInit=*/true, PLE); 549 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs, 550 /*TopLevelOfInitList=*/false, 551 /*TreatUnavailableAsInvalid=*/false); 552 553 // Attempt to initialize the promise type with the arguments. 554 // If that fails, fall back to the promise type's default constructor. 555 if (InitSeq) { 556 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs); 557 if (Result.isInvalid()) { 558 VD->setInvalidDecl(); 559 } else if (Result.get()) { 560 VD->setInit(MaybeCreateExprWithCleanups(Result.get())); 561 VD->setInitStyle(VarDecl::CallInit); 562 CheckCompleteVariableDeclaration(VD); 563 } 564 } else 565 ActOnUninitializedDecl(VD); 566 567 FD->addDecl(VD); 568 return VD; 569} 570 571/// Check that this is a context in which a coroutine suspension can appear. 572static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc, 573 StringRef Keyword, 574 bool IsImplicit = false) { 575 if (!isValidCoroutineContext(S, Loc, Keyword))
3
Taking false branch
576 return nullptr; 577 578 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope")((isa<FunctionDecl>(S.CurContext) && "not in a function scope"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(S.CurContext) && \"not in a function scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 578, __PRETTY_FUNCTION__))
;
4
Assuming field 'CurContext' is a 'FunctionDecl'
5
'?' condition is true
579 580 auto *ScopeInfo = S.getCurFunction(); 581 assert(ScopeInfo && "missing function scope for function")((ScopeInfo && "missing function scope for function")
? static_cast<void> (0) : __assert_fail ("ScopeInfo && \"missing function scope for function\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 581, __PRETTY_FUNCTION__))
;
6
Assuming 'ScopeInfo' is non-null
7
'?' condition is true
582 583 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit) 584 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword); 585 586 if (ScopeInfo->CoroutinePromise)
8
Assuming field 'CoroutinePromise' is null
9
Taking false branch
587 return ScopeInfo; 588 589 if (!S.buildCoroutineParameterMoves(Loc))
10
Taking false branch
590 return nullptr; 591 592 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
11
Calling 'Sema::buildCoroutinePromise'
593 if (!ScopeInfo->CoroutinePromise) 594 return nullptr; 595 596 return ScopeInfo; 597} 598 599bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc, 600 StringRef Keyword) { 601 if (!checkCoroutineContext(*this, KWLoc, Keyword))
2
Calling 'checkCoroutineContext'
602 return false; 603 auto *ScopeInfo = getCurFunction(); 604 assert(ScopeInfo->CoroutinePromise)((ScopeInfo->CoroutinePromise) ? static_cast<void> (
0) : __assert_fail ("ScopeInfo->CoroutinePromise", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 604, __PRETTY_FUNCTION__))
; 605 606 // If we have existing coroutine statements then we have already built 607 // the initial and final suspend points. 608 if (!ScopeInfo->NeedsCoroutineSuspends) 609 return true; 610 611 ScopeInfo->setNeedsCoroutineSuspends(false); 612 613 auto *Fn = cast<FunctionDecl>(CurContext); 614 SourceLocation Loc = Fn->getLocation(); 615 // Build the initial suspend point 616 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult { 617 ExprResult Suspend = 618 buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None); 619 if (Suspend.isInvalid()) 620 return StmtError(); 621 Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get()); 622 if (Suspend.isInvalid()) 623 return StmtError(); 624 Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(), 625 /*IsImplicit*/ true); 626 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false); 627 if (Suspend.isInvalid()) { 628 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required) 629 << ((Name == "initial_suspend") ? 0 : 1); 630 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword; 631 return StmtError(); 632 } 633 return cast<Stmt>(Suspend.get()); 634 }; 635 636 StmtResult InitSuspend = buildSuspends("initial_suspend"); 637 if (InitSuspend.isInvalid()) 638 return true; 639 640 StmtResult FinalSuspend = buildSuspends("final_suspend"); 641 if (FinalSuspend.isInvalid()) 642 return true; 643 644 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get()); 645 646 return true; 647} 648 649// Recursively walks up the scope hierarchy until either a 'catch' or a function 650// scope is found, whichever comes first. 651static bool isWithinCatchScope(Scope *S) { 652 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but 653 // lambdas that use 'co_await' are allowed. The loop below ends when a 654 // function scope is found in order to ensure the following behavior: 655 // 656 // void foo() { // <- function scope 657 // try { // 658 // co_await x; // <- 'co_await' is OK within a function scope 659 // } catch { // <- catch scope 660 // co_await x; // <- 'co_await' is not OK within a catch scope 661 // []() { // <- function scope 662 // co_await x; // <- 'co_await' is OK within a function scope 663 // }(); 664 // } 665 // } 666 while (S && !(S->getFlags() & Scope::FnScope)) { 667 if (S->getFlags() & Scope::CatchScope) 668 return true; 669 S = S->getParent(); 670 } 671 return false; 672} 673 674// [expr.await]p2, emphasis added: "An await-expression shall appear only in 675// a *potentially evaluated* expression within the compound-statement of a 676// function-body *outside of a handler* [...] A context within a function 677// where an await-expression can appear is called a suspension context of the 678// function." 679static void checkSuspensionContext(Sema &S, SourceLocation Loc, 680 StringRef Keyword) { 681 // First emphasis of [expr.await]p2: must be a potentially evaluated context. 682 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of 683 // \c sizeof. 684 if (S.isUnevaluatedContext()) 685 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword; 686 687 // Second emphasis of [expr.await]p2: must be outside of an exception handler. 688 if (isWithinCatchScope(S.getCurScope())) 689 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword; 690} 691 692ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) { 693 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) { 694 CorrectDelayedTyposInExpr(E); 695 return ExprError(); 696 } 697 698 checkSuspensionContext(*this, Loc, "co_await"); 699 700 if (E->getType()->isPlaceholderType()) { 701 ExprResult R = CheckPlaceholderExpr(E); 702 if (R.isInvalid()) return ExprError(); 703 E = R.get(); 704 } 705 ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc); 706 if (Lookup.isInvalid()) 707 return ExprError(); 708 return BuildUnresolvedCoawaitExpr(Loc, E, 709 cast<UnresolvedLookupExpr>(Lookup.get())); 710} 711 712ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *E, 713 UnresolvedLookupExpr *Lookup) { 714 auto *FSI = checkCoroutineContext(*this, Loc, "co_await"); 715 if (!FSI) 716 return ExprError(); 717 718 if (E->getType()->isPlaceholderType()) { 719 ExprResult R = CheckPlaceholderExpr(E); 720 if (R.isInvalid()) 721 return ExprError(); 722 E = R.get(); 723 } 724 725 auto *Promise = FSI->CoroutinePromise; 726 if (Promise->getType()->isDependentType()) { 727 Expr *Res = 728 new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup); 729 return Res; 730 } 731 732 auto *RD = Promise->getType()->getAsCXXRecordDecl(); 733 if (lookupMember(*this, "await_transform", RD, Loc)) { 734 ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E); 735 if (R.isInvalid()) { 736 Diag(Loc, 737 diag::note_coroutine_promise_implicit_await_transform_required_here) 738 << E->getSourceRange(); 739 return ExprError(); 740 } 741 E = R.get(); 742 } 743 ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup); 744 if (Awaitable.isInvalid()) 745 return ExprError(); 746 747 return BuildResolvedCoawaitExpr(Loc, Awaitable.get()); 748} 749 750ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *E, 751 bool IsImplicit) { 752 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit); 753 if (!Coroutine) 754 return ExprError(); 755 756 if (E->getType()->isPlaceholderType()) { 757 ExprResult R = CheckPlaceholderExpr(E); 758 if (R.isInvalid()) return ExprError(); 759 E = R.get(); 760 } 761 762 if (E->getType()->isDependentType()) { 763 Expr *Res = new (Context) 764 CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit); 765 return Res; 766 } 767 768 // If the expression is a temporary, materialize it as an lvalue so that we 769 // can use it multiple times. 770 if (E->getValueKind() == VK_RValue) 771 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 772 773 // The location of the `co_await` token cannot be used when constructing 774 // the member call expressions since it's before the location of `Expr`, which 775 // is used as the start of the member call expression. 776 SourceLocation CallLoc = E->getExprLoc(); 777 778 // Build the await_ready, await_suspend, await_resume calls. 779 ReadySuspendResumeResult RSS = 780 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, E); 781 if (RSS.IsInvalid) 782 return ExprError(); 783 784 Expr *Res = 785 new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1], 786 RSS.Results[2], RSS.OpaqueValue, IsImplicit); 787 788 return Res; 789} 790 791ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) { 792 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) { 793 CorrectDelayedTyposInExpr(E); 794 return ExprError(); 795 } 796 797 checkSuspensionContext(*this, Loc, "co_yield"); 798 799 // Build yield_value call. 800 ExprResult Awaitable = buildPromiseCall( 801 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E); 802 if (Awaitable.isInvalid()) 803 return ExprError(); 804 805 // Build 'operator co_await' call. 806 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get()); 807 if (Awaitable.isInvalid()) 808 return ExprError(); 809 810 return BuildCoyieldExpr(Loc, Awaitable.get()); 811} 812ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) { 813 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield"); 814 if (!Coroutine) 815 return ExprError(); 816 817 if (E->getType()->isPlaceholderType()) { 818 ExprResult R = CheckPlaceholderExpr(E); 819 if (R.isInvalid()) return ExprError(); 820 E = R.get(); 821 } 822 823 if (E->getType()->isDependentType()) { 824 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E); 825 return Res; 826 } 827 828 // If the expression is a temporary, materialize it as an lvalue so that we 829 // can use it multiple times. 830 if (E->getValueKind() == VK_RValue) 831 E = CreateMaterializeTemporaryExpr(E->getType(), E, true); 832 833 // Build the await_ready, await_suspend, await_resume calls. 834 ReadySuspendResumeResult RSS = 835 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, Loc, E); 836 if (RSS.IsInvalid) 837 return ExprError(); 838 839 Expr *Res = 840 new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1], 841 RSS.Results[2], RSS.OpaqueValue); 842 843 return Res; 844} 845 846StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) { 847 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
1
Calling 'Sema::ActOnCoroutineBodyStart'
848 CorrectDelayedTyposInExpr(E); 849 return StmtError(); 850 } 851 return BuildCoreturnStmt(Loc, E); 852} 853 854StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E, 855 bool IsImplicit) { 856 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit); 857 if (!FSI) 858 return StmtError(); 859 860 if (E && E->getType()->isPlaceholderType() && 861 !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) { 862 ExprResult R = CheckPlaceholderExpr(E); 863 if (R.isInvalid()) return StmtError(); 864 E = R.get(); 865 } 866 867 // Move the return value if we can 868 if (E) { 869 auto NRVOCandidate = this->getCopyElisionCandidate(E->getType(), E, CES_AsIfByStdMove); 870 if (NRVOCandidate) { 871 InitializedEntity Entity = 872 InitializedEntity::InitializeResult(Loc, E->getType(), NRVOCandidate); 873 ExprResult MoveResult = this->PerformMoveOrCopyInitialization( 874 Entity, NRVOCandidate, E->getType(), E); 875 if (MoveResult.get()) 876 E = MoveResult.get(); 877 } 878 } 879 880 // FIXME: If the operand is a reference to a variable that's about to go out 881 // of scope, we should treat the operand as an xvalue for this overload 882 // resolution. 883 VarDecl *Promise = FSI->CoroutinePromise; 884 ExprResult PC; 885 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) { 886 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E); 887 } else { 888 E = MakeFullDiscardedValueExpr(E).get(); 889 PC = buildPromiseCall(*this, Promise, Loc, "return_void", None); 890 } 891 if (PC.isInvalid()) 892 return StmtError(); 893 894 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get(); 895 896 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit); 897 return Res; 898} 899 900/// Look up the std::nothrow object. 901static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) { 902 NamespaceDecl *Std = S.getStdNamespace(); 903 assert(Std && "Should already be diagnosed")((Std && "Should already be diagnosed") ? static_cast
<void> (0) : __assert_fail ("Std && \"Should already be diagnosed\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 903, __PRETTY_FUNCTION__))
; 904 905 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc, 906 Sema::LookupOrdinaryName); 907 if (!S.LookupQualifiedName(Result, Std)) { 908 // FIXME: <experimental/coroutine> should have been included already. 909 // If we require it to include <new> then this diagnostic is no longer 910 // needed. 911 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found); 912 return nullptr; 913 } 914 915 auto *VD = Result.getAsSingle<VarDecl>(); 916 if (!VD) { 917 Result.suppressDiagnostics(); 918 // We found something weird. Complain about the first thing we found. 919 NamedDecl *Found = *Result.begin(); 920 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow); 921 return nullptr; 922 } 923 924 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc); 925 if (DR.isInvalid()) 926 return nullptr; 927 928 return DR.get(); 929} 930 931// Find an appropriate delete for the promise. 932static FunctionDecl *findDeleteForPromise(Sema &S, SourceLocation Loc, 933 QualType PromiseType) { 934 FunctionDecl *OperatorDelete = nullptr; 935 936 DeclarationName DeleteName = 937 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete); 938 939 auto *PointeeRD = PromiseType->getAsCXXRecordDecl(); 940 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type")((PointeeRD && "PromiseType must be a CxxRecordDecl type"
) ? static_cast<void> (0) : __assert_fail ("PointeeRD && \"PromiseType must be a CxxRecordDecl type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 940, __PRETTY_FUNCTION__))
; 941 942 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete)) 943 return nullptr; 944 945 if (!OperatorDelete) { 946 // Look for a global declaration. 947 const bool CanProvideSize = S.isCompleteType(Loc, PromiseType); 948 const bool Overaligned = false; 949 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize, 950 Overaligned, DeleteName); 951 } 952 S.MarkFunctionReferenced(Loc, OperatorDelete); 953 return OperatorDelete; 954} 955 956 957void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) { 958 FunctionScopeInfo *Fn = getCurFunction(); 959 assert(Fn && Fn->isCoroutine() && "not a coroutine")((Fn && Fn->isCoroutine() && "not a coroutine"
) ? static_cast<void> (0) : __assert_fail ("Fn && Fn->isCoroutine() && \"not a coroutine\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 959, __PRETTY_FUNCTION__))
; 960 if (!Body) { 961 assert(FD->isInvalidDecl() &&((FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? static_cast<void> (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 962, __PRETTY_FUNCTION__))
962 "a null body is only allowed for invalid declarations")((FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? static_cast<void> (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 962, __PRETTY_FUNCTION__))
; 963 return; 964 } 965 // We have a function that uses coroutine keywords, but we failed to build 966 // the promise type. 967 if (!Fn->CoroutinePromise) 968 return FD->setInvalidDecl(); 969 970 if (isa<CoroutineBodyStmt>(Body)) { 971 // Nothing todo. the body is already a transformed coroutine body statement. 972 return; 973 } 974 975 // Coroutines [stmt.return]p1: 976 // A return statement shall not appear in a coroutine. 977 if (Fn->FirstReturnLoc.isValid()) { 978 assert(Fn->FirstCoroutineStmtLoc.isValid() &&((Fn->FirstCoroutineStmtLoc.isValid() && "first coroutine location not set"
) ? static_cast<void> (0) : __assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 979, __PRETTY_FUNCTION__))
979 "first coroutine location not set")((Fn->FirstCoroutineStmtLoc.isValid() && "first coroutine location not set"
) ? static_cast<void> (0) : __assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 979, __PRETTY_FUNCTION__))
; 980 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine); 981 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 982 << Fn->getFirstCoroutineStmtKeyword(); 983 } 984 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body); 985 if (Builder.isInvalid() || !Builder.buildStatements()) 986 return FD->setInvalidDecl(); 987 988 // Build body for the coroutine wrapper statement. 989 Body = CoroutineBodyStmt::Create(Context, Builder); 990} 991 992CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD, 993 sema::FunctionScopeInfo &Fn, 994 Stmt *Body) 995 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()), 996 IsPromiseDependentType( 997 !Fn.CoroutinePromise || 998 Fn.CoroutinePromise->getType()->isDependentType()) { 999 this->Body = Body; 1000 1001 for (auto KV : Fn.CoroutineParameterMoves) 1002 this->ParamMovesVector.push_back(KV.second); 1003 this->ParamMoves = this->ParamMovesVector; 1004 1005 if (!IsPromiseDependentType) { 1006 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl(); 1007 assert(PromiseRecordDecl && "Type should have already been checked")((PromiseRecordDecl && "Type should have already been checked"
) ? static_cast<void> (0) : __assert_fail ("PromiseRecordDecl && \"Type should have already been checked\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1007, __PRETTY_FUNCTION__))
; 1008 } 1009 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend(); 1010} 1011 1012bool CoroutineStmtBuilder::buildStatements() { 1013 assert(this->IsValid && "coroutine already invalid")((this->IsValid && "coroutine already invalid") ? static_cast
<void> (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1013, __PRETTY_FUNCTION__))
; 1014 this->IsValid = makeReturnObject(); 1015 if (this->IsValid && !IsPromiseDependentType) 1016 buildDependentStatements(); 1017 return this->IsValid; 1018} 1019 1020bool CoroutineStmtBuilder::buildDependentStatements() { 1021 assert(this->IsValid && "coroutine already invalid")((this->IsValid && "coroutine already invalid") ? static_cast
<void> (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1021, __PRETTY_FUNCTION__))
; 1022 assert(!this->IsPromiseDependentType &&((!this->IsPromiseDependentType && "coroutine cannot have a dependent promise type"
) ? static_cast<void> (0) : __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1023, __PRETTY_FUNCTION__))
1023 "coroutine cannot have a dependent promise type")((!this->IsPromiseDependentType && "coroutine cannot have a dependent promise type"
) ? static_cast<void> (0) : __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1023, __PRETTY_FUNCTION__))
; 1024 this->IsValid = makeOnException() && makeOnFallthrough() && 1025 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() && 1026 makeNewAndDeleteExpr(); 1027 return this->IsValid; 1028} 1029 1030bool CoroutineStmtBuilder::makePromiseStmt() { 1031 // Form a declaration statement for the promise declaration, so that AST 1032 // visitors can more easily find it. 1033 StmtResult PromiseStmt = 1034 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc); 1035 if (PromiseStmt.isInvalid()) 1036 return false; 1037 1038 this->Promise = PromiseStmt.get(); 1039 return true; 1040} 1041 1042bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() { 1043 if (Fn.hasInvalidCoroutineSuspends()) 1044 return false; 1045 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first); 1046 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second); 1047 return true; 1048} 1049 1050static bool diagReturnOnAllocFailure(Sema &S, Expr *E, 1051 CXXRecordDecl *PromiseRecordDecl, 1052 FunctionScopeInfo &Fn) { 1053 auto Loc = E->getExprLoc(); 1054 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) { 1055 auto *Decl = DeclRef->getDecl(); 1056 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) { 1057 if (Method->isStatic()) 1058 return true; 1059 else 1060 Loc = Decl->getLocation(); 1061 } 1062 } 1063 1064 S.Diag( 1065 Loc, 1066 diag::err_coroutine_promise_get_return_object_on_allocation_failure) 1067 << PromiseRecordDecl; 1068 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1069 << Fn.getFirstCoroutineStmtKeyword(); 1070 return false; 1071} 1072 1073bool CoroutineStmtBuilder::makeReturnOnAllocFailure() { 1074 assert(!IsPromiseDependentType &&((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1075, __PRETTY_FUNCTION__))
1075 "cannot make statement while the promise type is dependent")((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1075, __PRETTY_FUNCTION__))
; 1076 1077 // [dcl.fct.def.coroutine]/8 1078 // The unqualified-id get_return_object_on_allocation_failure is looked up in 1079 // the scope of class P by class member access lookup (3.4.5). ... 1080 // If an allocation function returns nullptr, ... the coroutine return value 1081 // is obtained by a call to ... get_return_object_on_allocation_failure(). 1082 1083 DeclarationName DN = 1084 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure"); 1085 LookupResult Found(S, DN, Loc, Sema::LookupMemberName); 1086 if (!S.LookupQualifiedName(Found, PromiseRecordDecl)) 1087 return true; 1088 1089 CXXScopeSpec SS; 1090 ExprResult DeclNameExpr = 1091 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false); 1092 if (DeclNameExpr.isInvalid()) 1093 return false; 1094 1095 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn)) 1096 return false; 1097 1098 ExprResult ReturnObjectOnAllocationFailure = 1099 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc); 1100 if (ReturnObjectOnAllocationFailure.isInvalid()) 1101 return false; 1102 1103 StmtResult ReturnStmt = 1104 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get()); 1105 if (ReturnStmt.isInvalid()) { 1106 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here) 1107 << DN; 1108 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1109 << Fn.getFirstCoroutineStmtKeyword(); 1110 return false; 1111 } 1112 1113 this->ReturnStmtOnAllocFailure = ReturnStmt.get(); 1114 return true; 1115} 1116 1117bool CoroutineStmtBuilder::makeNewAndDeleteExpr() { 1118 // Form and check allocation and deallocation calls. 1119 assert(!IsPromiseDependentType &&((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1120, __PRETTY_FUNCTION__))
1120 "cannot make statement while the promise type is dependent")((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1120, __PRETTY_FUNCTION__))
; 1121 QualType PromiseType = Fn.CoroutinePromise->getType(); 1122 1123 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type)) 1124 return false; 1125 1126 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr; 1127 1128 // [dcl.fct.def.coroutine]/7 1129 // Lookup allocation functions using a parameter list composed of the 1130 // requested size of the coroutine state being allocated, followed by 1131 // the coroutine function's arguments. If a matching allocation function 1132 // exists, use it. Otherwise, use an allocation function that just takes 1133 // the requested size. 1134 1135 FunctionDecl *OperatorNew = nullptr; 1136 FunctionDecl *OperatorDelete = nullptr; 1137 FunctionDecl *UnusedResult = nullptr; 1138 bool PassAlignment = false; 1139 SmallVector<Expr *, 1> PlacementArgs; 1140 1141 // [dcl.fct.def.coroutine]/7 1142 // "The allocation function’s name is looked up in the scope of P. 1143 // [...] If the lookup finds an allocation function in the scope of P, 1144 // overload resolution is performed on a function call created by assembling 1145 // an argument list. The first argument is the amount of space requested, 1146 // and has type std::size_t. The lvalues p1 ... pn are the succeeding 1147 // arguments." 1148 // 1149 // ...where "p1 ... pn" are defined earlier as: 1150 // 1151 // [dcl.fct.def.coroutine]/3 1152 // "For a coroutine f that is a non-static member function, let P1 denote the 1153 // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types 1154 // of the function parameters; otherwise let P1 ... Pn be the types of the 1155 // function parameters. Let p1 ... pn be lvalues denoting those objects." 1156 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) { 1157 if (MD->isInstance() && !isLambdaCallOperator(MD)) { 1158 ExprResult ThisExpr = S.ActOnCXXThis(Loc); 1159 if (ThisExpr.isInvalid()) 1160 return false; 1161 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get()); 1162 if (ThisExpr.isInvalid()) 1163 return false; 1164 PlacementArgs.push_back(ThisExpr.get()); 1165 } 1166 } 1167 for (auto *PD : FD.parameters()) { 1168 if (PD->getType()->isDependentType()) 1169 continue; 1170 1171 // Build a reference to the parameter. 1172 auto PDLoc = PD->getLocation(); 1173 ExprResult PDRefExpr = 1174 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(), 1175 ExprValueKind::VK_LValue, PDLoc); 1176 if (PDRefExpr.isInvalid()) 1177 return false; 1178 1179 PlacementArgs.push_back(PDRefExpr.get()); 1180 } 1181 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1182 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1183 /*isArray*/ false, PassAlignment, PlacementArgs, 1184 OperatorNew, UnusedResult, /*Diagnose*/ false); 1185 1186 // [dcl.fct.def.coroutine]/7 1187 // "If no matching function is found, overload resolution is performed again 1188 // on a function call created by passing just the amount of space required as 1189 // an argument of type std::size_t." 1190 if (!OperatorNew && !PlacementArgs.empty()) { 1191 PlacementArgs.clear(); 1192 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class, 1193 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1194 /*isArray*/ false, PassAlignment, PlacementArgs, 1195 OperatorNew, UnusedResult, /*Diagnose*/ false); 1196 } 1197 1198 // [dcl.fct.def.coroutine]/7 1199 // "The allocation function’s name is looked up in the scope of P. If this 1200 // lookup fails, the allocation function’s name is looked up in the global 1201 // scope." 1202 if (!OperatorNew) { 1203 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global, 1204 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1205 /*isArray*/ false, PassAlignment, PlacementArgs, 1206 OperatorNew, UnusedResult); 1207 } 1208 1209 bool IsGlobalOverload = 1210 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext()); 1211 // If we didn't find a class-local new declaration and non-throwing new 1212 // was is required then we need to lookup the non-throwing global operator 1213 // instead. 1214 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) { 1215 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc); 1216 if (!StdNoThrow) 1217 return false; 1218 PlacementArgs = {StdNoThrow}; 1219 OperatorNew = nullptr; 1220 S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both, 1221 /*DeleteScope*/ Sema::AFS_Both, PromiseType, 1222 /*isArray*/ false, PassAlignment, PlacementArgs, 1223 OperatorNew, UnusedResult); 1224 } 1225 1226 if (!OperatorNew) 1227 return false; 1228 1229 if (RequiresNoThrowAlloc) { 1230 const auto *FT = OperatorNew->getType()->getAs<FunctionProtoType>(); 1231 if (!FT->isNothrow(/*ResultIfDependent*/ false)) { 1232 S.Diag(OperatorNew->getLocation(), 1233 diag::err_coroutine_promise_new_requires_nothrow) 1234 << OperatorNew; 1235 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required) 1236 << OperatorNew; 1237 return false; 1238 } 1239 } 1240 1241 if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr) 1242 return false; 1243 1244 Expr *FramePtr = 1245 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_frame, {}); 1246 1247 Expr *FrameSize = 1248 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_size, {}); 1249 1250 // Make new call. 1251 1252 ExprResult NewRef = 1253 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc); 1254 if (NewRef.isInvalid()) 1255 return false; 1256 1257 SmallVector<Expr *, 2> NewArgs(1, FrameSize); 1258 for (auto Arg : PlacementArgs) 1259 NewArgs.push_back(Arg); 1260 1261 ExprResult NewExpr = 1262 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc); 1263 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false); 1264 if (NewExpr.isInvalid()) 1265 return false; 1266 1267 // Make delete call. 1268 1269 QualType OpDeleteQualType = OperatorDelete->getType(); 1270 1271 ExprResult DeleteRef = 1272 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc); 1273 if (DeleteRef.isInvalid()) 1274 return false; 1275 1276 Expr *CoroFree = 1277 buildBuiltinCall(S, Loc, Builtin::BI__builtin_coro_free, {FramePtr}); 1278 1279 SmallVector<Expr *, 2> DeleteArgs{CoroFree}; 1280 1281 // Check if we need to pass the size. 1282 const auto *OpDeleteType = 1283 OpDeleteQualType.getTypePtr()->getAs<FunctionProtoType>(); 1284 if (OpDeleteType->getNumParams() > 1) 1285 DeleteArgs.push_back(FrameSize); 1286 1287 ExprResult DeleteExpr = 1288 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc); 1289 DeleteExpr = 1290 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false); 1291 if (DeleteExpr.isInvalid()) 1292 return false; 1293 1294 this->Allocate = NewExpr.get(); 1295 this->Deallocate = DeleteExpr.get(); 1296 1297 return true; 1298} 1299 1300bool CoroutineStmtBuilder::makeOnFallthrough() { 1301 assert(!IsPromiseDependentType &&((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1302, __PRETTY_FUNCTION__))
1302 "cannot make statement while the promise type is dependent")((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1302, __PRETTY_FUNCTION__))
; 1303 1304 // [dcl.fct.def.coroutine]/4 1305 // The unqualified-ids 'return_void' and 'return_value' are looked up in 1306 // the scope of class P. If both are found, the program is ill-formed. 1307 bool HasRVoid, HasRValue; 1308 LookupResult LRVoid = 1309 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid); 1310 LookupResult LRValue = 1311 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue); 1312 1313 StmtResult Fallthrough; 1314 if (HasRVoid && HasRValue) { 1315 // FIXME Improve this diagnostic 1316 S.Diag(FD.getLocation(), 1317 diag::err_coroutine_promise_incompatible_return_functions) 1318 << PromiseRecordDecl; 1319 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(), 1320 diag::note_member_first_declared_here) 1321 << LRVoid.getLookupName(); 1322 S.Diag(LRValue.getRepresentativeDecl()->getLocation(), 1323 diag::note_member_first_declared_here) 1324 << LRValue.getLookupName(); 1325 return false; 1326 } else if (!HasRVoid && !HasRValue) { 1327 // FIXME: The PDTS currently specifies this case as UB, not ill-formed. 1328 // However we still diagnose this as an error since until the PDTS is fixed. 1329 S.Diag(FD.getLocation(), 1330 diag::err_coroutine_promise_requires_return_function) 1331 << PromiseRecordDecl; 1332 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1333 << PromiseRecordDecl; 1334 return false; 1335 } else if (HasRVoid) { 1336 // If the unqualified-id return_void is found, flowing off the end of a 1337 // coroutine is equivalent to a co_return with no operand. Otherwise, 1338 // flowing off the end of a coroutine results in undefined behavior. 1339 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr, 1340 /*IsImplicit*/false); 1341 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get()); 1342 if (Fallthrough.isInvalid()) 1343 return false; 1344 } 1345 1346 this->OnFallthrough = Fallthrough.get(); 1347 return true; 1348} 1349 1350bool CoroutineStmtBuilder::makeOnException() { 1351 // Try to form 'p.unhandled_exception();' 1352 assert(!IsPromiseDependentType &&((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1353, __PRETTY_FUNCTION__))
1353 "cannot make statement while the promise type is dependent")((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1353, __PRETTY_FUNCTION__))
; 1354 1355 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions; 1356 1357 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) { 1358 auto DiagID = 1359 RequireUnhandledException 1360 ? diag::err_coroutine_promise_unhandled_exception_required 1361 : diag:: 1362 warn_coroutine_promise_unhandled_exception_required_with_exceptions; 1363 S.Diag(Loc, DiagID) << PromiseRecordDecl; 1364 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here) 1365 << PromiseRecordDecl; 1366 return !RequireUnhandledException; 1367 } 1368 1369 // If exceptions are disabled, don't try to build OnException. 1370 if (!S.getLangOpts().CXXExceptions) 1371 return true; 1372 1373 ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc, 1374 "unhandled_exception", None); 1375 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc, 1376 /*DiscardedValue*/ false); 1377 if (UnhandledException.isInvalid()) 1378 return false; 1379 1380 // Since the body of the coroutine will be wrapped in try-catch, it will 1381 // be incompatible with SEH __try if present in a function. 1382 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) { 1383 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions); 1384 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1385 << Fn.getFirstCoroutineStmtKeyword(); 1386 return false; 1387 } 1388 1389 this->OnException = UnhandledException.get(); 1390 return true; 1391} 1392 1393bool CoroutineStmtBuilder::makeReturnObject() { 1394 // Build implicit 'p.get_return_object()' expression and form initialization 1395 // of return type from it. 1396 ExprResult ReturnObject = 1397 buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None); 1398 if (ReturnObject.isInvalid()) 1399 return false; 1400 1401 this->ReturnValue = ReturnObject.get(); 1402 return true; 1403} 1404 1405static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) { 1406 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) { 1407 auto *MethodDecl = MbrRef->getMethodDecl(); 1408 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here) 1409 << MethodDecl; 1410 } 1411 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here) 1412 << Fn.getFirstCoroutineStmtKeyword(); 1413} 1414 1415bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() { 1416 assert(!IsPromiseDependentType &&((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1417, __PRETTY_FUNCTION__))
1417 "cannot make statement while the promise type is dependent")((!IsPromiseDependentType && "cannot make statement while the promise type is dependent"
) ? static_cast<void> (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1417, __PRETTY_FUNCTION__))
; 1418 assert(this->ReturnValue && "ReturnValue must be already formed")((this->ReturnValue && "ReturnValue must be already formed"
) ? static_cast<void> (0) : __assert_fail ("this->ReturnValue && \"ReturnValue must be already formed\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1418, __PRETTY_FUNCTION__))
; 1419 1420 QualType const GroType = this->ReturnValue->getType(); 1421 assert(!GroType->isDependentType() &&((!GroType->isDependentType() && "get_return_object type must no longer be dependent"
) ? static_cast<void> (0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1422, __PRETTY_FUNCTION__))
1422 "get_return_object type must no longer be dependent")((!GroType->isDependentType() && "get_return_object type must no longer be dependent"
) ? static_cast<void> (0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1422, __PRETTY_FUNCTION__))
; 1423 1424 QualType const FnRetType = FD.getReturnType(); 1425 assert(!FnRetType->isDependentType() &&((!FnRetType->isDependentType() && "get_return_object type must no longer be dependent"
) ? static_cast<void> (0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1426, __PRETTY_FUNCTION__))
1426 "get_return_object type must no longer be dependent")((!FnRetType->isDependentType() && "get_return_object type must no longer be dependent"
) ? static_cast<void> (0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1426, __PRETTY_FUNCTION__))
; 1427 1428 if (FnRetType->isVoidType()) { 1429 ExprResult Res = 1430 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false); 1431 if (Res.isInvalid()) 1432 return false; 1433 1434 this->ResultDecl = Res.get(); 1435 return true; 1436 } 1437 1438 if (GroType->isVoidType()) { 1439 // Trigger a nice error message. 1440 InitializedEntity Entity = 1441 InitializedEntity::InitializeResult(Loc, FnRetType, false); 1442 S.PerformMoveOrCopyInitialization(Entity, nullptr, FnRetType, ReturnValue); 1443 noteMemberDeclaredHere(S, ReturnValue, Fn); 1444 return false; 1445 } 1446 1447 auto *GroDecl = VarDecl::Create( 1448 S.Context, &FD, FD.getLocation(), FD.getLocation(), 1449 &S.PP.getIdentifierTable().get("__coro_gro"), GroType, 1450 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None); 1451 1452 S.CheckVariableDeclarationType(GroDecl); 1453 if (GroDecl->isInvalidDecl()) 1454 return false; 1455 1456 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl); 1457 ExprResult Res = S.PerformMoveOrCopyInitialization(Entity, nullptr, GroType, 1458 this->ReturnValue); 1459 if (Res.isInvalid()) 1460 return false; 1461 1462 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false); 1463 if (Res.isInvalid()) 1464 return false; 1465 1466 S.AddInitializerToDecl(GroDecl, Res.get(), 1467 /*DirectInit=*/false); 1468 1469 S.FinalizeDeclaration(GroDecl); 1470 1471 // Form a declaration statement for the return declaration, so that AST 1472 // visitors can more easily find it. 1473 StmtResult GroDeclStmt = 1474 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc); 1475 if (GroDeclStmt.isInvalid()) 1476 return false; 1477 1478 this->ResultDecl = GroDeclStmt.get(); 1479 1480 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc); 1481 if (declRef.isInvalid()) 1482 return false; 1483 1484 StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get()); 1485 if (ReturnStmt.isInvalid()) { 1486 noteMemberDeclaredHere(S, ReturnValue, Fn); 1487 return false; 1488 } 1489 if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl) 1490 GroDecl->setNRVOVariable(true); 1491 1492 this->ReturnStmt = ReturnStmt.get(); 1493 return true; 1494} 1495 1496// Create a static_cast\<T&&>(expr). 1497static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) { 1498 if (T.isNull()) 1499 T = E->getType(); 1500 QualType TargetType = S.BuildReferenceType( 1501 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName()); 1502 SourceLocation ExprLoc = E->getBeginLoc(); 1503 TypeSourceInfo *TargetLoc = 1504 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc); 1505 1506 return S 1507 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E, 1508 SourceRange(ExprLoc, ExprLoc), E->getSourceRange()) 1509 .get(); 1510} 1511 1512/// Build a variable declaration for move parameter. 1513static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type, 1514 IdentifierInfo *II) { 1515 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc); 1516 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type, 1517 TInfo, SC_None); 1518 Decl->setImplicit(); 1519 return Decl; 1520} 1521 1522// Build statements that move coroutine function parameters to the coroutine 1523// frame, and store them on the function scope info. 1524bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) { 1525 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")((isa<FunctionDecl>(CurContext) && "not in a function scope"
) ? static_cast<void> (0) : __assert_fail ("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1525, __PRETTY_FUNCTION__))
; 1526 auto *FD = cast<FunctionDecl>(CurContext); 1527 1528 auto *ScopeInfo = getCurFunction(); 1529 assert(ScopeInfo->CoroutineParameterMoves.empty() &&((ScopeInfo->CoroutineParameterMoves.empty() && "Should not build parameter moves twice"
) ? static_cast<void> (0) : __assert_fail ("ScopeInfo->CoroutineParameterMoves.empty() && \"Should not build parameter moves twice\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1530, __PRETTY_FUNCTION__))
1530 "Should not build parameter moves twice")((ScopeInfo->CoroutineParameterMoves.empty() && "Should not build parameter moves twice"
) ? static_cast<void> (0) : __assert_fail ("ScopeInfo->CoroutineParameterMoves.empty() && \"Should not build parameter moves twice\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/Sema/SemaCoroutine.cpp"
, 1530, __PRETTY_FUNCTION__))
; 1531 1532 for (auto *PD : FD->parameters()) { 1533 if (PD->getType()->isDependentType()) 1534 continue; 1535 1536 ExprResult PDRefExpr = 1537 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(), 1538 ExprValueKind::VK_LValue, Loc); // FIXME: scope? 1539 if (PDRefExpr.isInvalid()) 1540 return false; 1541 1542 Expr *CExpr = nullptr; 1543 if (PD->getType()->getAsCXXRecordDecl() || 1544 PD->getType()->isRValueReferenceType()) 1545 CExpr = castForMoving(*this, PDRefExpr.get()); 1546 else 1547 CExpr = PDRefExpr.get(); 1548 1549 auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier()); 1550 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true); 1551 1552 // Convert decl to a statement. 1553 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc); 1554 if (Stmt.isInvalid()) 1555 return false; 1556 1557 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get())); 1558 } 1559 return true; 1560} 1561 1562StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) { 1563 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args); 1564 if (!Res) 1565 return StmtError(); 1566 return Res; 1567} 1568 1569ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc, 1570 SourceLocation FuncLoc) { 1571 if (!StdCoroutineTraitsCache) { 1572 if (auto StdExp = lookupStdExperimentalNamespace()) { 1573 LookupResult Result(*this, 1574 &PP.getIdentifierTable().get("coroutine_traits"), 1575 FuncLoc, LookupOrdinaryName); 1576 if (!LookupQualifiedName(Result, StdExp)) { 1577 Diag(KwLoc, diag::err_implied_coroutine_type_not_found) 1578 << "std::experimental::coroutine_traits"; 1579 return nullptr; 1580 } 1581 if (!(StdCoroutineTraitsCache = 1582 Result.getAsSingle<ClassTemplateDecl>())) { 1583 Result.suppressDiagnostics(); 1584 NamedDecl *Found = *Result.begin(); 1585 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits); 1586 return nullptr; 1587 } 1588 } 1589 } 1590 return StdCoroutineTraitsCache; 1591}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h

1//===- DeclCXX.h - Classes for representing C++ declarations --*- 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 C++ Decl subclasses, other than those for templates
11/// (found in DeclTemplate.h) and friends (in DeclFriend.h).
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLCXX_H
16#define LLVM_CLANG_AST_DECLCXX_H
17
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/ASTUnresolvedSet.h"
20#include "clang/AST/Attr.h"
21#include "clang/AST/Decl.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExternalASTSource.h"
26#include "clang/AST/LambdaCapture.h"
27#include "clang/AST/NestedNameSpecifier.h"
28#include "clang/AST/Redeclarable.h"
29#include "clang/AST/Stmt.h"
30#include "clang/AST/Type.h"
31#include "clang/AST/TypeLoc.h"
32#include "clang/AST/UnresolvedSet.h"
33#include "clang/Basic/LLVM.h"
34#include "clang/Basic/Lambda.h"
35#include "clang/Basic/LangOptions.h"
36#include "clang/Basic/OperatorKinds.h"
37#include "clang/Basic/SourceLocation.h"
38#include "clang/Basic/Specifiers.h"
39#include "llvm/ADT/ArrayRef.h"
40#include "llvm/ADT/DenseMap.h"
41#include "llvm/ADT/PointerIntPair.h"
42#include "llvm/ADT/PointerUnion.h"
43#include "llvm/ADT/STLExtras.h"
44#include "llvm/ADT/iterator_range.h"
45#include "llvm/BinaryFormat/Dwarf.h"
46#include "llvm/Support/Casting.h"
47#include "llvm/Support/Compiler.h"
48#include "llvm/Support/PointerLikeTypeTraits.h"
49#include "llvm/Support/TrailingObjects.h"
50#include <cassert>
51#include <cstddef>
52#include <iterator>
53#include <memory>
54#include <vector>
55
56namespace clang {
57
58class ClassTemplateDecl;
59class ConstructorUsingShadowDecl;
60class CXXBasePath;
61class CXXBasePaths;
62class CXXConstructorDecl;
63class CXXDestructorDecl;
64class CXXFinalOverriderMap;
65class CXXIndirectPrimaryBaseSet;
66class CXXMethodDecl;
67class DecompositionDecl;
68class DiagnosticBuilder;
69class FriendDecl;
70class FunctionTemplateDecl;
71class IdentifierInfo;
72class MemberSpecializationInfo;
73class TemplateDecl;
74class TemplateParameterList;
75class UsingDecl;
76
77/// Represents an access specifier followed by colon ':'.
78///
79/// An objects of this class represents sugar for the syntactic occurrence
80/// of an access specifier followed by a colon in the list of member
81/// specifiers of a C++ class definition.
82///
83/// Note that they do not represent other uses of access specifiers,
84/// such as those occurring in a list of base specifiers.
85/// Also note that this class has nothing to do with so-called
86/// "access declarations" (C++98 11.3 [class.access.dcl]).
87class AccessSpecDecl : public Decl {
88 /// The location of the ':'.
89 SourceLocation ColonLoc;
90
91 AccessSpecDecl(AccessSpecifier AS, DeclContext *DC,
92 SourceLocation ASLoc, SourceLocation ColonLoc)
93 : Decl(AccessSpec, DC, ASLoc), ColonLoc(ColonLoc) {
94 setAccess(AS);
95 }
96
97 AccessSpecDecl(EmptyShell Empty) : Decl(AccessSpec, Empty) {}
98
99 virtual void anchor();
100
101public:
102 /// The location of the access specifier.
103 SourceLocation getAccessSpecifierLoc() const { return getLocation(); }
104
105 /// Sets the location of the access specifier.
106 void setAccessSpecifierLoc(SourceLocation ASLoc) { setLocation(ASLoc); }
107
108 /// The location of the colon following the access specifier.
109 SourceLocation getColonLoc() const { return ColonLoc; }
110
111 /// Sets the location of the colon.
112 void setColonLoc(SourceLocation CLoc) { ColonLoc = CLoc; }
113
114 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
115 return SourceRange(getAccessSpecifierLoc(), getColonLoc());
116 }
117
118 static AccessSpecDecl *Create(ASTContext &C, AccessSpecifier AS,
119 DeclContext *DC, SourceLocation ASLoc,
120 SourceLocation ColonLoc) {
121 return new (C, DC) AccessSpecDecl(AS, DC, ASLoc, ColonLoc);
122 }
123
124 static AccessSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == AccessSpec; }
129};
130
131/// Represents a base class of a C++ class.
132///
133/// Each CXXBaseSpecifier represents a single, direct base class (or
134/// struct) of a C++ class (or struct). It specifies the type of that
135/// base class, whether it is a virtual or non-virtual base, and what
136/// level of access (public, protected, private) is used for the
137/// derivation. For example:
138///
139/// \code
140/// class A { };
141/// class B { };
142/// class C : public virtual A, protected B { };
143/// \endcode
144///
145/// In this code, C will have two CXXBaseSpecifiers, one for "public
146/// virtual A" and the other for "protected B".
147class CXXBaseSpecifier {
148 /// The source code range that covers the full base
149 /// specifier, including the "virtual" (if present) and access
150 /// specifier (if present).
151 SourceRange Range;
152
153 /// The source location of the ellipsis, if this is a pack
154 /// expansion.
155 SourceLocation EllipsisLoc;
156
157 /// Whether this is a virtual base class or not.
158 unsigned Virtual : 1;
159
160 /// Whether this is the base of a class (true) or of a struct (false).
161 ///
162 /// This determines the mapping from the access specifier as written in the
163 /// source code to the access specifier used for semantic analysis.
164 unsigned BaseOfClass : 1;
165
166 /// Access specifier as written in the source code (may be AS_none).
167 ///
168 /// The actual type of data stored here is an AccessSpecifier, but we use
169 /// "unsigned" here to work around a VC++ bug.
170 unsigned Access : 2;
171
172 /// Whether the class contains a using declaration
173 /// to inherit the named class's constructors.
174 unsigned InheritConstructors : 1;
175
176 /// The type of the base class.
177 ///
178 /// This will be a class or struct (or a typedef of such). The source code
179 /// range does not include the \c virtual or the access specifier.
180 TypeSourceInfo *BaseTypeInfo;
181
182public:
183 CXXBaseSpecifier() = default;
184 CXXBaseSpecifier(SourceRange R, bool V, bool BC, AccessSpecifier A,
185 TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
186 : Range(R), EllipsisLoc(EllipsisLoc), Virtual(V), BaseOfClass(BC),
187 Access(A), InheritConstructors(false), BaseTypeInfo(TInfo) {}
188
189 /// Retrieves the source range that contains the entire base specifier.
190 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
191 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
192 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
193
194 /// Get the location at which the base class type was written.
195 SourceLocation getBaseTypeLoc() const LLVM_READONLY__attribute__((__pure__)) {
196 return BaseTypeInfo->getTypeLoc().getBeginLoc();
197 }
198
199 /// Determines whether the base class is a virtual base class (or not).
200 bool isVirtual() const { return Virtual; }
201
202 /// Determine whether this base class is a base of a class declared
203 /// with the 'class' keyword (vs. one declared with the 'struct' keyword).
204 bool isBaseOfClass() const { return BaseOfClass; }
205
206 /// Determine whether this base specifier is a pack expansion.
207 bool isPackExpansion() const { return EllipsisLoc.isValid(); }
208
209 /// Determine whether this base class's constructors get inherited.
210 bool getInheritConstructors() const { return InheritConstructors; }
211
212 /// Set that this base class's constructors should be inherited.
213 void setInheritConstructors(bool Inherit = true) {
214 InheritConstructors = Inherit;
215 }
216
217 /// For a pack expansion, determine the location of the ellipsis.
218 SourceLocation getEllipsisLoc() const {
219 return EllipsisLoc;
220 }
221
222 /// Returns the access specifier for this base specifier.
223 ///
224 /// This is the actual base specifier as used for semantic analysis, so
225 /// the result can never be AS_none. To retrieve the access specifier as
226 /// written in the source code, use getAccessSpecifierAsWritten().
227 AccessSpecifier getAccessSpecifier() const {
228 if ((AccessSpecifier)Access == AS_none)
229 return BaseOfClass? AS_private : AS_public;
230 else
231 return (AccessSpecifier)Access;
232 }
233
234 /// Retrieves the access specifier as written in the source code
235 /// (which may mean that no access specifier was explicitly written).
236 ///
237 /// Use getAccessSpecifier() to retrieve the access specifier for use in
238 /// semantic analysis.
239 AccessSpecifier getAccessSpecifierAsWritten() const {
240 return (AccessSpecifier)Access;
241 }
242
243 /// Retrieves the type of the base class.
244 ///
245 /// This type will always be an unqualified class type.
246 QualType getType() const {
247 return BaseTypeInfo->getType().getUnqualifiedType();
248 }
249
250 /// Retrieves the type and source location of the base class.
251 TypeSourceInfo *getTypeSourceInfo() const { return BaseTypeInfo; }
252};
253
254/// Represents a C++ struct/union/class.
255class CXXRecordDecl : public RecordDecl {
256 friend class ASTDeclReader;
257 friend class ASTDeclWriter;
258 friend class ASTNodeImporter;
259 friend class ASTReader;
260 friend class ASTRecordWriter;
261 friend class ASTWriter;
262 friend class DeclContext;
263 friend class LambdaExpr;
264
265 friend void FunctionDecl::setPure(bool);
266 friend void TagDecl::startDefinition();
267
268 /// Values used in DefinitionData fields to represent special members.
269 enum SpecialMemberFlags {
270 SMF_DefaultConstructor = 0x1,
271 SMF_CopyConstructor = 0x2,
272 SMF_MoveConstructor = 0x4,
273 SMF_CopyAssignment = 0x8,
274 SMF_MoveAssignment = 0x10,
275 SMF_Destructor = 0x20,
276 SMF_All = 0x3f
277 };
278
279 struct DefinitionData {
280 /// True if this class has any user-declared constructors.
281 unsigned UserDeclaredConstructor : 1;
282
283 /// The user-declared special members which this class has.
284 unsigned UserDeclaredSpecialMembers : 6;
285
286 /// True when this class is an aggregate.
287 unsigned Aggregate : 1;
288
289 /// True when this class is a POD-type.
290 unsigned PlainOldData : 1;
291
292 /// True when this class is empty for traits purposes, that is:
293 /// * has no data members other than 0-width bit-fields and empty fields
294 /// marked [[no_unique_address]]
295 /// * has no virtual function/base, and
296 /// * doesn't inherit from a non-empty class.
297 /// Doesn't take union-ness into account.
298 unsigned Empty : 1;
299
300 /// True when this class is polymorphic, i.e., has at
301 /// least one virtual member or derives from a polymorphic class.
302 unsigned Polymorphic : 1;
303
304 /// True when this class is abstract, i.e., has at least
305 /// one pure virtual function, (that can come from a base class).
306 unsigned Abstract : 1;
307
308 /// True when this class is standard-layout, per the applicable
309 /// language rules (including DRs).
310 unsigned IsStandardLayout : 1;
311
312 /// True when this class was standard-layout under the C++11
313 /// definition.
314 ///
315 /// C++11 [class]p7. A standard-layout class is a class that:
316 /// * has no non-static data members of type non-standard-layout class (or
317 /// array of such types) or reference,
318 /// * has no virtual functions (10.3) and no virtual base classes (10.1),
319 /// * has the same access control (Clause 11) for all non-static data
320 /// members
321 /// * has no non-standard-layout base classes,
322 /// * either has no non-static data members in the most derived class and at
323 /// most one base class with non-static data members, or has no base
324 /// classes with non-static data members, and
325 /// * has no base classes of the same type as the first non-static data
326 /// member.
327 unsigned IsCXX11StandardLayout : 1;
328
329 /// True when any base class has any declared non-static data
330 /// members or bit-fields.
331 /// This is a helper bit of state used to implement IsStandardLayout more
332 /// efficiently.
333 unsigned HasBasesWithFields : 1;
334
335 /// True when any base class has any declared non-static data
336 /// members.
337 /// This is a helper bit of state used to implement IsCXX11StandardLayout
338 /// more efficiently.
339 unsigned HasBasesWithNonStaticDataMembers : 1;
340
341 /// True when there are private non-static data members.
342 unsigned HasPrivateFields : 1;
343
344 /// True when there are protected non-static data members.
345 unsigned HasProtectedFields : 1;
346
347 /// True when there are private non-static data members.
348 unsigned HasPublicFields : 1;
349
350 /// True if this class (or any subobject) has mutable fields.
351 unsigned HasMutableFields : 1;
352
353 /// True if this class (or any nested anonymous struct or union)
354 /// has variant members.
355 unsigned HasVariantMembers : 1;
356
357 /// True if there no non-field members declared by the user.
358 unsigned HasOnlyCMembers : 1;
359
360 /// True if any field has an in-class initializer, including those
361 /// within anonymous unions or structs.
362 unsigned HasInClassInitializer : 1;
363
364 /// True if any field is of reference type, and does not have an
365 /// in-class initializer.
366 ///
367 /// In this case, value-initialization of this class is illegal in C++98
368 /// even if the class has a trivial default constructor.
369 unsigned HasUninitializedReferenceMember : 1;
370
371 /// True if any non-mutable field whose type doesn't have a user-
372 /// provided default ctor also doesn't have an in-class initializer.
373 unsigned HasUninitializedFields : 1;
374
375 /// True if there are any member using-declarations that inherit
376 /// constructors from a base class.
377 unsigned HasInheritedConstructor : 1;
378
379 /// True if there are any member using-declarations named
380 /// 'operator='.
381 unsigned HasInheritedAssignment : 1;
382
383 /// These flags are \c true if a defaulted corresponding special
384 /// member can't be fully analyzed without performing overload resolution.
385 /// @{
386 unsigned NeedOverloadResolutionForCopyConstructor : 1;
387 unsigned NeedOverloadResolutionForMoveConstructor : 1;
388 unsigned NeedOverloadResolutionForMoveAssignment : 1;
389 unsigned NeedOverloadResolutionForDestructor : 1;
390 /// @}
391
392 /// These flags are \c true if an implicit defaulted corresponding
393 /// special member would be defined as deleted.
394 /// @{
395 unsigned DefaultedCopyConstructorIsDeleted : 1;
396 unsigned DefaultedMoveConstructorIsDeleted : 1;
397 unsigned DefaultedMoveAssignmentIsDeleted : 1;
398 unsigned DefaultedDestructorIsDeleted : 1;
399 /// @}
400
401 /// The trivial special members which this class has, per
402 /// C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25,
403 /// C++11 [class.dtor]p5, or would have if the member were not suppressed.
404 ///
405 /// This excludes any user-declared but not user-provided special members
406 /// which have been declared but not yet defined.
407 unsigned HasTrivialSpecialMembers : 6;
408
409 /// These bits keep track of the triviality of special functions for the
410 /// purpose of calls. Only the bits corresponding to SMF_CopyConstructor,
411 /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
412 unsigned HasTrivialSpecialMembersForCall : 6;
413
414 /// The declared special members of this class which are known to be
415 /// non-trivial.
416 ///
417 /// This excludes any user-declared but not user-provided special members
418 /// which have been declared but not yet defined, and any implicit special
419 /// members which have not yet been declared.
420 unsigned DeclaredNonTrivialSpecialMembers : 6;
421
422 /// These bits keep track of the declared special members that are
423 /// non-trivial for the purpose of calls.
424 /// Only the bits corresponding to SMF_CopyConstructor,
425 /// SMF_MoveConstructor, and SMF_Destructor are meaningful here.
426 unsigned DeclaredNonTrivialSpecialMembersForCall : 6;
427
428 /// True when this class has a destructor with no semantic effect.
429 unsigned HasIrrelevantDestructor : 1;
430
431 /// True when this class has at least one user-declared constexpr
432 /// constructor which is neither the copy nor move constructor.
433 unsigned HasConstexprNonCopyMoveConstructor : 1;
434
435 /// True if this class has a (possibly implicit) defaulted default
436 /// constructor.
437 unsigned HasDefaultedDefaultConstructor : 1;
438
439 /// True if a defaulted default constructor for this class would
440 /// be constexpr.
441 unsigned DefaultedDefaultConstructorIsConstexpr : 1;
442
443 /// True if this class has a constexpr default constructor.
444 ///
445 /// This is true for either a user-declared constexpr default constructor
446 /// or an implicitly declared constexpr default constructor.
447 unsigned HasConstexprDefaultConstructor : 1;
448
449 /// True if a defaulted destructor for this class would be constexpr.
450 unsigned DefaultedDestructorIsConstexpr : 1;
451
452 /// True when this class contains at least one non-static data
453 /// member or base class of non-literal or volatile type.
454 unsigned HasNonLiteralTypeFieldsOrBases : 1;
455
456 /// True when visible conversion functions are already computed
457 /// and are available.
458 unsigned ComputedVisibleConversions : 1;
459
460 /// Whether we have a C++11 user-provided default constructor (not
461 /// explicitly deleted or defaulted).
462 unsigned UserProvidedDefaultConstructor : 1;
463
464 /// The special members which have been declared for this class,
465 /// either by the user or implicitly.
466 unsigned DeclaredSpecialMembers : 6;
467
468 /// Whether an implicit copy constructor could have a const-qualified
469 /// parameter, for initializing virtual bases and for other subobjects.
470 unsigned ImplicitCopyConstructorCanHaveConstParamForVBase : 1;
471 unsigned ImplicitCopyConstructorCanHaveConstParamForNonVBase : 1;
472
473 /// Whether an implicit copy assignment operator would have a
474 /// const-qualified parameter.
475 unsigned ImplicitCopyAssignmentHasConstParam : 1;
476
477 /// Whether any declared copy constructor has a const-qualified
478 /// parameter.
479 unsigned HasDeclaredCopyConstructorWithConstParam : 1;
480
481 /// Whether any declared copy assignment operator has either a
482 /// const-qualified reference parameter or a non-reference parameter.
483 unsigned HasDeclaredCopyAssignmentWithConstParam : 1;
484
485 /// Whether this class describes a C++ lambda.
486 unsigned IsLambda : 1;
487
488 /// Whether we are currently parsing base specifiers.
489 unsigned IsParsingBaseSpecifiers : 1;
490
491 unsigned HasODRHash : 1;
492
493 /// A hash of parts of the class to help in ODR checking.
494 unsigned ODRHash = 0;
495
496 /// The number of base class specifiers in Bases.
497 unsigned NumBases = 0;
498
499 /// The number of virtual base class specifiers in VBases.
500 unsigned NumVBases = 0;
501
502 /// Base classes of this class.
503 ///
504 /// FIXME: This is wasted space for a union.
505 LazyCXXBaseSpecifiersPtr Bases;
506
507 /// direct and indirect virtual base classes of this class.
508 LazyCXXBaseSpecifiersPtr VBases;
509
510 /// The conversion functions of this C++ class (but not its
511 /// inherited conversion functions).
512 ///
513 /// Each of the entries in this overload set is a CXXConversionDecl.
514 LazyASTUnresolvedSet Conversions;
515
516 /// The conversion functions of this C++ class and all those
517 /// inherited conversion functions that are visible in this class.
518 ///
519 /// Each of the entries in this overload set is a CXXConversionDecl or a
520 /// FunctionTemplateDecl.
521 LazyASTUnresolvedSet VisibleConversions;
522
523 /// The declaration which defines this record.
524 CXXRecordDecl *Definition;
525
526 /// The first friend declaration in this class, or null if there
527 /// aren't any.
528 ///
529 /// This is actually currently stored in reverse order.
530 LazyDeclPtr FirstFriend;
531
532 DefinitionData(CXXRecordDecl *D);
533
534 /// Retrieve the set of direct base classes.
535 CXXBaseSpecifier *getBases() const {
536 if (!Bases.isOffset())
537 return Bases.get(nullptr);
538 return getBasesSlowCase();
539 }
540
541 /// Retrieve the set of virtual base classes.
542 CXXBaseSpecifier *getVBases() const {
543 if (!VBases.isOffset())
544 return VBases.get(nullptr);
545 return getVBasesSlowCase();
546 }
547
548 ArrayRef<CXXBaseSpecifier> bases() const {
549 return llvm::makeArrayRef(getBases(), NumBases);
550 }
551
552 ArrayRef<CXXBaseSpecifier> vbases() const {
553 return llvm::makeArrayRef(getVBases(), NumVBases);
554 }
555
556 private:
557 CXXBaseSpecifier *getBasesSlowCase() const;
558 CXXBaseSpecifier *getVBasesSlowCase() const;
559 };
560
561 struct DefinitionData *DefinitionData;
562
563 /// Describes a C++ closure type (generated by a lambda expression).
564 struct LambdaDefinitionData : public DefinitionData {
565 using Capture = LambdaCapture;
566
567 /// Whether this lambda is known to be dependent, even if its
568 /// context isn't dependent.
569 ///
570 /// A lambda with a non-dependent context can be dependent if it occurs
571 /// within the default argument of a function template, because the
572 /// lambda will have been created with the enclosing context as its
573 /// declaration context, rather than function. This is an unfortunate
574 /// artifact of having to parse the default arguments before.
575 unsigned Dependent : 1;
576
577 /// Whether this lambda is a generic lambda.
578 unsigned IsGenericLambda : 1;
579
580 /// The Default Capture.
581 unsigned CaptureDefault : 2;
582
583 /// The number of captures in this lambda is limited 2^NumCaptures.
584 unsigned NumCaptures : 15;
585
586 /// The number of explicit captures in this lambda.
587 unsigned NumExplicitCaptures : 13;
588
589 /// The number used to indicate this lambda expression for name
590 /// mangling in the Itanium C++ ABI.
591 unsigned ManglingNumber = 0;
592
593 /// The declaration that provides context for this lambda, if the
594 /// actual DeclContext does not suffice. This is used for lambdas that
595 /// occur within default arguments of function parameters within the class
596 /// or within a data member initializer.
597 LazyDeclPtr ContextDecl;
598
599 /// The list of captures, both explicit and implicit, for this
600 /// lambda.
601 Capture *Captures = nullptr;
602
603 /// The type of the call method.
604 TypeSourceInfo *MethodTyInfo;
605
606 LambdaDefinitionData(CXXRecordDecl *D, TypeSourceInfo *Info,
607 bool Dependent, bool IsGeneric,
608 LambdaCaptureDefault CaptureDefault)
609 : DefinitionData(D), Dependent(Dependent), IsGenericLambda(IsGeneric),
610 CaptureDefault(CaptureDefault), NumCaptures(0), NumExplicitCaptures(0),
611 MethodTyInfo(Info) {
612 IsLambda = true;
613
614 // C++1z [expr.prim.lambda]p4:
615 // This class type is not an aggregate type.
616 Aggregate = false;
617 PlainOldData = false;
618 }
619 };
620
621 struct DefinitionData *dataPtr() const {
622 // Complete the redecl chain (if necessary).
623 getMostRecentDecl();
624 return DefinitionData;
625 }
626
627 struct DefinitionData &data() const {
628 auto *DD = dataPtr();
629 assert(DD && "queried property of class with no definition")((DD && "queried property of class with no definition"
) ? static_cast<void> (0) : __assert_fail ("DD && \"queried property of class with no definition\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 629, __PRETTY_FUNCTION__))
;
630 return *DD;
631 }
632
633 struct LambdaDefinitionData &getLambdaData() const {
634 // No update required: a merged definition cannot change any lambda
635 // properties.
636 auto *DD = DefinitionData;
637 assert(DD && DD->IsLambda && "queried lambda property of non-lambda class")((DD && DD->IsLambda && "queried lambda property of non-lambda class"
) ? static_cast<void> (0) : __assert_fail ("DD && DD->IsLambda && \"queried lambda property of non-lambda class\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 637, __PRETTY_FUNCTION__))
;
638 return static_cast<LambdaDefinitionData&>(*DD);
639 }
640
641 /// The template or declaration that this declaration
642 /// describes or was instantiated from, respectively.
643 ///
644 /// For non-templates, this value will be null. For record
645 /// declarations that describe a class template, this will be a
646 /// pointer to a ClassTemplateDecl. For member
647 /// classes of class template specializations, this will be the
648 /// MemberSpecializationInfo referring to the member class that was
649 /// instantiated or specialized.
650 llvm::PointerUnion<ClassTemplateDecl *, MemberSpecializationInfo *>
651 TemplateOrInstantiation;
652
653 /// Called from setBases and addedMember to notify the class that a
654 /// direct or virtual base class or a member of class type has been added.
655 void addedClassSubobject(CXXRecordDecl *Base);
656
657 /// Notify the class that member has been added.
658 ///
659 /// This routine helps maintain information about the class based on which
660 /// members have been added. It will be invoked by DeclContext::addDecl()
661 /// whenever a member is added to this record.
662 void addedMember(Decl *D);
663
664 void markedVirtualFunctionPure();
665
666 /// Get the head of our list of friend declarations, possibly
667 /// deserializing the friends from an external AST source.
668 FriendDecl *getFirstFriend() const;
669
670 /// Determine whether this class has an empty base class subobject of type X
671 /// or of one of the types that might be at offset 0 within X (per the C++
672 /// "standard layout" rules).
673 bool hasSubobjectAtOffsetZeroOfEmptyBaseType(ASTContext &Ctx,
674 const CXXRecordDecl *X);
675
676protected:
677 CXXRecordDecl(Kind K, TagKind TK, const ASTContext &C, DeclContext *DC,
678 SourceLocation StartLoc, SourceLocation IdLoc,
679 IdentifierInfo *Id, CXXRecordDecl *PrevDecl);
680
681public:
682 /// Iterator that traverses the base classes of a class.
683 using base_class_iterator = CXXBaseSpecifier *;
684
685 /// Iterator that traverses the base classes of a class.
686 using base_class_const_iterator = const CXXBaseSpecifier *;
687
688 CXXRecordDecl *getCanonicalDecl() override {
689 return cast<CXXRecordDecl>(RecordDecl::getCanonicalDecl());
690 }
691
692 const CXXRecordDecl *getCanonicalDecl() const {
693 return const_cast<CXXRecordDecl*>(this)->getCanonicalDecl();
694 }
695
696 CXXRecordDecl *getPreviousDecl() {
697 return cast_or_null<CXXRecordDecl>(
698 static_cast<RecordDecl *>(this)->getPreviousDecl());
699 }
700
701 const CXXRecordDecl *getPreviousDecl() const {
702 return const_cast<CXXRecordDecl*>(this)->getPreviousDecl();
703 }
704
705 CXXRecordDecl *getMostRecentDecl() {
706 return cast<CXXRecordDecl>(
707 static_cast<RecordDecl *>(this)->getMostRecentDecl());
708 }
709
710 const CXXRecordDecl *getMostRecentDecl() const {
711 return const_cast<CXXRecordDecl*>(this)->getMostRecentDecl();
712 }
713
714 CXXRecordDecl *getMostRecentNonInjectedDecl() {
715 CXXRecordDecl *Recent =
716 static_cast<CXXRecordDecl *>(this)->getMostRecentDecl();
717 while (Recent->isInjectedClassName()) {
718 // FIXME: Does injected class name need to be in the redeclarations chain?
719 assert(Recent->getPreviousDecl())((Recent->getPreviousDecl()) ? static_cast<void> (0)
: __assert_fail ("Recent->getPreviousDecl()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 719, __PRETTY_FUNCTION__))
;
720 Recent = Recent->getPreviousDecl();
721 }
722 return Recent;
723 }
724
725 const CXXRecordDecl *getMostRecentNonInjectedDecl() const {
726 return const_cast<CXXRecordDecl*>(this)->getMostRecentNonInjectedDecl();
727 }
728
729 CXXRecordDecl *getDefinition() const {
730 // We only need an update if we don't already know which
731 // declaration is the definition.
732 auto *DD = DefinitionData ? DefinitionData : dataPtr();
733 return DD ? DD->Definition : nullptr;
734 }
735
736 bool hasDefinition() const { return DefinitionData || dataPtr(); }
737
738 static CXXRecordDecl *Create(const ASTContext &C, TagKind TK, DeclContext *DC,
739 SourceLocation StartLoc, SourceLocation IdLoc,
740 IdentifierInfo *Id,
741 CXXRecordDecl *PrevDecl = nullptr,
742 bool DelayTypeCreation = false);
743 static CXXRecordDecl *CreateLambda(const ASTContext &C, DeclContext *DC,
744 TypeSourceInfo *Info, SourceLocation Loc,
745 bool DependentLambda, bool IsGeneric,
746 LambdaCaptureDefault CaptureDefault);
747 static CXXRecordDecl *CreateDeserialized(const ASTContext &C, unsigned ID);
748
749 bool isDynamicClass() const {
750 return data().Polymorphic || data().NumVBases != 0;
751 }
752
753 /// @returns true if class is dynamic or might be dynamic because the
754 /// definition is incomplete of dependent.
755 bool mayBeDynamicClass() const {
756 return !hasDefinition() || isDynamicClass() || hasAnyDependentBases();
757 }
758
759 /// @returns true if class is non dynamic or might be non dynamic because the
760 /// definition is incomplete of dependent.
761 bool mayBeNonDynamicClass() const {
762 return !hasDefinition() || !isDynamicClass() || hasAnyDependentBases();
763 }
764
765 void setIsParsingBaseSpecifiers() { data().IsParsingBaseSpecifiers = true; }
766
767 bool isParsingBaseSpecifiers() const {
768 return data().IsParsingBaseSpecifiers;
769 }
770
771 unsigned getODRHash() const;
772
773 /// Sets the base classes of this struct or class.
774 void setBases(CXXBaseSpecifier const * const *Bases, unsigned NumBases);
775
776 /// Retrieves the number of base classes of this class.
777 unsigned getNumBases() const { return data().NumBases; }
778
779 using base_class_range = llvm::iterator_range<base_class_iterator>;
780 using base_class_const_range =
781 llvm::iterator_range<base_class_const_iterator>;
782
783 base_class_range bases() {
784 return base_class_range(bases_begin(), bases_end());
785 }
786 base_class_const_range bases() const {
787 return base_class_const_range(bases_begin(), bases_end());
788 }
789
790 base_class_iterator bases_begin() { return data().getBases(); }
791 base_class_const_iterator bases_begin() const { return data().getBases(); }
792 base_class_iterator bases_end() { return bases_begin() + data().NumBases; }
793 base_class_const_iterator bases_end() const {
794 return bases_begin() + data().NumBases;
795 }
796
797 /// Retrieves the number of virtual base classes of this class.
798 unsigned getNumVBases() const { return data().NumVBases; }
799
800 base_class_range vbases() {
801 return base_class_range(vbases_begin(), vbases_end());
802 }
803 base_class_const_range vbases() const {
804 return base_class_const_range(vbases_begin(), vbases_end());
805 }
806
807 base_class_iterator vbases_begin() { return data().getVBases(); }
808 base_class_const_iterator vbases_begin() const { return data().getVBases(); }
809 base_class_iterator vbases_end() { return vbases_begin() + data().NumVBases; }
810 base_class_const_iterator vbases_end() const {
811 return vbases_begin() + data().NumVBases;
812 }
813
814 /// Determine whether this class has any dependent base classes which
815 /// are not the current instantiation.
816 bool hasAnyDependentBases() const;
817
818 /// Iterator access to method members. The method iterator visits
819 /// all method members of the class, including non-instance methods,
820 /// special methods, etc.
821 using method_iterator = specific_decl_iterator<CXXMethodDecl>;
822 using method_range =
823 llvm::iterator_range<specific_decl_iterator<CXXMethodDecl>>;
824
825 method_range methods() const {
826 return method_range(method_begin(), method_end());
827 }
828
829 /// Method begin iterator. Iterates in the order the methods
830 /// were declared.
831 method_iterator method_begin() const {
832 return method_iterator(decls_begin());
833 }
834
835 /// Method past-the-end iterator.
836 method_iterator method_end() const {
837 return method_iterator(decls_end());
838 }
839
840 /// Iterator access to constructor members.
841 using ctor_iterator = specific_decl_iterator<CXXConstructorDecl>;
842 using ctor_range =
843 llvm::iterator_range<specific_decl_iterator<CXXConstructorDecl>>;
844
845 ctor_range ctors() const { return ctor_range(ctor_begin(), ctor_end()); }
846
847 ctor_iterator ctor_begin() const {
848 return ctor_iterator(decls_begin());
849 }
850
851 ctor_iterator ctor_end() const {
852 return ctor_iterator(decls_end());
853 }
854
855 /// An iterator over friend declarations. All of these are defined
856 /// in DeclFriend.h.
857 class friend_iterator;
858 using friend_range = llvm::iterator_range<friend_iterator>;
859
860 friend_range friends() const;
861 friend_iterator friend_begin() const;
862 friend_iterator friend_end() const;
863 void pushFriendDecl(FriendDecl *FD);
864
865 /// Determines whether this record has any friends.
866 bool hasFriends() const {
867 return data().FirstFriend.isValid();
868 }
869
870 /// \c true if a defaulted copy constructor for this class would be
871 /// deleted.
872 bool defaultedCopyConstructorIsDeleted() const {
873 assert((!needsOverloadResolutionForCopyConstructor() ||(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 875, __PRETTY_FUNCTION__))
874 (data().DeclaredSpecialMembers & SMF_CopyConstructor)) &&(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 875, __PRETTY_FUNCTION__))
875 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers
& SMF_CopyConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForCopyConstructor() || (data().DeclaredSpecialMembers & SMF_CopyConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 875, __PRETTY_FUNCTION__))
;
876 return data().DefaultedCopyConstructorIsDeleted;
877 }
878
879 /// \c true if a defaulted move constructor for this class would be
880 /// deleted.
881 bool defaultedMoveConstructorIsDeleted() const {
882 assert((!needsOverloadResolutionForMoveConstructor() ||(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 884, __PRETTY_FUNCTION__))
883 (data().DeclaredSpecialMembers & SMF_MoveConstructor)) &&(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 884, __PRETTY_FUNCTION__))
884 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers
& SMF_MoveConstructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForMoveConstructor() || (data().DeclaredSpecialMembers & SMF_MoveConstructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 884, __PRETTY_FUNCTION__))
;
885 return data().DefaultedMoveConstructorIsDeleted;
886 }
887
888 /// \c true if a defaulted destructor for this class would be deleted.
889 bool defaultedDestructorIsDeleted() const {
890 assert((!needsOverloadResolutionForDestructor() ||(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 892, __PRETTY_FUNCTION__))
891 (data().DeclaredSpecialMembers & SMF_Destructor)) &&(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 892, __PRETTY_FUNCTION__))
892 "this property has not yet been computed by Sema")(((!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers
& SMF_Destructor)) && "this property has not yet been computed by Sema"
) ? static_cast<void> (0) : __assert_fail ("(!needsOverloadResolutionForDestructor() || (data().DeclaredSpecialMembers & SMF_Destructor)) && \"this property has not yet been computed by Sema\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 892, __PRETTY_FUNCTION__))
;
893 return data().DefaultedDestructorIsDeleted;
894 }
895
896 /// \c true if we know for sure that this class has a single,
897 /// accessible, unambiguous copy constructor that is not deleted.
898 bool hasSimpleCopyConstructor() const {
899 return !hasUserDeclaredCopyConstructor() &&
900 !data().DefaultedCopyConstructorIsDeleted;
901 }
902
903 /// \c true if we know for sure that this class has a single,
904 /// accessible, unambiguous move constructor that is not deleted.
905 bool hasSimpleMoveConstructor() const {
906 return !hasUserDeclaredMoveConstructor() && hasMoveConstructor() &&
907 !data().DefaultedMoveConstructorIsDeleted;
908 }
909
910 /// \c true if we know for sure that this class has a single,
911 /// accessible, unambiguous move assignment operator that is not deleted.
912 bool hasSimpleMoveAssignment() const {
913 return !hasUserDeclaredMoveAssignment() && hasMoveAssignment() &&
914 !data().DefaultedMoveAssignmentIsDeleted;
915 }
916
917 /// \c true if we know for sure that this class has an accessible
918 /// destructor that is not deleted.
919 bool hasSimpleDestructor() const {
920 return !hasUserDeclaredDestructor() &&
921 !data().DefaultedDestructorIsDeleted;
922 }
923
924 /// Determine whether this class has any default constructors.
925 bool hasDefaultConstructor() const {
926 return (data().DeclaredSpecialMembers & SMF_DefaultConstructor) ||
927 needsImplicitDefaultConstructor();
928 }
929
930 /// Determine if we need to declare a default constructor for
931 /// this class.
932 ///
933 /// This value is used for lazy creation of default constructors.
934 bool needsImplicitDefaultConstructor() const {
935 return !data().UserDeclaredConstructor &&
936 !(data().DeclaredSpecialMembers & SMF_DefaultConstructor) &&
937 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
938 }
939
940 /// Determine whether this class has any user-declared constructors.
941 ///
942 /// When true, a default constructor will not be implicitly declared.
943 bool hasUserDeclaredConstructor() const {
944 return data().UserDeclaredConstructor;
945 }
946
947 /// Whether this class has a user-provided default constructor
948 /// per C++11.
949 bool hasUserProvidedDefaultConstructor() const {
950 return data().UserProvidedDefaultConstructor;
951 }
952
953 /// Determine whether this class has a user-declared copy constructor.
954 ///
955 /// When false, a copy constructor will be implicitly declared.
956 bool hasUserDeclaredCopyConstructor() const {
957 return data().UserDeclaredSpecialMembers & SMF_CopyConstructor;
958 }
959
960 /// Determine whether this class needs an implicit copy
961 /// constructor to be lazily declared.
962 bool needsImplicitCopyConstructor() const {
963 return !(data().DeclaredSpecialMembers & SMF_CopyConstructor);
964 }
965
966 /// Determine whether we need to eagerly declare a defaulted copy
967 /// constructor for this class.
968 bool needsOverloadResolutionForCopyConstructor() const {
969 // C++17 [class.copy.ctor]p6:
970 // If the class definition declares a move constructor or move assignment
971 // operator, the implicitly declared copy constructor is defined as
972 // deleted.
973 // In MSVC mode, sometimes a declared move assignment does not delete an
974 // implicit copy constructor, so defer this choice to Sema.
975 if (data().UserDeclaredSpecialMembers &
976 (SMF_MoveConstructor | SMF_MoveAssignment))
977 return true;
978 return data().NeedOverloadResolutionForCopyConstructor;
979 }
980
981 /// Determine whether an implicit copy constructor for this type
982 /// would have a parameter with a const-qualified reference type.
983 bool implicitCopyConstructorHasConstParam() const {
984 return data().ImplicitCopyConstructorCanHaveConstParamForNonVBase &&
985 (isAbstract() ||
986 data().ImplicitCopyConstructorCanHaveConstParamForVBase);
987 }
988
989 /// Determine whether this class has a copy constructor with
990 /// a parameter type which is a reference to a const-qualified type.
991 bool hasCopyConstructorWithConstParam() const {
992 return data().HasDeclaredCopyConstructorWithConstParam ||
993 (needsImplicitCopyConstructor() &&
994 implicitCopyConstructorHasConstParam());
995 }
996
997 /// Whether this class has a user-declared move constructor or
998 /// assignment operator.
999 ///
1000 /// When false, a move constructor and assignment operator may be
1001 /// implicitly declared.
1002 bool hasUserDeclaredMoveOperation() const {
1003 return data().UserDeclaredSpecialMembers &
1004 (SMF_MoveConstructor | SMF_MoveAssignment);
1005 }
1006
1007 /// Determine whether this class has had a move constructor
1008 /// declared by the user.
1009 bool hasUserDeclaredMoveConstructor() const {
1010 return data().UserDeclaredSpecialMembers & SMF_MoveConstructor;
1011 }
1012
1013 /// Determine whether this class has a move constructor.
1014 bool hasMoveConstructor() const {
1015 return (data().DeclaredSpecialMembers & SMF_MoveConstructor) ||
1016 needsImplicitMoveConstructor();
1017 }
1018
1019 /// Set that we attempted to declare an implicit copy
1020 /// constructor, but overload resolution failed so we deleted it.
1021 void setImplicitCopyConstructorIsDeleted() {
1022 assert((data().DefaultedCopyConstructorIsDeleted ||(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1024, __PRETTY_FUNCTION__))
1023 needsOverloadResolutionForCopyConstructor()) &&(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1024, __PRETTY_FUNCTION__))
1024 "Copy constructor should not be deleted")(((data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor
()) && "Copy constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedCopyConstructorIsDeleted || needsOverloadResolutionForCopyConstructor()) && \"Copy constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1024, __PRETTY_FUNCTION__))
;
1025 data().DefaultedCopyConstructorIsDeleted = true;
1026 }
1027
1028 /// Set that we attempted to declare an implicit move
1029 /// constructor, but overload resolution failed so we deleted it.
1030 void setImplicitMoveConstructorIsDeleted() {
1031 assert((data().DefaultedMoveConstructorIsDeleted ||(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1033, __PRETTY_FUNCTION__))
1032 needsOverloadResolutionForMoveConstructor()) &&(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1033, __PRETTY_FUNCTION__))
1033 "move constructor should not be deleted")(((data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor
()) && "move constructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveConstructorIsDeleted || needsOverloadResolutionForMoveConstructor()) && \"move constructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1033, __PRETTY_FUNCTION__))
;
1034 data().DefaultedMoveConstructorIsDeleted = true;
1035 }
1036
1037 /// Set that we attempted to declare an implicit destructor,
1038 /// but overload resolution failed so we deleted it.
1039 void setImplicitDestructorIsDeleted() {
1040 assert((data().DefaultedDestructorIsDeleted ||(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1042, __PRETTY_FUNCTION__))
1041 needsOverloadResolutionForDestructor()) &&(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1042, __PRETTY_FUNCTION__))
1042 "destructor should not be deleted")(((data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor
()) && "destructor should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedDestructorIsDeleted || needsOverloadResolutionForDestructor()) && \"destructor should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1042, __PRETTY_FUNCTION__))
;
1043 data().DefaultedDestructorIsDeleted = true;
1044 }
1045
1046 /// Determine whether this class should get an implicit move
1047 /// constructor or if any existing special member function inhibits this.
1048 bool needsImplicitMoveConstructor() const {
1049 return !(data().DeclaredSpecialMembers & SMF_MoveConstructor) &&
1050 !hasUserDeclaredCopyConstructor() &&
1051 !hasUserDeclaredCopyAssignment() &&
1052 !hasUserDeclaredMoveAssignment() &&
1053 !hasUserDeclaredDestructor();
1054 }
1055
1056 /// Determine whether we need to eagerly declare a defaulted move
1057 /// constructor for this class.
1058 bool needsOverloadResolutionForMoveConstructor() const {
1059 return data().NeedOverloadResolutionForMoveConstructor;
1060 }
1061
1062 /// Determine whether this class has a user-declared copy assignment
1063 /// operator.
1064 ///
1065 /// When false, a copy assignment operator will be implicitly declared.
1066 bool hasUserDeclaredCopyAssignment() const {
1067 return data().UserDeclaredSpecialMembers & SMF_CopyAssignment;
1068 }
1069
1070 /// Determine whether this class needs an implicit copy
1071 /// assignment operator to be lazily declared.
1072 bool needsImplicitCopyAssignment() const {
1073 return !(data().DeclaredSpecialMembers & SMF_CopyAssignment);
1074 }
1075
1076 /// Determine whether we need to eagerly declare a defaulted copy
1077 /// assignment operator for this class.
1078 bool needsOverloadResolutionForCopyAssignment() const {
1079 return data().HasMutableFields;
1080 }
1081
1082 /// Determine whether an implicit copy assignment operator for this
1083 /// type would have a parameter with a const-qualified reference type.
1084 bool implicitCopyAssignmentHasConstParam() const {
1085 return data().ImplicitCopyAssignmentHasConstParam;
1086 }
1087
1088 /// Determine whether this class has a copy assignment operator with
1089 /// a parameter type which is a reference to a const-qualified type or is not
1090 /// a reference.
1091 bool hasCopyAssignmentWithConstParam() const {
1092 return data().HasDeclaredCopyAssignmentWithConstParam ||
1093 (needsImplicitCopyAssignment() &&
1094 implicitCopyAssignmentHasConstParam());
1095 }
1096
1097 /// Determine whether this class has had a move assignment
1098 /// declared by the user.
1099 bool hasUserDeclaredMoveAssignment() const {
1100 return data().UserDeclaredSpecialMembers & SMF_MoveAssignment;
1101 }
1102
1103 /// Determine whether this class has a move assignment operator.
1104 bool hasMoveAssignment() const {
1105 return (data().DeclaredSpecialMembers & SMF_MoveAssignment) ||
1106 needsImplicitMoveAssignment();
1107 }
1108
1109 /// Set that we attempted to declare an implicit move assignment
1110 /// operator, but overload resolution failed so we deleted it.
1111 void setImplicitMoveAssignmentIsDeleted() {
1112 assert((data().DefaultedMoveAssignmentIsDeleted ||(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1114, __PRETTY_FUNCTION__))
1113 needsOverloadResolutionForMoveAssignment()) &&(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1114, __PRETTY_FUNCTION__))
1114 "move assignment should not be deleted")(((data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment
()) && "move assignment should not be deleted") ? static_cast
<void> (0) : __assert_fail ("(data().DefaultedMoveAssignmentIsDeleted || needsOverloadResolutionForMoveAssignment()) && \"move assignment should not be deleted\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1114, __PRETTY_FUNCTION__))
;
1115 data().DefaultedMoveAssignmentIsDeleted = true;
1116 }
1117
1118 /// Determine whether this class should get an implicit move
1119 /// assignment operator or if any existing special member function inhibits
1120 /// this.
1121 bool needsImplicitMoveAssignment() const {
1122 return !(data().DeclaredSpecialMembers & SMF_MoveAssignment) &&
1123 !hasUserDeclaredCopyConstructor() &&
1124 !hasUserDeclaredCopyAssignment() &&
1125 !hasUserDeclaredMoveConstructor() &&
1126 !hasUserDeclaredDestructor() &&
1127 (!isLambda() || lambdaIsDefaultConstructibleAndAssignable());
1128 }
1129
1130 /// Determine whether we need to eagerly declare a move assignment
1131 /// operator for this class.
1132 bool needsOverloadResolutionForMoveAssignment() const {
1133 return data().NeedOverloadResolutionForMoveAssignment;
1134 }
1135
1136 /// Determine whether this class has a user-declared destructor.
1137 ///
1138 /// When false, a destructor will be implicitly declared.
1139 bool hasUserDeclaredDestructor() const {
1140 return data().UserDeclaredSpecialMembers & SMF_Destructor;
1141 }
1142
1143 /// Determine whether this class needs an implicit destructor to
1144 /// be lazily declared.
1145 bool needsImplicitDestructor() const {
1146 return !(data().DeclaredSpecialMembers & SMF_Destructor);
1147 }
1148
1149 /// Determine whether we need to eagerly declare a destructor for this
1150 /// class.
1151 bool needsOverloadResolutionForDestructor() const {
1152 return data().NeedOverloadResolutionForDestructor;
1153 }
1154
1155 /// Determine whether this class describes a lambda function object.
1156 bool isLambda() const {
1157 // An update record can't turn a non-lambda into a lambda.
1158 auto *DD = DefinitionData;
1159 return DD && DD->IsLambda;
1160 }
1161
1162 /// Determine whether this class describes a generic
1163 /// lambda function object (i.e. function call operator is
1164 /// a template).
1165 bool isGenericLambda() const;
1166
1167 /// Determine whether this lambda should have an implicit default constructor
1168 /// and copy and move assignment operators.
1169 bool lambdaIsDefaultConstructibleAndAssignable() const;
1170
1171 /// Retrieve the lambda call operator of the closure type
1172 /// if this is a closure type.
1173 CXXMethodDecl *getLambdaCallOperator() const;
1174
1175 /// Retrieve the dependent lambda call operator of the closure type
1176 /// if this is a templated closure type.
1177 FunctionTemplateDecl *getDependentLambdaCallOperator() const;
1178
1179 /// Retrieve the lambda static invoker, the address of which
1180 /// is returned by the conversion operator, and the body of which
1181 /// is forwarded to the lambda call operator.
1182 CXXMethodDecl *getLambdaStaticInvoker() const;
1183
1184 /// Retrieve the generic lambda's template parameter list.
1185 /// Returns null if the class does not represent a lambda or a generic
1186 /// lambda.
1187 TemplateParameterList *getGenericLambdaTemplateParameterList() const;
1188
1189 /// Retrieve the lambda template parameters that were specified explicitly.
1190 ArrayRef<NamedDecl *> getLambdaExplicitTemplateParameters() const;
1191
1192 LambdaCaptureDefault getLambdaCaptureDefault() const {
1193 assert(isLambda())((isLambda()) ? static_cast<void> (0) : __assert_fail (
"isLambda()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1193, __PRETTY_FUNCTION__))
;
1194 return static_cast<LambdaCaptureDefault>(getLambdaData().CaptureDefault);
1195 }
1196
1197 /// For a closure type, retrieve the mapping from captured
1198 /// variables and \c this to the non-static data members that store the
1199 /// values or references of the captures.
1200 ///
1201 /// \param Captures Will be populated with the mapping from captured
1202 /// variables to the corresponding fields.
1203 ///
1204 /// \param ThisCapture Will be set to the field declaration for the
1205 /// \c this capture.
1206 ///
1207 /// \note No entries will be added for init-captures, as they do not capture
1208 /// variables.
1209 void getCaptureFields(llvm::DenseMap<const VarDecl *, FieldDecl *> &Captures,
1210 FieldDecl *&ThisCapture) const;
1211
1212 using capture_const_iterator = const LambdaCapture *;
1213 using capture_const_range = llvm::iterator_range<capture_const_iterator>;
1214
1215 capture_const_range captures() const {
1216 return capture_const_range(captures_begin(), captures_end());
1217 }
1218
1219 capture_const_iterator captures_begin() const {
1220 return isLambda() ? getLambdaData().Captures : nullptr;
1221 }
1222
1223 capture_const_iterator captures_end() const {
1224 return isLambda() ? captures_begin() + getLambdaData().NumCaptures
1225 : nullptr;
1226 }
1227
1228 using conversion_iterator = UnresolvedSetIterator;
1229
1230 conversion_iterator conversion_begin() const {
1231 return data().Conversions.get(getASTContext()).begin();
1232 }
1233
1234 conversion_iterator conversion_end() const {
1235 return data().Conversions.get(getASTContext()).end();
1236 }
1237
1238 /// Removes a conversion function from this class. The conversion
1239 /// function must currently be a member of this class. Furthermore,
1240 /// this class must currently be in the process of being defined.
1241 void removeConversion(const NamedDecl *Old);
1242
1243 /// Get all conversion functions visible in current class,
1244 /// including conversion function templates.
1245 llvm::iterator_range<conversion_iterator> getVisibleConversionFunctions();
1246
1247 /// Determine whether this class is an aggregate (C++ [dcl.init.aggr]),
1248 /// which is a class with no user-declared constructors, no private
1249 /// or protected non-static data members, no base classes, and no virtual
1250 /// functions (C++ [dcl.init.aggr]p1).
1251 bool isAggregate() const { return data().Aggregate; }
1252
1253 /// Whether this class has any in-class initializers
1254 /// for non-static data members (including those in anonymous unions or
1255 /// structs).
1256 bool hasInClassInitializer() const { return data().HasInClassInitializer; }
1257
1258 /// Whether this class or any of its subobjects has any members of
1259 /// reference type which would make value-initialization ill-formed.
1260 ///
1261 /// Per C++03 [dcl.init]p5:
1262 /// - if T is a non-union class type without a user-declared constructor,
1263 /// then every non-static data member and base-class component of T is
1264 /// value-initialized [...] A program that calls for [...]
1265 /// value-initialization of an entity of reference type is ill-formed.
1266 bool hasUninitializedReferenceMember() const {
1267 return !isUnion() && !hasUserDeclaredConstructor() &&
1268 data().HasUninitializedReferenceMember;
1269 }
1270
1271 /// Whether this class is a POD-type (C++ [class]p4)
1272 ///
1273 /// For purposes of this function a class is POD if it is an aggregate
1274 /// that has no non-static non-POD data members, no reference data
1275 /// members, no user-defined copy assignment operator and no
1276 /// user-defined destructor.
1277 ///
1278 /// Note that this is the C++ TR1 definition of POD.
1279 bool isPOD() const { return data().PlainOldData; }
1280
1281 /// True if this class is C-like, without C++-specific features, e.g.
1282 /// it contains only public fields, no bases, tag kind is not 'class', etc.
1283 bool isCLike() const;
1284
1285 /// Determine whether this is an empty class in the sense of
1286 /// (C++11 [meta.unary.prop]).
1287 ///
1288 /// The CXXRecordDecl is a class type, but not a union type,
1289 /// with no non-static data members other than bit-fields of length 0,
1290 /// no virtual member functions, no virtual base classes,
1291 /// and no base class B for which is_empty<B>::value is false.
1292 ///
1293 /// \note This does NOT include a check for union-ness.
1294 bool isEmpty() const { return data().Empty; }
1295
1296 bool hasPrivateFields() const {
1297 return data().HasPrivateFields;
1298 }
1299
1300 bool hasProtectedFields() const {
1301 return data().HasProtectedFields;
1302 }
1303
1304 /// Determine whether this class has direct non-static data members.
1305 bool hasDirectFields() const {
1306 auto &D = data();
1307 return D.HasPublicFields || D.HasProtectedFields || D.HasPrivateFields;
1308 }
1309
1310 /// Whether this class is polymorphic (C++ [class.virtual]),
1311 /// which means that the class contains or inherits a virtual function.
1312 bool isPolymorphic() const { return data().Polymorphic; }
1313
1314 /// Determine whether this class has a pure virtual function.
1315 ///
1316 /// The class is is abstract per (C++ [class.abstract]p2) if it declares
1317 /// a pure virtual function or inherits a pure virtual function that is
1318 /// not overridden.
1319 bool isAbstract() const { return data().Abstract; }
1320
1321 /// Determine whether this class is standard-layout per
1322 /// C++ [class]p7.
1323 bool isStandardLayout() const { return data().IsStandardLayout; }
1324
1325 /// Determine whether this class was standard-layout per
1326 /// C++11 [class]p7, specifically using the C++11 rules without any DRs.
1327 bool isCXX11StandardLayout() const { return data().IsCXX11StandardLayout; }
1328
1329 /// Determine whether this class, or any of its class subobjects,
1330 /// contains a mutable field.
1331 bool hasMutableFields() const { return data().HasMutableFields; }
1332
1333 /// Determine whether this class has any variant members.
1334 bool hasVariantMembers() const { return data().HasVariantMembers; }
1335
1336 /// Determine whether this class has a trivial default constructor
1337 /// (C++11 [class.ctor]p5).
1338 bool hasTrivialDefaultConstructor() const {
1339 return hasDefaultConstructor() &&
1340 (data().HasTrivialSpecialMembers & SMF_DefaultConstructor);
1341 }
1342
1343 /// Determine whether this class has a non-trivial default constructor
1344 /// (C++11 [class.ctor]p5).
1345 bool hasNonTrivialDefaultConstructor() const {
1346 return (data().DeclaredNonTrivialSpecialMembers & SMF_DefaultConstructor) ||
1347 (needsImplicitDefaultConstructor() &&
1348 !(data().HasTrivialSpecialMembers & SMF_DefaultConstructor));
1349 }
1350
1351 /// Determine whether this class has at least one constexpr constructor
1352 /// other than the copy or move constructors.
1353 bool hasConstexprNonCopyMoveConstructor() const {
1354 return data().HasConstexprNonCopyMoveConstructor ||
1355 (needsImplicitDefaultConstructor() &&
1356 defaultedDefaultConstructorIsConstexpr());
1357 }
1358
1359 /// Determine whether a defaulted default constructor for this class
1360 /// would be constexpr.
1361 bool defaultedDefaultConstructorIsConstexpr() const {
1362 return data().DefaultedDefaultConstructorIsConstexpr &&
1363 (!isUnion() || hasInClassInitializer() || !hasVariantMembers() ||
1364 getASTContext().getLangOpts().CPlusPlus2a);
1365 }
1366
1367 /// Determine whether this class has a constexpr default constructor.
1368 bool hasConstexprDefaultConstructor() const {
1369 return data().HasConstexprDefaultConstructor ||
1370 (needsImplicitDefaultConstructor() &&
1371 defaultedDefaultConstructorIsConstexpr());
1372 }
1373
1374 /// Determine whether this class has a trivial copy constructor
1375 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1376 bool hasTrivialCopyConstructor() const {
1377 return data().HasTrivialSpecialMembers & SMF_CopyConstructor;
1378 }
1379
1380 bool hasTrivialCopyConstructorForCall() const {
1381 return data().HasTrivialSpecialMembersForCall & SMF_CopyConstructor;
1382 }
1383
1384 /// Determine whether this class has a non-trivial copy constructor
1385 /// (C++ [class.copy]p6, C++11 [class.copy]p12)
1386 bool hasNonTrivialCopyConstructor() const {
1387 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyConstructor ||
1388 !hasTrivialCopyConstructor();
1389 }
1390
1391 bool hasNonTrivialCopyConstructorForCall() const {
1392 return (data().DeclaredNonTrivialSpecialMembersForCall &
1393 SMF_CopyConstructor) ||
1394 !hasTrivialCopyConstructorForCall();
1395 }
1396
1397 /// Determine whether this class has a trivial move constructor
1398 /// (C++11 [class.copy]p12)
1399 bool hasTrivialMoveConstructor() const {
1400 return hasMoveConstructor() &&
1401 (data().HasTrivialSpecialMembers & SMF_MoveConstructor);
1402 }
1403
1404 bool hasTrivialMoveConstructorForCall() const {
1405 return hasMoveConstructor() &&
1406 (data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor);
1407 }
1408
1409 /// Determine whether this class has a non-trivial move constructor
1410 /// (C++11 [class.copy]p12)
1411 bool hasNonTrivialMoveConstructor() const {
1412 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveConstructor) ||
1413 (needsImplicitMoveConstructor() &&
1414 !(data().HasTrivialSpecialMembers & SMF_MoveConstructor));
1415 }
1416
1417 bool hasNonTrivialMoveConstructorForCall() const {
1418 return (data().DeclaredNonTrivialSpecialMembersForCall &
1419 SMF_MoveConstructor) ||
1420 (needsImplicitMoveConstructor() &&
1421 !(data().HasTrivialSpecialMembersForCall & SMF_MoveConstructor));
1422 }
1423
1424 /// Determine whether this class has a trivial copy assignment operator
1425 /// (C++ [class.copy]p11, C++11 [class.copy]p25)
1426 bool hasTrivialCopyAssignment() const {
1427 return data().HasTrivialSpecialMembers & SMF_CopyAssignment;
1428 }
1429
1430 /// Determine whether this class has a non-trivial copy assignment
1431 /// operator (C++ [class.copy]p11, C++11 [class.copy]p25)
1432 bool hasNonTrivialCopyAssignment() const {
1433 return data().DeclaredNonTrivialSpecialMembers & SMF_CopyAssignment ||
1434 !hasTrivialCopyAssignment();
1435 }
1436
1437 /// Determine whether this class has a trivial move assignment operator
1438 /// (C++11 [class.copy]p25)
1439 bool hasTrivialMoveAssignment() const {
1440 return hasMoveAssignment() &&
1441 (data().HasTrivialSpecialMembers & SMF_MoveAssignment);
1442 }
1443
1444 /// Determine whether this class has a non-trivial move assignment
1445 /// operator (C++11 [class.copy]p25)
1446 bool hasNonTrivialMoveAssignment() const {
1447 return (data().DeclaredNonTrivialSpecialMembers & SMF_MoveAssignment) ||
1448 (needsImplicitMoveAssignment() &&
1449 !(data().HasTrivialSpecialMembers & SMF_MoveAssignment));
1450 }
1451
1452 /// Determine whether a defaulted default constructor for this class
1453 /// would be constexpr.
1454 bool defaultedDestructorIsConstexpr() const {
1455 return data().DefaultedDestructorIsConstexpr &&
1456 getASTContext().getLangOpts().CPlusPlus2a;
1457 }
1458
1459 /// Determine whether this class has a constexpr destructor.
1460 bool hasConstexprDestructor() const;
1461
1462 /// Determine whether this class has a trivial destructor
1463 /// (C++ [class.dtor]p3)
1464 bool hasTrivialDestructor() const {
1465 return data().HasTrivialSpecialMembers & SMF_Destructor;
1466 }
1467
1468 bool hasTrivialDestructorForCall() const {
1469 return data().HasTrivialSpecialMembersForCall & SMF_Destructor;
1470 }
1471
1472 /// Determine whether this class has a non-trivial destructor
1473 /// (C++ [class.dtor]p3)
1474 bool hasNonTrivialDestructor() const {
1475 return !(data().HasTrivialSpecialMembers & SMF_Destructor);
1476 }
1477
1478 bool hasNonTrivialDestructorForCall() const {
1479 return !(data().HasTrivialSpecialMembersForCall & SMF_Destructor);
1480 }
1481
1482 void setHasTrivialSpecialMemberForCall() {
1483 data().HasTrivialSpecialMembersForCall =
1484 (SMF_CopyConstructor | SMF_MoveConstructor | SMF_Destructor);
1485 }
1486
1487 /// Determine whether declaring a const variable with this type is ok
1488 /// per core issue 253.
1489 bool allowConstDefaultInit() const {
1490 return !data().HasUninitializedFields ||
1491 !(data().HasDefaultedDefaultConstructor ||
1492 needsImplicitDefaultConstructor());
1493 }
1494
1495 /// Determine whether this class has a destructor which has no
1496 /// semantic effect.
1497 ///
1498 /// Any such destructor will be trivial, public, defaulted and not deleted,
1499 /// and will call only irrelevant destructors.
1500 bool hasIrrelevantDestructor() const {
1501 return data().HasIrrelevantDestructor;
1502 }
1503
1504 /// Determine whether this class has a non-literal or/ volatile type
1505 /// non-static data member or base class.
1506 bool hasNonLiteralTypeFieldsOrBases() const {
1507 return data().HasNonLiteralTypeFieldsOrBases;
1508 }
1509
1510 /// Determine whether this class has a using-declaration that names
1511 /// a user-declared base class constructor.
1512 bool hasInheritedConstructor() const {
1513 return data().HasInheritedConstructor;
1514 }
1515
1516 /// Determine whether this class has a using-declaration that names
1517 /// a base class assignment operator.
1518 bool hasInheritedAssignment() const {
1519 return data().HasInheritedAssignment;
1520 }
1521
1522 /// Determine whether this class is considered trivially copyable per
1523 /// (C++11 [class]p6).
1524 bool isTriviallyCopyable() const;
1525
1526 /// Determine whether this class is considered trivial.
1527 ///
1528 /// C++11 [class]p6:
1529 /// "A trivial class is a class that has a trivial default constructor and
1530 /// is trivially copyable."
1531 bool isTrivial() const {
1532 return isTriviallyCopyable() && hasTrivialDefaultConstructor();
1533 }
1534
1535 /// Determine whether this class is a literal type.
1536 ///
1537 /// C++11 [basic.types]p10:
1538 /// A class type that has all the following properties:
1539 /// - it has a trivial destructor
1540 /// - every constructor call and full-expression in the
1541 /// brace-or-equal-intializers for non-static data members (if any) is
1542 /// a constant expression.
1543 /// - it is an aggregate type or has at least one constexpr constructor
1544 /// or constructor template that is not a copy or move constructor, and
1545 /// - all of its non-static data members and base classes are of literal
1546 /// types
1547 ///
1548 /// We resolve DR1361 by ignoring the second bullet. We resolve DR1452 by
1549 /// treating types with trivial default constructors as literal types.
1550 ///
1551 /// Only in C++17 and beyond, are lambdas literal types.
1552 bool isLiteral() const {
1553 ASTContext &Ctx = getASTContext();
1554 return (Ctx.getLangOpts().CPlusPlus2a ? hasConstexprDestructor()
1555 : hasTrivialDestructor()) &&
1556 (!isLambda() || Ctx.getLangOpts().CPlusPlus17) &&
1557 !hasNonLiteralTypeFieldsOrBases() &&
1558 (isAggregate() || isLambda() ||
1559 hasConstexprNonCopyMoveConstructor() ||
1560 hasTrivialDefaultConstructor());
1561 }
1562
1563 /// If this record is an instantiation of a member class,
1564 /// retrieves the member class from which it was instantiated.
1565 ///
1566 /// This routine will return non-null for (non-templated) member
1567 /// classes of class templates. For example, given:
1568 ///
1569 /// \code
1570 /// template<typename T>
1571 /// struct X {
1572 /// struct A { };
1573 /// };
1574 /// \endcode
1575 ///
1576 /// The declaration for X<int>::A is a (non-templated) CXXRecordDecl
1577 /// whose parent is the class template specialization X<int>. For
1578 /// this declaration, getInstantiatedFromMemberClass() will return
1579 /// the CXXRecordDecl X<T>::A. When a complete definition of
1580 /// X<int>::A is required, it will be instantiated from the
1581 /// declaration returned by getInstantiatedFromMemberClass().
1582 CXXRecordDecl *getInstantiatedFromMemberClass() const;
1583
1584 /// If this class is an instantiation of a member class of a
1585 /// class template specialization, retrieves the member specialization
1586 /// information.
1587 MemberSpecializationInfo *getMemberSpecializationInfo() const;
1588
1589 /// Specify that this record is an instantiation of the
1590 /// member class \p RD.
1591 void setInstantiationOfMemberClass(CXXRecordDecl *RD,
1592 TemplateSpecializationKind TSK);
1593
1594 /// Retrieves the class template that is described by this
1595 /// class declaration.
1596 ///
1597 /// Every class template is represented as a ClassTemplateDecl and a
1598 /// CXXRecordDecl. The former contains template properties (such as
1599 /// the template parameter lists) while the latter contains the
1600 /// actual description of the template's
1601 /// contents. ClassTemplateDecl::getTemplatedDecl() retrieves the
1602 /// CXXRecordDecl that from a ClassTemplateDecl, while
1603 /// getDescribedClassTemplate() retrieves the ClassTemplateDecl from
1604 /// a CXXRecordDecl.
1605 ClassTemplateDecl *getDescribedClassTemplate() const;
1606
1607 void setDescribedClassTemplate(ClassTemplateDecl *Template);
1608
1609 /// Determine whether this particular class is a specialization or
1610 /// instantiation of a class template or member class of a class template,
1611 /// and how it was instantiated or specialized.
1612 TemplateSpecializationKind getTemplateSpecializationKind() const;
1613
1614 /// Set the kind of specialization or template instantiation this is.
1615 void setTemplateSpecializationKind(TemplateSpecializationKind TSK);
1616
1617 /// Retrieve the record declaration from which this record could be
1618 /// instantiated. Returns null if this class is not a template instantiation.
1619 const CXXRecordDecl *getTemplateInstantiationPattern() const;
1620
1621 CXXRecordDecl *getTemplateInstantiationPattern() {
1622 return const_cast<CXXRecordDecl *>(const_cast<const CXXRecordDecl *>(this)
1623 ->getTemplateInstantiationPattern());
1624 }
1625
1626 /// Returns the destructor decl for this class.
1627 CXXDestructorDecl *getDestructor() const;
1628
1629 /// Returns true if the class destructor, or any implicitly invoked
1630 /// destructors are marked noreturn.
1631 bool isAnyDestructorNoReturn() const;
1632
1633 /// If the class is a local class [class.local], returns
1634 /// the enclosing function declaration.
1635 const FunctionDecl *isLocalClass() const {
1636 if (const auto *RD = dyn_cast<CXXRecordDecl>(getDeclContext()))
1637 return RD->isLocalClass();
1638
1639 return dyn_cast<FunctionDecl>(getDeclContext());
1640 }
1641
1642 FunctionDecl *isLocalClass() {
1643 return const_cast<FunctionDecl*>(
1644 const_cast<const CXXRecordDecl*>(this)->isLocalClass());
1645 }
1646
1647 /// Determine whether this dependent class is a current instantiation,
1648 /// when viewed from within the given context.
1649 bool isCurrentInstantiation(const DeclContext *CurContext) const;
1650
1651 /// Determine whether this class is derived from the class \p Base.
1652 ///
1653 /// This routine only determines whether this class is derived from \p Base,
1654 /// but does not account for factors that may make a Derived -> Base class
1655 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1656 /// base class subobjects.
1657 ///
1658 /// \param Base the base class we are searching for.
1659 ///
1660 /// \returns true if this class is derived from Base, false otherwise.
1661 bool isDerivedFrom(const CXXRecordDecl *Base) const;
1662
1663 /// Determine whether this class is derived from the type \p Base.
1664 ///
1665 /// This routine only determines whether this class is derived from \p Base,
1666 /// but does not account for factors that may make a Derived -> Base class
1667 /// ill-formed, such as private/protected inheritance or multiple, ambiguous
1668 /// base class subobjects.
1669 ///
1670 /// \param Base the base class we are searching for.
1671 ///
1672 /// \param Paths will contain the paths taken from the current class to the
1673 /// given \p Base class.
1674 ///
1675 /// \returns true if this class is derived from \p Base, false otherwise.
1676 ///
1677 /// \todo add a separate parameter to configure IsDerivedFrom, rather than
1678 /// tangling input and output in \p Paths
1679 bool isDerivedFrom(const CXXRecordDecl *Base, CXXBasePaths &Paths) const;
1680
1681 /// Determine whether this class is virtually derived from
1682 /// the class \p Base.
1683 ///
1684 /// This routine only determines whether this class is virtually
1685 /// derived from \p Base, but does not account for factors that may
1686 /// make a Derived -> Base class ill-formed, such as
1687 /// private/protected inheritance or multiple, ambiguous base class
1688 /// subobjects.
1689 ///
1690 /// \param Base the base class we are searching for.
1691 ///
1692 /// \returns true if this class is virtually derived from Base,
1693 /// false otherwise.
1694 bool isVirtuallyDerivedFrom(const CXXRecordDecl *Base) const;
1695
1696 /// Determine whether this class is provably not derived from
1697 /// the type \p Base.
1698 bool isProvablyNotDerivedFrom(const CXXRecordDecl *Base) const;
1699
1700 /// Function type used by forallBases() as a callback.
1701 ///
1702 /// \param BaseDefinition the definition of the base class
1703 ///
1704 /// \returns true if this base matched the search criteria
1705 using ForallBasesCallback =
1706 llvm::function_ref<bool(const CXXRecordDecl *BaseDefinition)>;
1707
1708 /// Determines if the given callback holds for all the direct
1709 /// or indirect base classes of this type.
1710 ///
1711 /// The class itself does not count as a base class. This routine
1712 /// returns false if the class has non-computable base classes.
1713 ///
1714 /// \param BaseMatches Callback invoked for each (direct or indirect) base
1715 /// class of this type, or if \p AllowShortCircuit is true then until a call
1716 /// returns false.
1717 ///
1718 /// \param AllowShortCircuit if false, forces the callback to be called
1719 /// for every base class, even if a dependent or non-matching base was
1720 /// found.
1721 bool forallBases(ForallBasesCallback BaseMatches,
1722 bool AllowShortCircuit = true) const;
1723
1724 /// Function type used by lookupInBases() to determine whether a
1725 /// specific base class subobject matches the lookup criteria.
1726 ///
1727 /// \param Specifier the base-class specifier that describes the inheritance
1728 /// from the base class we are trying to match.
1729 ///
1730 /// \param Path the current path, from the most-derived class down to the
1731 /// base named by the \p Specifier.
1732 ///
1733 /// \returns true if this base matched the search criteria, false otherwise.
1734 using BaseMatchesCallback =
1735 llvm::function_ref<bool(const CXXBaseSpecifier *Specifier,
1736 CXXBasePath &Path)>;
1737
1738 /// Look for entities within the base classes of this C++ class,
1739 /// transitively searching all base class subobjects.
1740 ///
1741 /// This routine uses the callback function \p BaseMatches to find base
1742 /// classes meeting some search criteria, walking all base class subobjects
1743 /// and populating the given \p Paths structure with the paths through the
1744 /// inheritance hierarchy that resulted in a match. On a successful search,
1745 /// the \p Paths structure can be queried to retrieve the matching paths and
1746 /// to determine if there were any ambiguities.
1747 ///
1748 /// \param BaseMatches callback function used to determine whether a given
1749 /// base matches the user-defined search criteria.
1750 ///
1751 /// \param Paths used to record the paths from this class to its base class
1752 /// subobjects that match the search criteria.
1753 ///
1754 /// \param LookupInDependent can be set to true to extend the search to
1755 /// dependent base classes.
1756 ///
1757 /// \returns true if there exists any path from this class to a base class
1758 /// subobject that matches the search criteria.
1759 bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths,
1760 bool LookupInDependent = false) const;
1761
1762 /// Base-class lookup callback that determines whether the given
1763 /// base class specifier refers to a specific class declaration.
1764 ///
1765 /// This callback can be used with \c lookupInBases() to determine whether
1766 /// a given derived class has is a base class subobject of a particular type.
1767 /// The base record pointer should refer to the canonical CXXRecordDecl of the
1768 /// base class that we are searching for.
1769 static bool FindBaseClass(const CXXBaseSpecifier *Specifier,
1770 CXXBasePath &Path, const CXXRecordDecl *BaseRecord);
1771
1772 /// Base-class lookup callback that determines whether the
1773 /// given base class specifier refers to a specific class
1774 /// declaration and describes virtual derivation.
1775 ///
1776 /// This callback can be used with \c lookupInBases() to determine
1777 /// whether a given derived class has is a virtual base class
1778 /// subobject of a particular type. The base record pointer should
1779 /// refer to the canonical CXXRecordDecl of the base class that we
1780 /// are searching for.
1781 static bool FindVirtualBaseClass(const CXXBaseSpecifier *Specifier,
1782 CXXBasePath &Path,
1783 const CXXRecordDecl *BaseRecord);
1784
1785 /// Base-class lookup callback that determines whether there exists
1786 /// a tag with the given name.
1787 ///
1788 /// This callback can be used with \c lookupInBases() to find tag members
1789 /// of the given name within a C++ class hierarchy.
1790 static bool FindTagMember(const CXXBaseSpecifier *Specifier,
1791 CXXBasePath &Path, DeclarationName Name);
1792
1793 /// Base-class lookup callback that determines whether there exists
1794 /// a member with the given name.
1795 ///
1796 /// This callback can be used with \c lookupInBases() to find members
1797 /// of the given name within a C++ class hierarchy.
1798 static bool FindOrdinaryMember(const CXXBaseSpecifier *Specifier,
1799 CXXBasePath &Path, DeclarationName Name);
1800
1801 /// Base-class lookup callback that determines whether there exists
1802 /// a member with the given name.
1803 ///
1804 /// This callback can be used with \c lookupInBases() to find members
1805 /// of the given name within a C++ class hierarchy, including dependent
1806 /// classes.
1807 static bool
1808 FindOrdinaryMemberInDependentClasses(const CXXBaseSpecifier *Specifier,
1809 CXXBasePath &Path, DeclarationName Name);
1810
1811 /// Base-class lookup callback that determines whether there exists
1812 /// an OpenMP declare reduction member with the given name.
1813 ///
1814 /// This callback can be used with \c lookupInBases() to find members
1815 /// of the given name within a C++ class hierarchy.
1816 static bool FindOMPReductionMember(const CXXBaseSpecifier *Specifier,
1817 CXXBasePath &Path, DeclarationName Name);
1818
1819 /// Base-class lookup callback that determines whether there exists
1820 /// an OpenMP declare mapper member with the given name.
1821 ///
1822 /// This callback can be used with \c lookupInBases() to find members
1823 /// of the given name within a C++ class hierarchy.
1824 static bool FindOMPMapperMember(const CXXBaseSpecifier *Specifier,
1825 CXXBasePath &Path, DeclarationName Name);
1826
1827 /// Base-class lookup callback that determines whether there exists
1828 /// a member with the given name that can be used in a nested-name-specifier.
1829 ///
1830 /// This callback can be used with \c lookupInBases() to find members of
1831 /// the given name within a C++ class hierarchy that can occur within
1832 /// nested-name-specifiers.
1833 static bool FindNestedNameSpecifierMember(const CXXBaseSpecifier *Specifier,
1834 CXXBasePath &Path,
1835 DeclarationName Name);
1836
1837 /// Retrieve the final overriders for each virtual member
1838 /// function in the class hierarchy where this class is the
1839 /// most-derived class in the class hierarchy.
1840 void getFinalOverriders(CXXFinalOverriderMap &FinaOverriders) const;
1841
1842 /// Get the indirect primary bases for this class.
1843 void getIndirectPrimaryBases(CXXIndirectPrimaryBaseSet& Bases) const;
1844
1845 /// Performs an imprecise lookup of a dependent name in this class.
1846 ///
1847 /// This function does not follow strict semantic rules and should be used
1848 /// only when lookup rules can be relaxed, e.g. indexing.
1849 std::vector<const NamedDecl *>
1850 lookupDependentName(const DeclarationName &Name,
1851 llvm::function_ref<bool(const NamedDecl *ND)> Filter);
1852
1853 /// Renders and displays an inheritance diagram
1854 /// for this C++ class and all of its base classes (transitively) using
1855 /// GraphViz.
1856 void viewInheritance(ASTContext& Context) const;
1857
1858 /// Calculates the access of a decl that is reached
1859 /// along a path.
1860 static AccessSpecifier MergeAccess(AccessSpecifier PathAccess,
1861 AccessSpecifier DeclAccess) {
1862 assert(DeclAccess != AS_none)((DeclAccess != AS_none) ? static_cast<void> (0) : __assert_fail
("DeclAccess != AS_none", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1862, __PRETTY_FUNCTION__))
;
1863 if (DeclAccess == AS_private) return AS_none;
1864 return (PathAccess > DeclAccess ? PathAccess : DeclAccess);
1865 }
1866
1867 /// Indicates that the declaration of a defaulted or deleted special
1868 /// member function is now complete.
1869 void finishedDefaultedOrDeletedMember(CXXMethodDecl *MD);
1870
1871 void setTrivialForCallFlags(CXXMethodDecl *MD);
1872
1873 /// Indicates that the definition of this class is now complete.
1874 void completeDefinition() override;
1875
1876 /// Indicates that the definition of this class is now complete,
1877 /// and provides a final overrider map to help determine
1878 ///
1879 /// \param FinalOverriders The final overrider map for this class, which can
1880 /// be provided as an optimization for abstract-class checking. If NULL,
1881 /// final overriders will be computed if they are needed to complete the
1882 /// definition.
1883 void completeDefinition(CXXFinalOverriderMap *FinalOverriders);
1884
1885 /// Determine whether this class may end up being abstract, even though
1886 /// it is not yet known to be abstract.
1887 ///
1888 /// \returns true if this class is not known to be abstract but has any
1889 /// base classes that are abstract. In this case, \c completeDefinition()
1890 /// will need to compute final overriders to determine whether the class is
1891 /// actually abstract.
1892 bool mayBeAbstract() const;
1893
1894 /// If this is the closure type of a lambda expression, retrieve the
1895 /// number to be used for name mangling in the Itanium C++ ABI.
1896 ///
1897 /// Zero indicates that this closure type has internal linkage, so the
1898 /// mangling number does not matter, while a non-zero value indicates which
1899 /// lambda expression this is in this particular context.
1900 unsigned getLambdaManglingNumber() const {
1901 assert(isLambda() && "Not a lambda closure type!")((isLambda() && "Not a lambda closure type!") ? static_cast
<void> (0) : __assert_fail ("isLambda() && \"Not a lambda closure type!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 1901, __PRETTY_FUNCTION__))
;
1902 return getLambdaData().ManglingNumber;
1903 }
1904
1905 /// Retrieve the declaration that provides additional context for a
1906 /// lambda, when the normal declaration context is not specific enough.
1907 ///
1908 /// Certain contexts (default arguments of in-class function parameters and
1909 /// the initializers of data members) have separate name mangling rules for
1910 /// lambdas within the Itanium C++ ABI. For these cases, this routine provides
1911 /// the declaration in which the lambda occurs, e.g., the function parameter
1912 /// or the non-static data member. Otherwise, it returns NULL to imply that
1913 /// the declaration context suffices.
1914 Decl *getLambdaContextDecl() const;
1915
1916 /// Set the mangling number and context declaration for a lambda
1917 /// class.
1918 void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl) {
1919 getLambdaData().ManglingNumber = ManglingNumber;
1920 getLambdaData().ContextDecl = ContextDecl;
1921 }
1922
1923 /// Returns the inheritance model used for this record.
1924 MSInheritanceAttr::Spelling getMSInheritanceModel() const;
1925
1926 /// Calculate what the inheritance model would be for this class.
1927 MSInheritanceAttr::Spelling calculateInheritanceModel() const;
1928
1929 /// In the Microsoft C++ ABI, use zero for the field offset of a null data
1930 /// member pointer if we can guarantee that zero is not a valid field offset,
1931 /// or if the member pointer has multiple fields. Polymorphic classes have a
1932 /// vfptr at offset zero, so we can use zero for null. If there are multiple
1933 /// fields, we can use zero even if it is a valid field offset because
1934 /// null-ness testing will check the other fields.
1935 bool nullFieldOffsetIsZero() const {
1936 return !MSInheritanceAttr::hasOnlyOneField(/*IsMemberFunction=*/false,
1937 getMSInheritanceModel()) ||
1938 (hasDefinition() && isPolymorphic());
1939 }
1940
1941 /// Controls when vtordisps will be emitted if this record is used as a
1942 /// virtual base.
1943 MSVtorDispAttr::Mode getMSVtorDispMode() const;
1944
1945 /// Determine whether this lambda expression was known to be dependent
1946 /// at the time it was created, even if its context does not appear to be
1947 /// dependent.
1948 ///
1949 /// This flag is a workaround for an issue with parsing, where default
1950 /// arguments are parsed before their enclosing function declarations have
1951 /// been created. This means that any lambda expressions within those
1952 /// default arguments will have as their DeclContext the context enclosing
1953 /// the function declaration, which may be non-dependent even when the
1954 /// function declaration itself is dependent. This flag indicates when we
1955 /// know that the lambda is dependent despite that.
1956 bool isDependentLambda() const {
1957 return isLambda() && getLambdaData().Dependent;
1958 }
1959
1960 TypeSourceInfo *getLambdaTypeInfo() const {
1961 return getLambdaData().MethodTyInfo;
1962 }
1963
1964 // Determine whether this type is an Interface Like type for
1965 // __interface inheritance purposes.
1966 bool isInterfaceLike() const;
1967
1968 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1969 static bool classofKind(Kind K) {
1970 return K >= firstCXXRecord && K <= lastCXXRecord;
1971 }
1972};
1973
1974/// Store information needed for an explicit specifier.
1975/// used by CXXDeductionGuideDecl, CXXConstructorDecl and CXXConversionDecl.
1976class ExplicitSpecifier {
1977 llvm::PointerIntPair<Expr *, 2, ExplicitSpecKind> ExplicitSpec{
1978 nullptr, ExplicitSpecKind::ResolvedFalse};
1979
1980public:
1981 ExplicitSpecifier() = default;
1982 ExplicitSpecifier(Expr *Expression, ExplicitSpecKind Kind)
1983 : ExplicitSpec(Expression, Kind) {}
1984 ExplicitSpecKind getKind() const { return ExplicitSpec.getInt(); }
1985 const Expr *getExpr() const { return ExplicitSpec.getPointer(); }
1986 Expr *getExpr() { return ExplicitSpec.getPointer(); }
1987
1988 /// Return true if the ExplicitSpecifier isn't defaulted.
1989 bool isSpecified() const {
1990 return ExplicitSpec.getInt() != ExplicitSpecKind::ResolvedFalse ||
1991 ExplicitSpec.getPointer();
1992 }
1993
1994 /// Check for Equivalence of explicit specifiers.
1995 /// Return True if the explicit specifier are equivalent false otherwise.
1996 bool isEquivalent(const ExplicitSpecifier Other) const;
1997 /// Return true if the explicit specifier is already resolved to be explicit.
1998 bool isExplicit() const {
1999 return ExplicitSpec.getInt() == ExplicitSpecKind::ResolvedTrue;
2000 }
2001 /// Return true if the ExplicitSpecifier isn't valid.
2002 /// This state occurs after a substitution failures.
2003 bool isInvalid() const {
2004 return ExplicitSpec.getInt() == ExplicitSpecKind::Unresolved &&
2005 !ExplicitSpec.getPointer();
2006 }
2007 void setKind(ExplicitSpecKind Kind) { ExplicitSpec.setInt(Kind); }
2008 void setExpr(Expr *E) { ExplicitSpec.setPointer(E); }
2009 // getFromDecl - retrieve the explicit specifier in the given declaration.
2010 // if the given declaration has no explicit. the returned explicit specifier
2011 // is defaulted. .isSpecified() will be false.
2012 static ExplicitSpecifier getFromDecl(FunctionDecl *Function);
2013 static const ExplicitSpecifier getFromDecl(const FunctionDecl *Function) {
2014 return getFromDecl(const_cast<FunctionDecl *>(Function));
2015 }
2016 static ExplicitSpecifier Invalid() {
2017 return ExplicitSpecifier(nullptr, ExplicitSpecKind::Unresolved);
2018 }
2019};
2020
2021/// Represents a C++ deduction guide declaration.
2022///
2023/// \code
2024/// template<typename T> struct A { A(); A(T); };
2025/// A() -> A<int>;
2026/// \endcode
2027///
2028/// In this example, there will be an explicit deduction guide from the
2029/// second line, and implicit deduction guide templates synthesized from
2030/// the constructors of \c A.
2031class CXXDeductionGuideDecl : public FunctionDecl {
2032 void anchor() override;
2033
2034private:
2035 CXXDeductionGuideDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2036 ExplicitSpecifier ES,
2037 const DeclarationNameInfo &NameInfo, QualType T,
2038 TypeSourceInfo *TInfo, SourceLocation EndLocation)
2039 : FunctionDecl(CXXDeductionGuide, C, DC, StartLoc, NameInfo, T, TInfo,
2040 SC_None, false, CSK_unspecified),
2041 ExplicitSpec(ES) {
2042 if (EndLocation.isValid())
2043 setRangeEnd(EndLocation);
2044 setIsCopyDeductionCandidate(false);
2045 }
2046
2047 ExplicitSpecifier ExplicitSpec;
2048 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2049
2050public:
2051 friend class ASTDeclReader;
2052 friend class ASTDeclWriter;
2053
2054 static CXXDeductionGuideDecl *
2055 Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
2056 ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T,
2057 TypeSourceInfo *TInfo, SourceLocation EndLocation);
2058
2059 static CXXDeductionGuideDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2060
2061 ExplicitSpecifier getExplicitSpecifier() { return ExplicitSpec; }
2062 const ExplicitSpecifier getExplicitSpecifier() const { return ExplicitSpec; }
2063
2064 /// Return true if the declartion is already resolved to be explicit.
2065 bool isExplicit() const { return ExplicitSpec.isExplicit(); }
2066
2067 /// Get the template for which this guide performs deduction.
2068 TemplateDecl *getDeducedTemplate() const {
2069 return getDeclName().getCXXDeductionGuideTemplate();
2070 }
2071
2072 void setIsCopyDeductionCandidate(bool isCDC = true) {
2073 FunctionDeclBits.IsCopyDeductionCandidate = isCDC;
2074 }
2075
2076 bool isCopyDeductionCandidate() const {
2077 return FunctionDeclBits.IsCopyDeductionCandidate;
2078 }
2079
2080 // Implement isa/cast/dyncast/etc.
2081 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2082 static bool classofKind(Kind K) { return K == CXXDeductionGuide; }
2083};
2084
2085/// Represents a static or instance method of a struct/union/class.
2086///
2087/// In the terminology of the C++ Standard, these are the (static and
2088/// non-static) member functions, whether virtual or not.
2089class CXXMethodDecl : public FunctionDecl {
2090 void anchor() override;
2091
2092protected:
2093 CXXMethodDecl(Kind DK, ASTContext &C, CXXRecordDecl *RD,
2094 SourceLocation StartLoc, const DeclarationNameInfo &NameInfo,
2095 QualType T, TypeSourceInfo *TInfo, StorageClass SC,
2096 bool isInline, ConstexprSpecKind ConstexprKind,
2097 SourceLocation EndLocation)
2098 : FunctionDecl(DK, C, RD, StartLoc, NameInfo, T, TInfo, SC, isInline,
2099 ConstexprKind) {
2100 if (EndLocation.isValid())
2101 setRangeEnd(EndLocation);
2102 }
2103
2104public:
2105 static CXXMethodDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2106 SourceLocation StartLoc,
2107 const DeclarationNameInfo &NameInfo, QualType T,
2108 TypeSourceInfo *TInfo, StorageClass SC,
2109 bool isInline, ConstexprSpecKind ConstexprKind,
2110 SourceLocation EndLocation);
2111
2112 static CXXMethodDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2113
2114 bool isStatic() const;
2115 bool isInstance() const { return !isStatic(); }
26
Assuming the condition is true
27
Returning the value 1, which participates in a condition later
2116
2117 /// Returns true if the given operator is implicitly static in a record
2118 /// context.
2119 static bool isStaticOverloadedOperator(OverloadedOperatorKind OOK) {
2120 // [class.free]p1:
2121 // Any allocation function for a class T is a static member
2122 // (even if not explicitly declared static).
2123 // [class.free]p6 Any deallocation function for a class X is a static member
2124 // (even if not explicitly declared static).
2125 return OOK == OO_New || OOK == OO_Array_New || OOK == OO_Delete ||
2126 OOK == OO_Array_Delete;
2127 }
2128
2129 bool isConst() const { return getType()->castAs<FunctionType>()->isConst(); }
2130 bool isVolatile() const { return getType()->castAs<FunctionType>()->isVolatile(); }
2131
2132 bool isVirtual() const {
2133 CXXMethodDecl *CD = const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2134
2135 // Member function is virtual if it is marked explicitly so, or if it is
2136 // declared in __interface -- then it is automatically pure virtual.
2137 if (CD->isVirtualAsWritten() || CD->isPure())
2138 return true;
2139
2140 return CD->size_overridden_methods() != 0;
2141 }
2142
2143 /// If it's possible to devirtualize a call to this method, return the called
2144 /// function. Otherwise, return null.
2145
2146 /// \param Base The object on which this virtual function is called.
2147 /// \param IsAppleKext True if we are compiling for Apple kext.
2148 CXXMethodDecl *getDevirtualizedMethod(const Expr *Base, bool IsAppleKext);
2149
2150 const CXXMethodDecl *getDevirtualizedMethod(const Expr *Base,
2151 bool IsAppleKext) const {
2152 return const_cast<CXXMethodDecl *>(this)->getDevirtualizedMethod(
2153 Base, IsAppleKext);
2154 }
2155
2156 /// Determine whether this is a usual deallocation function (C++
2157 /// [basic.stc.dynamic.deallocation]p2), which is an overloaded delete or
2158 /// delete[] operator with a particular signature. Populates \p PreventedBy
2159 /// with the declarations of the functions of the same kind if they were the
2160 /// reason for this function returning false. This is used by
2161 /// Sema::isUsualDeallocationFunction to reconsider the answer based on the
2162 /// context.
2163 bool isUsualDeallocationFunction(
2164 SmallVectorImpl<const FunctionDecl *> &PreventedBy) const;
2165
2166 /// Determine whether this is a copy-assignment operator, regardless
2167 /// of whether it was declared implicitly or explicitly.
2168 bool isCopyAssignmentOperator() const;
2169
2170 /// Determine whether this is a move assignment operator.
2171 bool isMoveAssignmentOperator() const;
2172
2173 CXXMethodDecl *getCanonicalDecl() override {
2174 return cast<CXXMethodDecl>(FunctionDecl::getCanonicalDecl());
2175 }
2176 const CXXMethodDecl *getCanonicalDecl() const {
2177 return const_cast<CXXMethodDecl*>(this)->getCanonicalDecl();
2178 }
2179
2180 CXXMethodDecl *getMostRecentDecl() {
2181 return cast<CXXMethodDecl>(
2182 static_cast<FunctionDecl *>(this)->getMostRecentDecl());
2183 }
2184 const CXXMethodDecl *getMostRecentDecl() const {
2185 return const_cast<CXXMethodDecl*>(this)->getMostRecentDecl();
2186 }
2187
2188 /// True if this method is user-declared and was not
2189 /// deleted or defaulted on its first declaration.
2190 bool isUserProvided() const {
2191 auto *DeclAsWritten = this;
2192 if (auto *Pattern = getTemplateInstantiationPattern())
2193 DeclAsWritten = cast<CXXMethodDecl>(Pattern);
2194 return !(DeclAsWritten->isDeleted() ||
2195 DeclAsWritten->getCanonicalDecl()->isDefaulted());
2196 }
2197
2198 void addOverriddenMethod(const CXXMethodDecl *MD);
2199
2200 using method_iterator = const CXXMethodDecl *const *;
2201
2202 method_iterator begin_overridden_methods() const;
2203 method_iterator end_overridden_methods() const;
2204 unsigned size_overridden_methods() const;
2205
2206 using overridden_method_range= ASTContext::overridden_method_range;
2207
2208 overridden_method_range overridden_methods() const;
2209
2210 /// Return the parent of this method declaration, which
2211 /// is the class in which this method is defined.
2212 const CXXRecordDecl *getParent() const {
2213 return cast<CXXRecordDecl>(FunctionDecl::getParent());
2214 }
2215
2216 /// Return the parent of this method declaration, which
2217 /// is the class in which this method is defined.
2218 CXXRecordDecl *getParent() {
2219 return const_cast<CXXRecordDecl *>(
2220 cast<CXXRecordDecl>(FunctionDecl::getParent()));
2221 }
2222
2223 /// Return the type of the \c this pointer.
2224 ///
2225 /// Should only be called for instance (i.e., non-static) methods. Note
2226 /// that for the call operator of a lambda closure type, this returns the
2227 /// desugared 'this' type (a pointer to the closure type), not the captured
2228 /// 'this' type.
2229 QualType getThisType() const;
2230
2231 /// Return the type of the object pointed by \c this.
2232 ///
2233 /// See getThisType() for usage restriction.
2234 QualType getThisObjectType() const;
2235
2236 static QualType getThisType(const FunctionProtoType *FPT,
2237 const CXXRecordDecl *Decl);
2238
2239 static QualType getThisObjectType(const FunctionProtoType *FPT,
2240 const CXXRecordDecl *Decl);
2241
2242 Qualifiers getMethodQualifiers() const {
2243 return getType()->castAs<FunctionProtoType>()->getMethodQuals();
2244 }
2245
2246 /// Retrieve the ref-qualifier associated with this method.
2247 ///
2248 /// In the following example, \c f() has an lvalue ref-qualifier, \c g()
2249 /// has an rvalue ref-qualifier, and \c h() has no ref-qualifier.
2250 /// @code
2251 /// struct X {
2252 /// void f() &;
2253 /// void g() &&;
2254 /// void h();
2255 /// };
2256 /// @endcode
2257 RefQualifierKind getRefQualifier() const {
2258 return getType()->castAs<FunctionProtoType>()->getRefQualifier();
2259 }
2260
2261 bool hasInlineBody() const;
2262
2263 /// Determine whether this is a lambda closure type's static member
2264 /// function that is used for the result of the lambda's conversion to
2265 /// function pointer (for a lambda with no captures).
2266 ///
2267 /// The function itself, if used, will have a placeholder body that will be
2268 /// supplied by IR generation to either forward to the function call operator
2269 /// or clone the function call operator.
2270 bool isLambdaStaticInvoker() const;
2271
2272 /// Find the method in \p RD that corresponds to this one.
2273 ///
2274 /// Find if \p RD or one of the classes it inherits from override this method.
2275 /// If so, return it. \p RD is assumed to be a subclass of the class defining
2276 /// this method (or be the class itself), unless \p MayBeBase is set to true.
2277 CXXMethodDecl *
2278 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2279 bool MayBeBase = false);
2280
2281 const CXXMethodDecl *
2282 getCorrespondingMethodInClass(const CXXRecordDecl *RD,
2283 bool MayBeBase = false) const {
2284 return const_cast<CXXMethodDecl *>(this)
2285 ->getCorrespondingMethodInClass(RD, MayBeBase);
2286 }
2287
2288 /// Find if \p RD declares a function that overrides this function, and if so,
2289 /// return it. Does not search base classes.
2290 CXXMethodDecl *getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2291 bool MayBeBase = false);
2292 const CXXMethodDecl *
2293 getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD,
2294 bool MayBeBase = false) const {
2295 return const_cast<CXXMethodDecl *>(this)
2296 ->getCorrespondingMethodDeclaredInClass(RD, MayBeBase);
2297 }
2298
2299 // Implement isa/cast/dyncast/etc.
2300 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2301 static bool classofKind(Kind K) {
2302 return K >= firstCXXMethod && K <= lastCXXMethod;
2303 }
2304};
2305
2306/// Represents a C++ base or member initializer.
2307///
2308/// This is part of a constructor initializer that
2309/// initializes one non-static member variable or one base class. For
2310/// example, in the following, both 'A(a)' and 'f(3.14159)' are member
2311/// initializers:
2312///
2313/// \code
2314/// class A { };
2315/// class B : public A {
2316/// float f;
2317/// public:
2318/// B(A& a) : A(a), f(3.14159) { }
2319/// };
2320/// \endcode
2321class CXXCtorInitializer final {
2322 /// Either the base class name/delegating constructor type (stored as
2323 /// a TypeSourceInfo*), an normal field (FieldDecl), or an anonymous field
2324 /// (IndirectFieldDecl*) being initialized.
2325 llvm::PointerUnion3<TypeSourceInfo *, FieldDecl *, IndirectFieldDecl *>
2326 Initializee;
2327
2328 /// The source location for the field name or, for a base initializer
2329 /// pack expansion, the location of the ellipsis.
2330 ///
2331 /// In the case of a delegating
2332 /// constructor, it will still include the type's source location as the
2333 /// Initializee points to the CXXConstructorDecl (to allow loop detection).
2334 SourceLocation MemberOrEllipsisLocation;
2335
2336 /// The argument used to initialize the base or member, which may
2337 /// end up constructing an object (when multiple arguments are involved).
2338 Stmt *Init;
2339
2340 /// Location of the left paren of the ctor-initializer.
2341 SourceLocation LParenLoc;
2342
2343 /// Location of the right paren of the ctor-initializer.
2344 SourceLocation RParenLoc;
2345
2346 /// If the initializee is a type, whether that type makes this
2347 /// a delegating initialization.
2348 unsigned IsDelegating : 1;
2349
2350 /// If the initializer is a base initializer, this keeps track
2351 /// of whether the base is virtual or not.
2352 unsigned IsVirtual : 1;
2353
2354 /// Whether or not the initializer is explicitly written
2355 /// in the sources.
2356 unsigned IsWritten : 1;
2357
2358 /// If IsWritten is true, then this number keeps track of the textual order
2359 /// of this initializer in the original sources, counting from 0.
2360 unsigned SourceOrder : 13;
2361
2362public:
2363 /// Creates a new base-class initializer.
2364 explicit
2365 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo, bool IsVirtual,
2366 SourceLocation L, Expr *Init, SourceLocation R,
2367 SourceLocation EllipsisLoc);
2368
2369 /// Creates a new member initializer.
2370 explicit
2371 CXXCtorInitializer(ASTContext &Context, FieldDecl *Member,
2372 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2373 SourceLocation R);
2374
2375 /// Creates a new anonymous field initializer.
2376 explicit
2377 CXXCtorInitializer(ASTContext &Context, IndirectFieldDecl *Member,
2378 SourceLocation MemberLoc, SourceLocation L, Expr *Init,
2379 SourceLocation R);
2380
2381 /// Creates a new delegating initializer.
2382 explicit
2383 CXXCtorInitializer(ASTContext &Context, TypeSourceInfo *TInfo,
2384 SourceLocation L, Expr *Init, SourceLocation R);
2385
2386 /// \return Unique reproducible object identifier.
2387 int64_t getID(const ASTContext &Context) const;
2388
2389 /// Determine whether this initializer is initializing a base class.
2390 bool isBaseInitializer() const {
2391 return Initializee.is<TypeSourceInfo*>() && !IsDelegating;
2392 }
2393
2394 /// Determine whether this initializer is initializing a non-static
2395 /// data member.
2396 bool isMemberInitializer() const { return Initializee.is<FieldDecl*>(); }
2397
2398 bool isAnyMemberInitializer() const {
2399 return isMemberInitializer() || isIndirectMemberInitializer();
2400 }
2401
2402 bool isIndirectMemberInitializer() const {
2403 return Initializee.is<IndirectFieldDecl*>();
2404 }
2405
2406 /// Determine whether this initializer is an implicit initializer
2407 /// generated for a field with an initializer defined on the member
2408 /// declaration.
2409 ///
2410 /// In-class member initializers (also known as "non-static data member
2411 /// initializations", NSDMIs) were introduced in C++11.
2412 bool isInClassMemberInitializer() const {
2413 return Init->getStmtClass() == Stmt::CXXDefaultInitExprClass;
2414 }
2415
2416 /// Determine whether this initializer is creating a delegating
2417 /// constructor.
2418 bool isDelegatingInitializer() const {
2419 return Initializee.is<TypeSourceInfo*>() && IsDelegating;
2420 }
2421
2422 /// Determine whether this initializer is a pack expansion.
2423 bool isPackExpansion() const {
2424 return isBaseInitializer() && MemberOrEllipsisLocation.isValid();
2425 }
2426
2427 // For a pack expansion, returns the location of the ellipsis.
2428 SourceLocation getEllipsisLoc() const {
2429 assert(isPackExpansion() && "Initializer is not a pack expansion")((isPackExpansion() && "Initializer is not a pack expansion"
) ? static_cast<void> (0) : __assert_fail ("isPackExpansion() && \"Initializer is not a pack expansion\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2429, __PRETTY_FUNCTION__))
;
2430 return MemberOrEllipsisLocation;
2431 }
2432
2433 /// If this is a base class initializer, returns the type of the
2434 /// base class with location information. Otherwise, returns an NULL
2435 /// type location.
2436 TypeLoc getBaseClassLoc() const;
2437
2438 /// If this is a base class initializer, returns the type of the base class.
2439 /// Otherwise, returns null.
2440 const Type *getBaseClass() const;
2441
2442 /// Returns whether the base is virtual or not.
2443 bool isBaseVirtual() const {
2444 assert(isBaseInitializer() && "Must call this on base initializer!")((isBaseInitializer() && "Must call this on base initializer!"
) ? static_cast<void> (0) : __assert_fail ("isBaseInitializer() && \"Must call this on base initializer!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2444, __PRETTY_FUNCTION__))
;
2445
2446 return IsVirtual;
2447 }
2448
2449 /// Returns the declarator information for a base class or delegating
2450 /// initializer.
2451 TypeSourceInfo *getTypeSourceInfo() const {
2452 return Initializee.dyn_cast<TypeSourceInfo *>();
2453 }
2454
2455 /// If this is a member initializer, returns the declaration of the
2456 /// non-static data member being initialized. Otherwise, returns null.
2457 FieldDecl *getMember() const {
2458 if (isMemberInitializer())
2459 return Initializee.get<FieldDecl*>();
2460 return nullptr;
2461 }
2462
2463 FieldDecl *getAnyMember() const {
2464 if (isMemberInitializer())
2465 return Initializee.get<FieldDecl*>();
2466 if (isIndirectMemberInitializer())
2467 return Initializee.get<IndirectFieldDecl*>()->getAnonField();
2468 return nullptr;
2469 }
2470
2471 IndirectFieldDecl *getIndirectMember() const {
2472 if (isIndirectMemberInitializer())
2473 return Initializee.get<IndirectFieldDecl*>();
2474 return nullptr;
2475 }
2476
2477 SourceLocation getMemberLocation() const {
2478 return MemberOrEllipsisLocation;
2479 }
2480
2481 /// Determine the source location of the initializer.
2482 SourceLocation getSourceLocation() const;
2483
2484 /// Determine the source range covering the entire initializer.
2485 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__));
2486
2487 /// Determine whether this initializer is explicitly written
2488 /// in the source code.
2489 bool isWritten() const { return IsWritten; }
2490
2491 /// Return the source position of the initializer, counting from 0.
2492 /// If the initializer was implicit, -1 is returned.
2493 int getSourceOrder() const {
2494 return IsWritten ? static_cast<int>(SourceOrder) : -1;
2495 }
2496
2497 /// Set the source order of this initializer.
2498 ///
2499 /// This can only be called once for each initializer; it cannot be called
2500 /// on an initializer having a positive number of (implicit) array indices.
2501 ///
2502 /// This assumes that the initializer was written in the source code, and
2503 /// ensures that isWritten() returns true.
2504 void setSourceOrder(int Pos) {
2505 assert(!IsWritten &&((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2506, __PRETTY_FUNCTION__))
2506 "setSourceOrder() used on implicit initializer")((!IsWritten && "setSourceOrder() used on implicit initializer"
) ? static_cast<void> (0) : __assert_fail ("!IsWritten && \"setSourceOrder() used on implicit initializer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2506, __PRETTY_FUNCTION__))
;
2507 assert(SourceOrder == 0 &&((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2508, __PRETTY_FUNCTION__))
2508 "calling twice setSourceOrder() on the same initializer")((SourceOrder == 0 && "calling twice setSourceOrder() on the same initializer"
) ? static_cast<void> (0) : __assert_fail ("SourceOrder == 0 && \"calling twice setSourceOrder() on the same initializer\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2508, __PRETTY_FUNCTION__))
;
2509 assert(Pos >= 0 &&((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2510, __PRETTY_FUNCTION__))
2510 "setSourceOrder() used to make an initializer implicit")((Pos >= 0 && "setSourceOrder() used to make an initializer implicit"
) ? static_cast<void> (0) : __assert_fail ("Pos >= 0 && \"setSourceOrder() used to make an initializer implicit\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2510, __PRETTY_FUNCTION__))
;
2511 IsWritten = true;
2512 SourceOrder = static_cast<unsigned>(Pos);
2513 }
2514
2515 SourceLocation getLParenLoc() const { return LParenLoc; }
2516 SourceLocation getRParenLoc() const { return RParenLoc; }
2517
2518 /// Get the initializer.
2519 Expr *getInit() const { return static_cast<Expr *>(Init); }
2520};
2521
2522/// Description of a constructor that was inherited from a base class.
2523class InheritedConstructor {
2524 ConstructorUsingShadowDecl *Shadow = nullptr;
2525 CXXConstructorDecl *BaseCtor = nullptr;
2526
2527public:
2528 InheritedConstructor() = default;
2529 InheritedConstructor(ConstructorUsingShadowDecl *Shadow,
2530 CXXConstructorDecl *BaseCtor)
2531 : Shadow(Shadow), BaseCtor(BaseCtor) {}
2532
2533 explicit operator bool() const { return Shadow; }
2534
2535 ConstructorUsingShadowDecl *getShadowDecl() const { return Shadow; }
2536 CXXConstructorDecl *getConstructor() const { return BaseCtor; }
2537};
2538
2539/// Represents a C++ constructor within a class.
2540///
2541/// For example:
2542///
2543/// \code
2544/// class X {
2545/// public:
2546/// explicit X(int); // represented by a CXXConstructorDecl.
2547/// };
2548/// \endcode
2549class CXXConstructorDecl final
2550 : public CXXMethodDecl,
2551 private llvm::TrailingObjects<CXXConstructorDecl, InheritedConstructor,
2552 ExplicitSpecifier> {
2553 // This class stores some data in DeclContext::CXXConstructorDeclBits
2554 // to save some space. Use the provided accessors to access it.
2555
2556 /// \name Support for base and member initializers.
2557 /// \{
2558 /// The arguments used to initialize the base or member.
2559 LazyCXXCtorInitializersPtr CtorInitializers;
2560
2561 CXXConstructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2562 const DeclarationNameInfo &NameInfo, QualType T,
2563 TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool isInline,
2564 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind,
2565 InheritedConstructor Inherited);
2566
2567 void anchor() override;
2568
2569 size_t numTrailingObjects(OverloadToken<InheritedConstructor>) const {
2570 return CXXConstructorDeclBits.IsInheritingConstructor;
2571 }
2572 size_t numTrailingObjects(OverloadToken<ExplicitSpecifier>) const {
2573 return CXXConstructorDeclBits.HasTrailingExplicitSpecifier;
2574 }
2575
2576 ExplicitSpecifier getExplicitSpecifierInternal() const {
2577 if (CXXConstructorDeclBits.HasTrailingExplicitSpecifier)
2578 return *getTrailingObjects<ExplicitSpecifier>();
2579 return ExplicitSpecifier(
2580 nullptr, CXXConstructorDeclBits.IsSimpleExplicit
2581 ? ExplicitSpecKind::ResolvedTrue
2582 : ExplicitSpecKind::ResolvedFalse);
2583 }
2584
2585 void setExplicitSpecifier(ExplicitSpecifier ES) {
2586 assert((!ES.getExpr() ||(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2589, __PRETTY_FUNCTION__))
2587 CXXConstructorDeclBits.HasTrailingExplicitSpecifier) &&(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2589, __PRETTY_FUNCTION__))
2588 "cannot set this explicit specifier. no trail-allocated space for "(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2589, __PRETTY_FUNCTION__))
2589 "explicit")(((!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier
) && "cannot set this explicit specifier. no trail-allocated space for "
"explicit") ? static_cast<void> (0) : __assert_fail ("(!ES.getExpr() || CXXConstructorDeclBits.HasTrailingExplicitSpecifier) && \"cannot set this explicit specifier. no trail-allocated space for \" \"explicit\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2589, __PRETTY_FUNCTION__))
;
2590 if (ES.getExpr())
2591 *getCanonicalDecl()->getTrailingObjects<ExplicitSpecifier>() = ES;
2592 else
2593 CXXConstructorDeclBits.IsSimpleExplicit = ES.isExplicit();
2594 }
2595
2596 enum TraillingAllocKind {
2597 TAKInheritsConstructor = 1,
2598 TAKHasTailExplicit = 1 << 1,
2599 };
2600
2601 uint64_t getTraillingAllocKind() const {
2602 return numTrailingObjects(OverloadToken<InheritedConstructor>()) |
2603 (numTrailingObjects(OverloadToken<ExplicitSpecifier>()) << 1);
2604 }
2605
2606public:
2607 friend class ASTDeclReader;
2608 friend class ASTDeclWriter;
2609 friend TrailingObjects;
2610
2611 static CXXConstructorDecl *CreateDeserialized(ASTContext &C, unsigned ID,
2612 uint64_t AllocKind);
2613 static CXXConstructorDecl *
2614 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2615 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2616 ExplicitSpecifier ES, bool isInline, bool isImplicitlyDeclared,
2617 ConstexprSpecKind ConstexprKind,
2618 InheritedConstructor Inherited = InheritedConstructor());
2619
2620 ExplicitSpecifier getExplicitSpecifier() {
2621 return getCanonicalDecl()->getExplicitSpecifierInternal();
2622 }
2623 const ExplicitSpecifier getExplicitSpecifier() const {
2624 return getCanonicalDecl()->getExplicitSpecifierInternal();
2625 }
2626
2627 /// Return true if the declartion is already resolved to be explicit.
2628 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2629
2630 /// Iterates through the member/base initializer list.
2631 using init_iterator = CXXCtorInitializer **;
2632
2633 /// Iterates through the member/base initializer list.
2634 using init_const_iterator = CXXCtorInitializer *const *;
2635
2636 using init_range = llvm::iterator_range<init_iterator>;
2637 using init_const_range = llvm::iterator_range<init_const_iterator>;
2638
2639 init_range inits() { return init_range(init_begin(), init_end()); }
2640 init_const_range inits() const {
2641 return init_const_range(init_begin(), init_end());
2642 }
2643
2644 /// Retrieve an iterator to the first initializer.
2645 init_iterator init_begin() {
2646 const auto *ConstThis = this;
2647 return const_cast<init_iterator>(ConstThis->init_begin());
2648 }
2649
2650 /// Retrieve an iterator to the first initializer.
2651 init_const_iterator init_begin() const;
2652
2653 /// Retrieve an iterator past the last initializer.
2654 init_iterator init_end() {
2655 return init_begin() + getNumCtorInitializers();
2656 }
2657
2658 /// Retrieve an iterator past the last initializer.
2659 init_const_iterator init_end() const {
2660 return init_begin() + getNumCtorInitializers();
2661 }
2662
2663 using init_reverse_iterator = std::reverse_iterator<init_iterator>;
2664 using init_const_reverse_iterator =
2665 std::reverse_iterator<init_const_iterator>;
2666
2667 init_reverse_iterator init_rbegin() {
2668 return init_reverse_iterator(init_end());
2669 }
2670 init_const_reverse_iterator init_rbegin() const {
2671 return init_const_reverse_iterator(init_end());
2672 }
2673
2674 init_reverse_iterator init_rend() {
2675 return init_reverse_iterator(init_begin());
2676 }
2677 init_const_reverse_iterator init_rend() const {
2678 return init_const_reverse_iterator(init_begin());
2679 }
2680
2681 /// Determine the number of arguments used to initialize the member
2682 /// or base.
2683 unsigned getNumCtorInitializers() const {
2684 return CXXConstructorDeclBits.NumCtorInitializers;
2685 }
2686
2687 void setNumCtorInitializers(unsigned numCtorInitializers) {
2688 CXXConstructorDeclBits.NumCtorInitializers = numCtorInitializers;
2689 // This assert added because NumCtorInitializers is stored
2690 // in CXXConstructorDeclBits as a bitfield and its width has
2691 // been shrunk from 32 bits to fit into CXXConstructorDeclBitfields.
2692 assert(CXXConstructorDeclBits.NumCtorInitializers ==((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers
&& "NumCtorInitializers overflow!") ? static_cast<
void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2693, __PRETTY_FUNCTION__))
2693 numCtorInitializers && "NumCtorInitializers overflow!")((CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers
&& "NumCtorInitializers overflow!") ? static_cast<
void> (0) : __assert_fail ("CXXConstructorDeclBits.NumCtorInitializers == numCtorInitializers && \"NumCtorInitializers overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2693, __PRETTY_FUNCTION__))
;
2694 }
2695
2696 void setCtorInitializers(CXXCtorInitializer **Initializers) {
2697 CtorInitializers = Initializers;
2698 }
2699
2700 /// Determine whether this constructor is a delegating constructor.
2701 bool isDelegatingConstructor() const {
2702 return (getNumCtorInitializers() == 1) &&
2703 init_begin()[0]->isDelegatingInitializer();
2704 }
2705
2706 /// When this constructor delegates to another, retrieve the target.
2707 CXXConstructorDecl *getTargetConstructor() const;
2708
2709 /// Whether this constructor is a default
2710 /// constructor (C++ [class.ctor]p5), which can be used to
2711 /// default-initialize a class of this type.
2712 bool isDefaultConstructor() const;
2713
2714 /// Whether this constructor is a copy constructor (C++ [class.copy]p2,
2715 /// which can be used to copy the class.
2716 ///
2717 /// \p TypeQuals will be set to the qualifiers on the
2718 /// argument type. For example, \p TypeQuals would be set to \c
2719 /// Qualifiers::Const for the following copy constructor:
2720 ///
2721 /// \code
2722 /// class X {
2723 /// public:
2724 /// X(const X&);
2725 /// };
2726 /// \endcode
2727 bool isCopyConstructor(unsigned &TypeQuals) const;
2728
2729 /// Whether this constructor is a copy
2730 /// constructor (C++ [class.copy]p2, which can be used to copy the
2731 /// class.
2732 bool isCopyConstructor() const {
2733 unsigned TypeQuals = 0;
2734 return isCopyConstructor(TypeQuals);
2735 }
2736
2737 /// Determine whether this constructor is a move constructor
2738 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2739 ///
2740 /// \param TypeQuals If this constructor is a move constructor, will be set
2741 /// to the type qualifiers on the referent of the first parameter's type.
2742 bool isMoveConstructor(unsigned &TypeQuals) const;
2743
2744 /// Determine whether this constructor is a move constructor
2745 /// (C++11 [class.copy]p3), which can be used to move values of the class.
2746 bool isMoveConstructor() const {
2747 unsigned TypeQuals = 0;
2748 return isMoveConstructor(TypeQuals);
2749 }
2750
2751 /// Determine whether this is a copy or move constructor.
2752 ///
2753 /// \param TypeQuals Will be set to the type qualifiers on the reference
2754 /// parameter, if in fact this is a copy or move constructor.
2755 bool isCopyOrMoveConstructor(unsigned &TypeQuals) const;
2756
2757 /// Determine whether this a copy or move constructor.
2758 bool isCopyOrMoveConstructor() const {
2759 unsigned Quals;
2760 return isCopyOrMoveConstructor(Quals);
2761 }
2762
2763 /// Whether this constructor is a
2764 /// converting constructor (C++ [class.conv.ctor]), which can be
2765 /// used for user-defined conversions.
2766 bool isConvertingConstructor(bool AllowExplicit) const;
2767
2768 /// Determine whether this is a member template specialization that
2769 /// would copy the object to itself. Such constructors are never used to copy
2770 /// an object.
2771 bool isSpecializationCopyingObject() const;
2772
2773 /// Determine whether this is an implicit constructor synthesized to
2774 /// model a call to a constructor inherited from a base class.
2775 bool isInheritingConstructor() const {
2776 return CXXConstructorDeclBits.IsInheritingConstructor;
2777 }
2778
2779 /// State that this is an implicit constructor synthesized to
2780 /// model a call to a constructor inherited from a base class.
2781 void setInheritingConstructor(bool isIC = true) {
2782 CXXConstructorDeclBits.IsInheritingConstructor = isIC;
2783 }
2784
2785 /// Get the constructor that this inheriting constructor is based on.
2786 InheritedConstructor getInheritedConstructor() const {
2787 return isInheritingConstructor() ?
2788 *getTrailingObjects<InheritedConstructor>() : InheritedConstructor();
2789 }
2790
2791 CXXConstructorDecl *getCanonicalDecl() override {
2792 return cast<CXXConstructorDecl>(FunctionDecl::getCanonicalDecl());
2793 }
2794 const CXXConstructorDecl *getCanonicalDecl() const {
2795 return const_cast<CXXConstructorDecl*>(this)->getCanonicalDecl();
2796 }
2797
2798 // Implement isa/cast/dyncast/etc.
2799 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2800 static bool classofKind(Kind K) { return K == CXXConstructor; }
2801};
2802
2803/// Represents a C++ destructor within a class.
2804///
2805/// For example:
2806///
2807/// \code
2808/// class X {
2809/// public:
2810/// ~X(); // represented by a CXXDestructorDecl.
2811/// };
2812/// \endcode
2813class CXXDestructorDecl : public CXXMethodDecl {
2814 friend class ASTDeclReader;
2815 friend class ASTDeclWriter;
2816
2817 // FIXME: Don't allocate storage for these except in the first declaration
2818 // of a virtual destructor.
2819 FunctionDecl *OperatorDelete = nullptr;
2820 Expr *OperatorDeleteThisArg = nullptr;
2821
2822 CXXDestructorDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2823 const DeclarationNameInfo &NameInfo, QualType T,
2824 TypeSourceInfo *TInfo, bool isInline,
2825 bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind)
2826 : CXXMethodDecl(CXXDestructor, C, RD, StartLoc, NameInfo, T, TInfo,
2827 SC_None, isInline, ConstexprKind, SourceLocation()) {
2828 setImplicit(isImplicitlyDeclared);
2829 }
2830
2831 void anchor() override;
2832
2833public:
2834 static CXXDestructorDecl *Create(ASTContext &C, CXXRecordDecl *RD,
2835 SourceLocation StartLoc,
2836 const DeclarationNameInfo &NameInfo,
2837 QualType T, TypeSourceInfo *TInfo,
2838 bool isInline, bool isImplicitlyDeclared,
2839 ConstexprSpecKind ConstexprKind);
2840 static CXXDestructorDecl *CreateDeserialized(ASTContext & C, unsigned ID);
2841
2842 void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg);
2843
2844 const FunctionDecl *getOperatorDelete() const {
2845 return getCanonicalDecl()->OperatorDelete;
2846 }
2847
2848 Expr *getOperatorDeleteThisArg() const {
2849 return getCanonicalDecl()->OperatorDeleteThisArg;
2850 }
2851
2852 CXXDestructorDecl *getCanonicalDecl() override {
2853 return cast<CXXDestructorDecl>(FunctionDecl::getCanonicalDecl());
2854 }
2855 const CXXDestructorDecl *getCanonicalDecl() const {
2856 return const_cast<CXXDestructorDecl*>(this)->getCanonicalDecl();
2857 }
2858
2859 // Implement isa/cast/dyncast/etc.
2860 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2861 static bool classofKind(Kind K) { return K == CXXDestructor; }
2862};
2863
2864/// Represents a C++ conversion function within a class.
2865///
2866/// For example:
2867///
2868/// \code
2869/// class X {
2870/// public:
2871/// operator bool();
2872/// };
2873/// \endcode
2874class CXXConversionDecl : public CXXMethodDecl {
2875 CXXConversionDecl(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2876 const DeclarationNameInfo &NameInfo, QualType T,
2877 TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES,
2878 ConstexprSpecKind ConstexprKind, SourceLocation EndLocation)
2879 : CXXMethodDecl(CXXConversion, C, RD, StartLoc, NameInfo, T, TInfo,
2880 SC_None, isInline, ConstexprKind, EndLocation),
2881 ExplicitSpec(ES) {}
2882 void anchor() override;
2883
2884 ExplicitSpecifier ExplicitSpec;
2885
2886 void setExplicitSpecifier(ExplicitSpecifier ES) { ExplicitSpec = ES; }
2887
2888public:
2889 friend class ASTDeclReader;
2890 friend class ASTDeclWriter;
2891
2892 static CXXConversionDecl *
2893 Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc,
2894 const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo,
2895 bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind,
2896 SourceLocation EndLocation);
2897 static CXXConversionDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2898
2899 ExplicitSpecifier getExplicitSpecifier() {
2900 return getCanonicalDecl()->ExplicitSpec;
2901 }
2902
2903 const ExplicitSpecifier getExplicitSpecifier() const {
2904 return getCanonicalDecl()->ExplicitSpec;
2905 }
2906
2907 /// Return true if the declartion is already resolved to be explicit.
2908 bool isExplicit() const { return getExplicitSpecifier().isExplicit(); }
2909
2910 /// Returns the type that this conversion function is converting to.
2911 QualType getConversionType() const {
2912 return getType()->castAs<FunctionType>()->getReturnType();
2913 }
2914
2915 /// Determine whether this conversion function is a conversion from
2916 /// a lambda closure type to a block pointer.
2917 bool isLambdaToBlockPointerConversion() const;
2918
2919 CXXConversionDecl *getCanonicalDecl() override {
2920 return cast<CXXConversionDecl>(FunctionDecl::getCanonicalDecl());
2921 }
2922 const CXXConversionDecl *getCanonicalDecl() const {
2923 return const_cast<CXXConversionDecl*>(this)->getCanonicalDecl();
2924 }
2925
2926 // Implement isa/cast/dyncast/etc.
2927 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2928 static bool classofKind(Kind K) { return K == CXXConversion; }
2929};
2930
2931/// Represents a linkage specification.
2932///
2933/// For example:
2934/// \code
2935/// extern "C" void foo();
2936/// \endcode
2937class LinkageSpecDecl : public Decl, public DeclContext {
2938 virtual void anchor();
2939 // This class stores some data in DeclContext::LinkageSpecDeclBits to save
2940 // some space. Use the provided accessors to access it.
2941public:
2942 /// Represents the language in a linkage specification.
2943 ///
2944 /// The values are part of the serialization ABI for
2945 /// ASTs and cannot be changed without altering that ABI. To help
2946 /// ensure a stable ABI for this, we choose the DW_LANG_ encodings
2947 /// from the dwarf standard.
2948 enum LanguageIDs {
2949 lang_c = llvm::dwarf::DW_LANG_C,
2950 lang_cxx = llvm::dwarf::DW_LANG_C_plus_plus,
2951 lang_cxx_11 = llvm::dwarf::DW_LANG_C_plus_plus_11,
2952 lang_cxx_14 = llvm::dwarf::DW_LANG_C_plus_plus_14
2953 };
2954
2955private:
2956 /// The source location for the extern keyword.
2957 SourceLocation ExternLoc;
2958
2959 /// The source location for the right brace (if valid).
2960 SourceLocation RBraceLoc;
2961
2962 LinkageSpecDecl(DeclContext *DC, SourceLocation ExternLoc,
2963 SourceLocation LangLoc, LanguageIDs lang, bool HasBraces);
2964
2965public:
2966 static LinkageSpecDecl *Create(ASTContext &C, DeclContext *DC,
2967 SourceLocation ExternLoc,
2968 SourceLocation LangLoc, LanguageIDs Lang,
2969 bool HasBraces);
2970 static LinkageSpecDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2971
2972 /// Return the language specified by this linkage specification.
2973 LanguageIDs getLanguage() const {
2974 return static_cast<LanguageIDs>(LinkageSpecDeclBits.Language);
2975 }
2976
2977 /// Set the language specified by this linkage specification.
2978 void setLanguage(LanguageIDs L) { LinkageSpecDeclBits.Language = L; }
2979
2980 /// Determines whether this linkage specification had braces in
2981 /// its syntactic form.
2982 bool hasBraces() const {
2983 assert(!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces)((!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces) ? static_cast
<void> (0) : __assert_fail ("!RBraceLoc.isValid() || LinkageSpecDeclBits.HasBraces"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 2983, __PRETTY_FUNCTION__))
;
2984 return LinkageSpecDeclBits.HasBraces;
2985 }
2986
2987 SourceLocation getExternLoc() const { return ExternLoc; }
2988 SourceLocation getRBraceLoc() const { return RBraceLoc; }
2989 void setExternLoc(SourceLocation L) { ExternLoc = L; }
2990 void setRBraceLoc(SourceLocation L) {
2991 RBraceLoc = L;
2992 LinkageSpecDeclBits.HasBraces = RBraceLoc.isValid();
2993 }
2994
2995 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2996 if (hasBraces())
2997 return getRBraceLoc();
2998 // No braces: get the end location of the (only) declaration in context
2999 // (if present).
3000 return decls_empty() ? getLocation() : decls_begin()->getEndLoc();
3001 }
3002
3003 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3004 return SourceRange(ExternLoc, getEndLoc());
3005 }
3006
3007 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3008 static bool classofKind(Kind K) { return K == LinkageSpec; }
3009
3010 static DeclContext *castToDeclContext(const LinkageSpecDecl *D) {
3011 return static_cast<DeclContext *>(const_cast<LinkageSpecDecl*>(D));
3012 }
3013
3014 static LinkageSpecDecl *castFromDeclContext(const DeclContext *DC) {
3015 return static_cast<LinkageSpecDecl *>(const_cast<DeclContext*>(DC));
3016 }
3017};
3018
3019/// Represents C++ using-directive.
3020///
3021/// For example:
3022/// \code
3023/// using namespace std;
3024/// \endcode
3025///
3026/// \note UsingDirectiveDecl should be Decl not NamedDecl, but we provide
3027/// artificial names for all using-directives in order to store
3028/// them in DeclContext effectively.
3029class UsingDirectiveDecl : public NamedDecl {
3030 /// The location of the \c using keyword.
3031 SourceLocation UsingLoc;
3032
3033 /// The location of the \c namespace keyword.
3034 SourceLocation NamespaceLoc;
3035
3036 /// The nested-name-specifier that precedes the namespace.
3037 NestedNameSpecifierLoc QualifierLoc;
3038
3039 /// The namespace nominated by this using-directive.
3040 NamedDecl *NominatedNamespace;
3041
3042 /// Enclosing context containing both using-directive and nominated
3043 /// namespace.
3044 DeclContext *CommonAncestor;
3045
3046 UsingDirectiveDecl(DeclContext *DC, SourceLocation UsingLoc,
3047 SourceLocation NamespcLoc,
3048 NestedNameSpecifierLoc QualifierLoc,
3049 SourceLocation IdentLoc,
3050 NamedDecl *Nominated,
3051 DeclContext *CommonAncestor)
3052 : NamedDecl(UsingDirective, DC, IdentLoc, getName()), UsingLoc(UsingLoc),
3053 NamespaceLoc(NamespcLoc), QualifierLoc(QualifierLoc),
3054 NominatedNamespace(Nominated), CommonAncestor(CommonAncestor) {}
3055
3056 /// Returns special DeclarationName used by using-directives.
3057 ///
3058 /// This is only used by DeclContext for storing UsingDirectiveDecls in
3059 /// its lookup structure.
3060 static DeclarationName getName() {
3061 return DeclarationName::getUsingDirectiveName();
3062 }
3063
3064 void anchor() override;
3065
3066public:
3067 friend class ASTDeclReader;
3068
3069 // Friend for getUsingDirectiveName.
3070 friend class DeclContext;
3071
3072 /// Retrieve the nested-name-specifier that qualifies the
3073 /// name of the namespace, with source-location information.
3074 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3075
3076 /// Retrieve the nested-name-specifier that qualifies the
3077 /// name of the namespace.
3078 NestedNameSpecifier *getQualifier() const {
3079 return QualifierLoc.getNestedNameSpecifier();
3080 }
3081
3082 NamedDecl *getNominatedNamespaceAsWritten() { return NominatedNamespace; }
3083 const NamedDecl *getNominatedNamespaceAsWritten() const {
3084 return NominatedNamespace;
3085 }
3086
3087 /// Returns the namespace nominated by this using-directive.
3088 NamespaceDecl *getNominatedNamespace();
3089
3090 const NamespaceDecl *getNominatedNamespace() const {
3091 return const_cast<UsingDirectiveDecl*>(this)->getNominatedNamespace();
3092 }
3093
3094 /// Returns the common ancestor context of this using-directive and
3095 /// its nominated namespace.
3096 DeclContext *getCommonAncestor() { return CommonAncestor; }
3097 const DeclContext *getCommonAncestor() const { return CommonAncestor; }
3098
3099 /// Return the location of the \c using keyword.
3100 SourceLocation getUsingLoc() const { return UsingLoc; }
3101
3102 // FIXME: Could omit 'Key' in name.
3103 /// Returns the location of the \c namespace keyword.
3104 SourceLocation getNamespaceKeyLocation() const { return NamespaceLoc; }
3105
3106 /// Returns the location of this using declaration's identifier.
3107 SourceLocation getIdentLocation() const { return getLocation(); }
3108
3109 static UsingDirectiveDecl *Create(ASTContext &C, DeclContext *DC,
3110 SourceLocation UsingLoc,
3111 SourceLocation NamespaceLoc,
3112 NestedNameSpecifierLoc QualifierLoc,
3113 SourceLocation IdentLoc,
3114 NamedDecl *Nominated,
3115 DeclContext *CommonAncestor);
3116 static UsingDirectiveDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3117
3118 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3119 return SourceRange(UsingLoc, getLocation());
3120 }
3121
3122 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3123 static bool classofKind(Kind K) { return K == UsingDirective; }
3124};
3125
3126/// Represents a C++ namespace alias.
3127///
3128/// For example:
3129///
3130/// \code
3131/// namespace Foo = Bar;
3132/// \endcode
3133class NamespaceAliasDecl : public NamedDecl,
3134 public Redeclarable<NamespaceAliasDecl> {
3135 friend class ASTDeclReader;
3136
3137 /// The location of the \c namespace keyword.
3138 SourceLocation NamespaceLoc;
3139
3140 /// The location of the namespace's identifier.
3141 ///
3142 /// This is accessed by TargetNameLoc.
3143 SourceLocation IdentLoc;
3144
3145 /// The nested-name-specifier that precedes the namespace.
3146 NestedNameSpecifierLoc QualifierLoc;
3147
3148 /// The Decl that this alias points to, either a NamespaceDecl or
3149 /// a NamespaceAliasDecl.
3150 NamedDecl *Namespace;
3151
3152 NamespaceAliasDecl(ASTContext &C, DeclContext *DC,
3153 SourceLocation NamespaceLoc, SourceLocation AliasLoc,
3154 IdentifierInfo *Alias, NestedNameSpecifierLoc QualifierLoc,
3155 SourceLocation IdentLoc, NamedDecl *Namespace)
3156 : NamedDecl(NamespaceAlias, DC, AliasLoc, Alias), redeclarable_base(C),
3157 NamespaceLoc(NamespaceLoc), IdentLoc(IdentLoc),
3158 QualifierLoc(QualifierLoc), Namespace(Namespace) {}
3159
3160 void anchor() override;
3161
3162 using redeclarable_base = Redeclarable<NamespaceAliasDecl>;
3163
3164 NamespaceAliasDecl *getNextRedeclarationImpl() override;
3165 NamespaceAliasDecl *getPreviousDeclImpl() override;
3166 NamespaceAliasDecl *getMostRecentDeclImpl() override;
3167
3168public:
3169 static NamespaceAliasDecl *Create(ASTContext &C, DeclContext *DC,
3170 SourceLocation NamespaceLoc,
3171 SourceLocation AliasLoc,
3172 IdentifierInfo *Alias,
3173 NestedNameSpecifierLoc QualifierLoc,
3174 SourceLocation IdentLoc,
3175 NamedDecl *Namespace);
3176
3177 static NamespaceAliasDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3178
3179 using redecl_range = redeclarable_base::redecl_range;
3180 using redecl_iterator = redeclarable_base::redecl_iterator;
3181
3182 using redeclarable_base::redecls_begin;
3183 using redeclarable_base::redecls_end;
3184 using redeclarable_base::redecls;
3185 using redeclarable_base::getPreviousDecl;
3186 using redeclarable_base::getMostRecentDecl;
3187
3188 NamespaceAliasDecl *getCanonicalDecl() override {
3189 return getFirstDecl();
3190 }
3191 const NamespaceAliasDecl *getCanonicalDecl() const {
3192 return getFirstDecl();
3193 }
3194
3195 /// Retrieve the nested-name-specifier that qualifies the
3196 /// name of the namespace, with source-location information.
3197 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3198
3199 /// Retrieve the nested-name-specifier that qualifies the
3200 /// name of the namespace.
3201 NestedNameSpecifier *getQualifier() const {
3202 return QualifierLoc.getNestedNameSpecifier();
3203 }
3204
3205 /// Retrieve the namespace declaration aliased by this directive.
3206 NamespaceDecl *getNamespace() {
3207 if (auto *AD = dyn_cast<NamespaceAliasDecl>(Namespace))
3208 return AD->getNamespace();
3209
3210 return cast<NamespaceDecl>(Namespace);
3211 }
3212
3213 const NamespaceDecl *getNamespace() const {
3214 return const_cast<NamespaceAliasDecl *>(this)->getNamespace();
3215 }
3216
3217 /// Returns the location of the alias name, i.e. 'foo' in
3218 /// "namespace foo = ns::bar;".
3219 SourceLocation getAliasLoc() const { return getLocation(); }
3220
3221 /// Returns the location of the \c namespace keyword.
3222 SourceLocation getNamespaceLoc() const { return NamespaceLoc; }
3223
3224 /// Returns the location of the identifier in the named namespace.
3225 SourceLocation getTargetNameLoc() const { return IdentLoc; }
3226
3227 /// Retrieve the namespace that this alias refers to, which
3228 /// may either be a NamespaceDecl or a NamespaceAliasDecl.
3229 NamedDecl *getAliasedNamespace() const { return Namespace; }
3230
3231 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3232 return SourceRange(NamespaceLoc, IdentLoc);
3233 }
3234
3235 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3236 static bool classofKind(Kind K) { return K == NamespaceAlias; }
3237};
3238
3239/// Represents a shadow declaration introduced into a scope by a
3240/// (resolved) using declaration.
3241///
3242/// For example,
3243/// \code
3244/// namespace A {
3245/// void foo();
3246/// }
3247/// namespace B {
3248/// using A::foo; // <- a UsingDecl
3249/// // Also creates a UsingShadowDecl for A::foo() in B
3250/// }
3251/// \endcode
3252class UsingShadowDecl : public NamedDecl, public Redeclarable<UsingShadowDecl> {
3253 friend class UsingDecl;
3254
3255 /// The referenced declaration.
3256 NamedDecl *Underlying = nullptr;
3257
3258 /// The using declaration which introduced this decl or the next using
3259 /// shadow declaration contained in the aforementioned using declaration.
3260 NamedDecl *UsingOrNextShadow = nullptr;
3261
3262 void anchor() override;
3263
3264 using redeclarable_base = Redeclarable<UsingShadowDecl>;
3265
3266 UsingShadowDecl *getNextRedeclarationImpl() override {
3267 return getNextRedeclaration();
3268 }
3269
3270 UsingShadowDecl *getPreviousDeclImpl() override {
3271 return getPreviousDecl();
3272 }
3273
3274 UsingShadowDecl *getMostRecentDeclImpl() override {
3275 return getMostRecentDecl();
3276 }
3277
3278protected:
3279 UsingShadowDecl(Kind K, ASTContext &C, DeclContext *DC, SourceLocation Loc,
3280 UsingDecl *Using, NamedDecl *Target);
3281 UsingShadowDecl(Kind K, ASTContext &C, EmptyShell);
3282
3283public:
3284 friend class ASTDeclReader;
3285 friend class ASTDeclWriter;
3286
3287 static UsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3288 SourceLocation Loc, UsingDecl *Using,
3289 NamedDecl *Target) {
3290 return new (C, DC) UsingShadowDecl(UsingShadow, C, DC, Loc, Using, Target);
3291 }
3292
3293 static UsingShadowDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3294
3295 using redecl_range = redeclarable_base::redecl_range;
3296 using redecl_iterator = redeclarable_base::redecl_iterator;
3297
3298 using redeclarable_base::redecls_begin;
3299 using redeclarable_base::redecls_end;
3300 using redeclarable_base::redecls;
3301 using redeclarable_base::getPreviousDecl;
3302 using redeclarable_base::getMostRecentDecl;
3303 using redeclarable_base::isFirstDecl;
3304
3305 UsingShadowDecl *getCanonicalDecl() override {
3306 return getFirstDecl();
3307 }
3308 const UsingShadowDecl *getCanonicalDecl() const {
3309 return getFirstDecl();
3310 }
3311
3312 /// Gets the underlying declaration which has been brought into the
3313 /// local scope.
3314 NamedDecl *getTargetDecl() const { return Underlying; }
3315
3316 /// Sets the underlying declaration which has been brought into the
3317 /// local scope.
3318 void setTargetDecl(NamedDecl *ND) {
3319 assert(ND && "Target decl is null!")((ND && "Target decl is null!") ? static_cast<void
> (0) : __assert_fail ("ND && \"Target decl is null!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/DeclCXX.h"
, 3319, __PRETTY_FUNCTION__))
;
3320 Underlying = ND;
3321 // A UsingShadowDecl is never a friend or local extern declaration, even
3322 // if it is a shadow declaration for one.
3323 IdentifierNamespace =
3324 ND->getIdentifierNamespace() &
3325 ~(IDNS_OrdinaryFriend | IDNS_TagFriend | IDNS_LocalExtern);
3326 }
3327
3328 /// Gets the using declaration to which this declaration is tied.
3329 UsingDecl *getUsingDecl() const;
3330
3331 /// The next using shadow declaration contained in the shadow decl
3332 /// chain of the using declaration which introduced this decl.
3333 UsingShadowDecl *getNextUsingShadowDecl() const {
3334 return dyn_cast_or_null<UsingShadowDecl>(UsingOrNextShadow);
3335 }
3336
3337 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3338 static bool classofKind(Kind K) {
3339 return K == Decl::UsingShadow || K == Decl::ConstructorUsingShadow;
3340 }
3341};
3342
3343/// Represents a shadow constructor declaration introduced into a
3344/// class by a C++11 using-declaration that names a constructor.
3345///
3346/// For example:
3347/// \code
3348/// struct Base { Base(int); };
3349/// struct Derived {
3350/// using Base::Base; // creates a UsingDecl and a ConstructorUsingShadowDecl
3351/// };
3352/// \endcode
3353class ConstructorUsingShadowDecl final : public UsingShadowDecl {
3354 /// If this constructor using declaration inherted the constructor
3355 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3356 /// in the named direct base class from which the declaration was inherited.
3357 ConstructorUsingShadowDecl *NominatedBaseClassShadowDecl = nullptr;
3358
3359 /// If this constructor using declaration inherted the constructor
3360 /// from an indirect base class, this is the ConstructorUsingShadowDecl
3361 /// that will be used to construct the unique direct or virtual base class
3362 /// that receives the constructor arguments.
3363 ConstructorUsingShadowDecl *ConstructedBaseClassShadowDecl = nullptr;
3364
3365 /// \c true if the constructor ultimately named by this using shadow
3366 /// declaration is within a virtual base class subobject of the class that
3367 /// contains this declaration.
3368 unsigned IsVirtual : 1;
3369
3370 ConstructorUsingShadowDecl(ASTContext &C, DeclContext *DC, SourceLocation Loc,
3371 UsingDecl *Using, NamedDecl *Target,
3372 bool TargetInVirtualBase)
3373 : UsingShadowDecl(ConstructorUsingShadow, C, DC, Loc, Using,
3374 Target->getUnderlyingDecl()),
3375 NominatedBaseClassShadowDecl(
3376 dyn_cast<ConstructorUsingShadowDecl>(Target)),
3377 ConstructedBaseClassShadowDecl(NominatedBaseClassShadowDecl),
3378 IsVirtual(TargetInVirtualBase) {
3379 // If we found a constructor that chains to a constructor for a virtual
3380 // base, we should directly call that virtual base constructor instead.
3381 // FIXME: This logic belongs in Sema.
3382 if (NominatedBaseClassShadowDecl &&
3383 NominatedBaseClassShadowDecl->constructsVirtualBase()) {
3384 ConstructedBaseClassShadowDecl =
3385 NominatedBaseClassShadowDecl->ConstructedBaseClassShadowDecl;
3386 IsVirtual = true;
3387 }
3388 }
3389
3390 ConstructorUsingShadowDecl(ASTContext &C, EmptyShell Empty)
3391 : UsingShadowDecl(ConstructorUsingShadow, C, Empty), IsVirtual(false) {}
3392
3393 void anchor() override;
3394
3395public:
3396 friend class ASTDeclReader;
3397 friend class ASTDeclWriter;
3398
3399 static ConstructorUsingShadowDecl *Create(ASTContext &C, DeclContext *DC,
3400 SourceLocation Loc,
3401 UsingDecl *Using, NamedDecl *Target,
3402 bool IsVirtual);
3403 static ConstructorUsingShadowDecl *CreateDeserialized(ASTContext &C,
3404 unsigned ID);
3405
3406 /// Returns the parent of this using shadow declaration, which
3407 /// is the class in which this is declared.
3408 //@{
3409 const CXXRecordDecl *getParent() const {
3410 return cast<CXXRecordDecl>(getDeclContext());
3411 }
3412 CXXRecordDecl *getParent() {
3413 return cast<CXXRecordDecl>(getDeclContext());
3414 }
3415 //@}
3416
3417 /// Get the inheriting constructor declaration for the direct base
3418 /// class from which this using shadow declaration was inherited, if there is
3419 /// one. This can be different for each redeclaration of the same shadow decl.
3420 ConstructorUsingShadowDecl *getNominatedBaseClassShadowDecl() const {
3421 return NominatedBaseClassShadowDecl;
3422 }
3423
3424 /// Get the inheriting constructor declaration for the base class
3425 /// for which we don't have an explicit initializer, if there is one.
3426 ConstructorUsingShadowDecl *getConstructedBaseClassShadowDecl() const {
3427 return ConstructedBaseClassShadowDecl;
3428 }
3429
3430 /// Get the base class that was named in the using declaration. This
3431 /// can be different for each redeclaration of this same shadow decl.
3432 CXXRecordDecl *getNominatedBaseClass() const;
3433
3434 /// Get the base class whose constructor or constructor shadow
3435 /// declaration is passed the constructor arguments.
3436 CXXRecordDecl *getConstructedBaseClass() const {
3437 return cast<CXXRecordDecl>((ConstructedBaseClassShadowDecl
3438 ? ConstructedBaseClassShadowDecl
3439 : getTargetDecl())
3440 ->getDeclContext());
3441 }
3442
3443 /// Returns \c true if the constructed base class is a virtual base
3444 /// class subobject of this declaration's class.
3445 bool constructsVirtualBase() const {
3446 return IsVirtual;
3447 }
3448
3449 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3450 static bool classofKind(Kind K) { return K == ConstructorUsingShadow; }
3451};
3452
3453/// Represents a C++ using-declaration.
3454///
3455/// For example:
3456/// \code
3457/// using someNameSpace::someIdentifier;
3458/// \endcode
3459class UsingDecl : public NamedDecl, public Mergeable<UsingDecl> {
3460 /// The source location of the 'using' keyword itself.
3461 SourceLocation UsingLocation;
3462
3463 /// The nested-name-specifier that precedes the name.
3464 NestedNameSpecifierLoc QualifierLoc;
3465
3466 /// Provides source/type location info for the declaration name
3467 /// embedded in the ValueDecl base class.
3468 DeclarationNameLoc DNLoc;
3469
3470 /// The first shadow declaration of the shadow decl chain associated
3471 /// with this using declaration.
3472 ///
3473 /// The bool member of the pair store whether this decl has the \c typename
3474 /// keyword.
3475 llvm::PointerIntPair<UsingShadowDecl *, 1, bool> FirstUsingShadow;
3476
3477 UsingDecl(DeclContext *DC, SourceLocation UL,
3478 NestedNameSpecifierLoc QualifierLoc,
3479 const DeclarationNameInfo &NameInfo, bool HasTypenameKeyword)
3480 : NamedDecl(Using, DC, NameInfo.getLoc(), NameInfo.getName()),
3481 UsingLocation(UL), QualifierLoc(QualifierLoc),
3482 DNLoc(NameInfo.getInfo()), FirstUsingShadow(nullptr, HasTypenameKeyword) {
3483 }
3484
3485 void anchor() override;
3486
3487public:
3488 friend class ASTDeclReader;
3489 friend class ASTDeclWriter;
3490
3491 /// Return the source location of the 'using' keyword.
3492 SourceLocation getUsingLoc() const { return UsingLocation; }
3493
3494 /// Set the source location of the 'using' keyword.
3495 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3496
3497 /// Retrieve the nested-name-specifier that qualifies the name,
3498 /// with source-location information.
3499 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3500
3501 /// Retrieve the nested-name-specifier that qualifies the name.
3502 NestedNameSpecifier *getQualifier() const {
3503 return QualifierLoc.getNestedNameSpecifier();
3504 }
3505
3506 DeclarationNameInfo getNameInfo() const {
3507 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3508 }
3509
3510 /// Return true if it is a C++03 access declaration (no 'using').
3511 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3512
3513 /// Return true if the using declaration has 'typename'.
3514 bool hasTypename() const { return FirstUsingShadow.getInt(); }
3515
3516 /// Sets whether the using declaration has 'typename'.
3517 void setTypename(bool TN) { FirstUsingShadow.setInt(TN); }
3518
3519 /// Iterates through the using shadow declarations associated with
3520 /// this using declaration.
3521 class shadow_iterator {
3522 /// The current using shadow declaration.
3523 UsingShadowDecl *Current = nullptr;
3524
3525 public:
3526 using value_type = UsingShadowDecl *;
3527 using reference = UsingShadowDecl *;
3528 using pointer = UsingShadowDecl *;
3529 using iterator_category = std::forward_iterator_tag;
3530 using difference_type = std::ptrdiff_t;
3531
3532 shadow_iterator() = default;
3533 explicit shadow_iterator(UsingShadowDecl *C) : Current(C) {}
3534
3535 reference operator*() const { return Current; }
3536 pointer operator->() const { return Current; }
3537
3538 shadow_iterator& operator++() {
3539 Current = Current->getNextUsingShadowDecl();
3540 return *this;
3541 }
3542
3543 shadow_iterator operator++(int) {
3544 shadow_iterator tmp(*this);
3545 ++(*this);
3546 return tmp;
3547 }
3548
3549 friend bool operator==(shadow_iterator x, shadow_iterator y) {
3550 return x.Current == y.Current;
3551 }
3552 friend bool operator!=(shadow_iterator x, shadow_iterator y) {
3553 return x.Current != y.Current;
3554 }
3555 };
3556
3557 using shadow_range = llvm::iterator_range<shadow_iterator>;
3558
3559 shadow_range shadows() const {
3560 return shadow_range(shadow_begin(), shadow_end());
3561 }
3562
3563 shadow_iterator shadow_begin() const {
3564 return shadow_iterator(FirstUsingShadow.getPointer());
3565 }
3566
3567 shadow_iterator shadow_end() const { return shadow_iterator(); }
3568
3569 /// Return the number of shadowed declarations associated with this
3570 /// using declaration.
3571 unsigned shadow_size() const {
3572 return std::distance(shadow_begin(), shadow_end());
3573 }
3574
3575 void addShadowDecl(UsingShadowDecl *S);
3576 void removeShadowDecl(UsingShadowDecl *S);
3577
3578 static UsingDecl *Create(ASTContext &C, DeclContext *DC,
3579 SourceLocation UsingL,
3580 NestedNameSpecifierLoc QualifierLoc,
3581 const DeclarationNameInfo &NameInfo,
3582 bool HasTypenameKeyword);
3583
3584 static UsingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3585
3586 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3587
3588 /// Retrieves the canonical declaration of this declaration.
3589 UsingDecl *getCanonicalDecl() override { return getFirstDecl(); }
3590 const UsingDecl *getCanonicalDecl() const { return getFirstDecl(); }
3591
3592 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3593 static bool classofKind(Kind K) { return K == Using; }
3594};
3595
3596/// Represents a pack of using declarations that a single
3597/// using-declarator pack-expanded into.
3598///
3599/// \code
3600/// template<typename ...T> struct X : T... {
3601/// using T::operator()...;
3602/// using T::operator T...;
3603/// };
3604/// \endcode
3605///
3606/// In the second case above, the UsingPackDecl will have the name
3607/// 'operator T' (which contains an unexpanded pack), but the individual
3608/// UsingDecls and UsingShadowDecls will have more reasonable names.
3609class UsingPackDecl final
3610 : public NamedDecl, public Mergeable<UsingPackDecl>,
3611 private llvm::TrailingObjects<UsingPackDecl, NamedDecl *> {
3612 /// The UnresolvedUsingValueDecl or UnresolvedUsingTypenameDecl from
3613 /// which this waas instantiated.
3614 NamedDecl *InstantiatedFrom;
3615
3616 /// The number of using-declarations created by this pack expansion.
3617 unsigned NumExpansions;
3618
3619 UsingPackDecl(DeclContext *DC, NamedDecl *InstantiatedFrom,
3620 ArrayRef<NamedDecl *> UsingDecls)
3621 : NamedDecl(UsingPack, DC,
3622 InstantiatedFrom ? InstantiatedFrom->getLocation()
3623 : SourceLocation(),
3624 InstantiatedFrom ? InstantiatedFrom->getDeclName()
3625 : DeclarationName()),
3626 InstantiatedFrom(InstantiatedFrom), NumExpansions(UsingDecls.size()) {
3627 std::uninitialized_copy(UsingDecls.begin(), UsingDecls.end(),
3628 getTrailingObjects<NamedDecl *>());
3629 }
3630
3631 void anchor() override;
3632
3633public:
3634 friend class ASTDeclReader;
3635 friend class ASTDeclWriter;
3636 friend TrailingObjects;
3637
3638 /// Get the using declaration from which this was instantiated. This will
3639 /// always be an UnresolvedUsingValueDecl or an UnresolvedUsingTypenameDecl
3640 /// that is a pack expansion.
3641 NamedDecl *getInstantiatedFromUsingDecl() const { return InstantiatedFrom; }
3642
3643 /// Get the set of using declarations that this pack expanded into. Note that
3644 /// some of these may still be unresolved.
3645 ArrayRef<NamedDecl *> expansions() const {
3646 return llvm::makeArrayRef(getTrailingObjects<NamedDecl *>(), NumExpansions);
3647 }
3648
3649 static UsingPackDecl *Create(ASTContext &C, DeclContext *DC,
3650 NamedDecl *InstantiatedFrom,
3651 ArrayRef<NamedDecl *> UsingDecls);
3652
3653 static UsingPackDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3654 unsigned NumExpansions);
3655
3656 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3657 return InstantiatedFrom->getSourceRange();
3658 }
3659
3660 UsingPackDecl *getCanonicalDecl() override { return getFirstDecl(); }
3661 const UsingPackDecl *getCanonicalDecl() const { return getFirstDecl(); }
3662
3663 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3664 static bool classofKind(Kind K) { return K == UsingPack; }
3665};
3666
3667/// Represents a dependent using declaration which was not marked with
3668/// \c typename.
3669///
3670/// Unlike non-dependent using declarations, these *only* bring through
3671/// non-types; otherwise they would break two-phase lookup.
3672///
3673/// \code
3674/// template \<class T> class A : public Base<T> {
3675/// using Base<T>::foo;
3676/// };
3677/// \endcode
3678class UnresolvedUsingValueDecl : public ValueDecl,
3679 public Mergeable<UnresolvedUsingValueDecl> {
3680 /// The source location of the 'using' keyword
3681 SourceLocation UsingLocation;
3682
3683 /// If this is a pack expansion, the location of the '...'.
3684 SourceLocation EllipsisLoc;
3685
3686 /// The nested-name-specifier that precedes the name.
3687 NestedNameSpecifierLoc QualifierLoc;
3688
3689 /// Provides source/type location info for the declaration name
3690 /// embedded in the ValueDecl base class.
3691 DeclarationNameLoc DNLoc;
3692
3693 UnresolvedUsingValueDecl(DeclContext *DC, QualType Ty,
3694 SourceLocation UsingLoc,
3695 NestedNameSpecifierLoc QualifierLoc,
3696 const DeclarationNameInfo &NameInfo,
3697 SourceLocation EllipsisLoc)
3698 : ValueDecl(UnresolvedUsingValue, DC,
3699 NameInfo.getLoc(), NameInfo.getName(), Ty),
3700 UsingLocation(UsingLoc), EllipsisLoc(EllipsisLoc),
3701 QualifierLoc(QualifierLoc), DNLoc(NameInfo.getInfo()) {}
3702
3703 void anchor() override;
3704
3705public:
3706 friend class ASTDeclReader;
3707 friend class ASTDeclWriter;
3708
3709 /// Returns the source location of the 'using' keyword.
3710 SourceLocation getUsingLoc() const { return UsingLocation; }
3711
3712 /// Set the source location of the 'using' keyword.
3713 void setUsingLoc(SourceLocation L) { UsingLocation = L; }
3714
3715 /// Return true if it is a C++03 access declaration (no 'using').
3716 bool isAccessDeclaration() const { return UsingLocation.isInvalid(); }
3717
3718 /// Retrieve the nested-name-specifier that qualifies the name,
3719 /// with source-location information.
3720 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3721
3722 /// Retrieve the nested-name-specifier that qualifies the name.
3723 NestedNameSpecifier *getQualifier() const {
3724 return QualifierLoc.getNestedNameSpecifier();
3725 }
3726
3727 DeclarationNameInfo getNameInfo() const {
3728 return DeclarationNameInfo(getDeclName(), getLocation(), DNLoc);
3729 }
3730
3731 /// Determine whether this is a pack expansion.
3732 bool isPackExpansion() const {
3733 return EllipsisLoc.isValid();
3734 }
3735
3736 /// Get the location of the ellipsis if this is a pack expansion.
3737 SourceLocation getEllipsisLoc() const {
3738 return EllipsisLoc;
3739 }
3740
3741 static UnresolvedUsingValueDecl *
3742 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3743 NestedNameSpecifierLoc QualifierLoc,
3744 const DeclarationNameInfo &NameInfo, SourceLocation EllipsisLoc);
3745
3746 static UnresolvedUsingValueDecl *
3747 CreateDeserialized(ASTContext &C, unsigned ID);
3748
3749 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
3750
3751 /// Retrieves the canonical declaration of this declaration.
3752 UnresolvedUsingValueDecl *getCanonicalDecl() override {
3753 return getFirstDecl();
3754 }
3755 const UnresolvedUsingValueDecl *getCanonicalDecl() const {
3756 return getFirstDecl();
3757 }
3758
3759 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3760 static bool classofKind(Kind K) { return K == UnresolvedUsingValue; }
3761};
3762
3763/// Represents a dependent using declaration which was marked with
3764/// \c typename.
3765///
3766/// \code
3767/// template \<class T> class A : public Base<T> {
3768/// using typename Base<T>::foo;
3769/// };
3770/// \endcode
3771///
3772/// The type associated with an unresolved using typename decl is
3773/// currently always a typename type.
3774class UnresolvedUsingTypenameDecl
3775 : public TypeDecl,
3776 public Mergeable<UnresolvedUsingTypenameDecl> {
3777 friend class ASTDeclReader;
3778
3779 /// The source location of the 'typename' keyword
3780 SourceLocation TypenameLocation;
3781
3782 /// If this is a pack expansion, the location of the '...'.
3783 SourceLocation EllipsisLoc;
3784
3785 /// The nested-name-specifier that precedes the name.
3786 NestedNameSpecifierLoc QualifierLoc;
3787
3788 UnresolvedUsingTypenameDecl(DeclContext *DC, SourceLocation UsingLoc,
3789 SourceLocation TypenameLoc,
3790 NestedNameSpecifierLoc QualifierLoc,
3791 SourceLocation TargetNameLoc,
3792 IdentifierInfo *TargetName,
3793 SourceLocation EllipsisLoc)
3794 : TypeDecl(UnresolvedUsingTypename, DC, TargetNameLoc, TargetName,
3795 UsingLoc),
3796 TypenameLocation(TypenameLoc), EllipsisLoc(EllipsisLoc),
3797 QualifierLoc(QualifierLoc) {}
3798
3799 void anchor() override;
3800
3801public:
3802 /// Returns the source location of the 'using' keyword.
3803 SourceLocation getUsingLoc() const { return getBeginLoc(); }
3804
3805 /// Returns the source location of the 'typename' keyword.
3806 SourceLocation getTypenameLoc() const { return TypenameLocation; }
3807
3808 /// Retrieve the nested-name-specifier that qualifies the name,
3809 /// with source-location information.
3810 NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; }
3811
3812 /// Retrieve the nested-name-specifier that qualifies the name.
3813 NestedNameSpecifier *getQualifier() const {
3814 return QualifierLoc.getNestedNameSpecifier();
3815 }
3816
3817 DeclarationNameInfo getNameInfo() const {
3818 return DeclarationNameInfo(getDeclName(), getLocation());
3819 }
3820
3821 /// Determine whether this is a pack expansion.
3822 bool isPackExpansion() const {
3823 return EllipsisLoc.isValid();
3824 }
3825
3826 /// Get the location of the ellipsis if this is a pack expansion.
3827 SourceLocation getEllipsisLoc() const {
3828 return EllipsisLoc;
3829 }
3830
3831 static UnresolvedUsingTypenameDecl *
3832 Create(ASTContext &C, DeclContext *DC, SourceLocation UsingLoc,
3833 SourceLocation TypenameLoc, NestedNameSpecifierLoc QualifierLoc,
3834 SourceLocation TargetNameLoc, DeclarationName TargetName,
3835 SourceLocation EllipsisLoc);
3836
3837 static UnresolvedUsingTypenameDecl *
3838 CreateDeserialized(ASTContext &C, unsigned ID);
3839
3840 /// Retrieves the canonical declaration of this declaration.
3841 UnresolvedUsingTypenameDecl *getCanonicalDecl() override {
3842 return getFirstDecl();
3843 }
3844 const UnresolvedUsingTypenameDecl *getCanonicalDecl() const {
3845 return getFirstDecl();
3846 }
3847
3848 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3849 static bool classofKind(Kind K) { return K == UnresolvedUsingTypename; }
3850};
3851
3852/// Represents a C++11 static_assert declaration.
3853class StaticAssertDecl : public Decl {
3854 llvm::PointerIntPair<Expr *, 1, bool> AssertExprAndFailed;
3855 StringLiteral *Message;
3856 SourceLocation RParenLoc;
3857
3858 StaticAssertDecl(DeclContext *DC, SourceLocation StaticAssertLoc,
3859 Expr *AssertExpr, StringLiteral *Message,
3860 SourceLocation RParenLoc, bool Failed)
3861 : Decl(StaticAssert, DC, StaticAssertLoc),
3862 AssertExprAndFailed(AssertExpr, Failed), Message(Message),
3863 RParenLoc(RParenLoc) {}
3864
3865 virtual void anchor();
3866
3867public:
3868 friend class ASTDeclReader;
3869
3870 static StaticAssertDecl *Create(ASTContext &C, DeclContext *DC,
3871 SourceLocation StaticAssertLoc,
3872 Expr *AssertExpr, StringLiteral *Message,
3873 SourceLocation RParenLoc, bool Failed);
3874 static StaticAssertDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3875
3876 Expr *getAssertExpr() { return AssertExprAndFailed.getPointer(); }
3877 const Expr *getAssertExpr() const { return AssertExprAndFailed.getPointer(); }
3878
3879 StringLiteral *getMessage() { return Message; }
3880 const StringLiteral *getMessage() const { return Message; }
3881
3882 bool isFailed() const { return AssertExprAndFailed.getInt(); }
3883
3884 SourceLocation getRParenLoc() const { return RParenLoc; }
3885
3886 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
3887 return SourceRange(getLocation(), getRParenLoc());
3888 }
3889
3890 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3891 static bool classofKind(Kind K) { return K == StaticAssert; }
3892};
3893
3894/// A binding in a decomposition declaration. For instance, given:
3895///
3896/// int n[3];
3897/// auto &[a, b, c] = n;
3898///
3899/// a, b, and c are BindingDecls, whose bindings are the expressions
3900/// x[0], x[1], and x[2] respectively, where x is the implicit
3901/// DecompositionDecl of type 'int (&)[3]'.
3902class BindingDecl : public ValueDecl {
3903 /// The declaration that this binding binds to part of.
3904 LazyDeclPtr Decomp;
3905 /// The binding represented by this declaration. References to this
3906 /// declaration are effectively equivalent to this expression (except
3907 /// that it is only evaluated once at the point of declaration of the
3908 /// binding).
3909 Expr *Binding = nullptr;
3910
3911 BindingDecl(DeclContext *DC, SourceLocation IdLoc, IdentifierInfo *Id)
3912 : ValueDecl(Decl::Binding, DC, IdLoc, Id, QualType()) {}
3913
3914 void anchor() override;
3915
3916public:
3917 friend class ASTDeclReader;
3918
3919 static BindingDecl *Create(ASTContext &C, DeclContext *DC,
3920 SourceLocation IdLoc, IdentifierInfo *Id);
3921 static BindingDecl *CreateDeserialized(ASTContext &C, unsigned ID);
3922
3923 /// Get the expression to which this declaration is bound. This may be null
3924 /// in two different cases: while parsing the initializer for the
3925 /// decomposition declaration, and when the initializer is type-dependent.
3926 Expr *getBinding() const { return Binding; }
3927
3928 /// Get the decomposition declaration that this binding represents a
3929 /// decomposition of.
3930 ValueDecl *getDecomposedDecl() const;
3931
3932 /// Get the variable (if any) that holds the value of evaluating the binding.
3933 /// Only present for user-defined bindings for tuple-like types.
3934 VarDecl *getHoldingVar() const;
3935
3936 /// Set the binding for this BindingDecl, along with its declared type (which
3937 /// should be a possibly-cv-qualified form of the type of the binding, or a
3938 /// reference to such a type).
3939 void setBinding(QualType DeclaredType, Expr *Binding) {
3940 setType(DeclaredType);
3941 this->Binding = Binding;
3942 }
3943
3944 /// Set the decomposed variable for this BindingDecl.
3945 void setDecomposedDecl(ValueDecl *Decomposed) { Decomp = Decomposed; }
3946
3947 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3948 static bool classofKind(Kind K) { return K == Decl::Binding; }
3949};
3950
3951/// A decomposition declaration. For instance, given:
3952///
3953/// int n[3];
3954/// auto &[a, b, c] = n;
3955///
3956/// the second line declares a DecompositionDecl of type 'int (&)[3]', and
3957/// three BindingDecls (named a, b, and c). An instance of this class is always
3958/// unnamed, but behaves in almost all other respects like a VarDecl.
3959class DecompositionDecl final
3960 : public VarDecl,
3961 private llvm::TrailingObjects<DecompositionDecl, BindingDecl *> {
3962 /// The number of BindingDecl*s following this object.
3963 unsigned NumBindings;
3964
3965 DecompositionDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
3966 SourceLocation LSquareLoc, QualType T,
3967 TypeSourceInfo *TInfo, StorageClass SC,
3968 ArrayRef<BindingDecl *> Bindings)
3969 : VarDecl(Decomposition, C, DC, StartLoc, LSquareLoc, nullptr, T, TInfo,
3970 SC),
3971 NumBindings(Bindings.size()) {
3972 std::uninitialized_copy(Bindings.begin(), Bindings.end(),
3973 getTrailingObjects<BindingDecl *>());
3974 for (auto *B : Bindings)
3975 B->setDecomposedDecl(this);
3976 }
3977
3978 void anchor() override;
3979
3980public:
3981 friend class ASTDeclReader;
3982 friend TrailingObjects;
3983
3984 static DecompositionDecl *Create(ASTContext &C, DeclContext *DC,
3985 SourceLocation StartLoc,
3986 SourceLocation LSquareLoc,
3987 QualType T, TypeSourceInfo *TInfo,
3988 StorageClass S,
3989 ArrayRef<BindingDecl *> Bindings);
3990 static DecompositionDecl *CreateDeserialized(ASTContext &C, unsigned ID,
3991 unsigned NumBindings);
3992
3993 ArrayRef<BindingDecl *> bindings() const {
3994 return llvm::makeArrayRef(getTrailingObjects<BindingDecl *>(), NumBindings);
3995 }
3996
3997 void printName(raw_ostream &os) const override;
3998
3999 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
4000 static bool classofKind(Kind K) { return K == Decomposition; }
4001};
4002
4003/// An instance of this class represents the declaration of a property
4004/// member. This is a Microsoft extension to C++, first introduced in
4005/// Visual Studio .NET 2003 as a parallel to similar features in C#
4006/// and Managed C++.
4007///
4008/// A property must always be a non-static class member.
4009///
4010/// A property member superficially resembles a non-static data
4011/// member, except preceded by a property attribute:
4012/// __declspec(property(get=GetX, put=PutX)) int x;
4013/// Either (but not both) of the 'get' and 'put' names may be omitted.
4014///
4015/// A reference to a property is always an lvalue. If the lvalue
4016/// undergoes lvalue-to-rvalue conversion, then a getter name is
4017/// required, and that member is called with no arguments.
4018/// If the lvalue is assigned into, then a setter name is required,
4019/// and that member is called with one argument, the value assigned.
4020/// Both operations are potentially overloaded. Compound assignments
4021/// are permitted, as are the increment and decrement operators.
4022///
4023/// The getter and putter methods are permitted to be overloaded,
4024/// although their return and parameter types are subject to certain
4025/// restrictions according to the type of the property.
4026///
4027/// A property declared using an incomplete array type may
4028/// additionally be subscripted, adding extra parameters to the getter
4029/// and putter methods.
4030class MSPropertyDecl : public DeclaratorDecl {
4031 IdentifierInfo *GetterId, *SetterId;
4032
4033 MSPropertyDecl(DeclContext *DC, SourceLocation L, DeclarationName N,
4034 QualType T, TypeSourceInfo *TInfo, SourceLocation StartL,
4035 IdentifierInfo *Getter, IdentifierInfo *Setter)
4036 : DeclaratorDecl(MSProperty, DC, L, N, T, TInfo, StartL),
4037 GetterId(Getter), SetterId(Setter) {}
4038
4039 void anchor() override;
4040public:
4041 friend class ASTDeclReader;
4042
4043 static MSPropertyDecl *Create(ASTContext &C, DeclContext *DC,
4044 SourceLocation L, DeclarationName N, QualType T,
4045 TypeSourceInfo *TInfo, SourceLocation StartL,
4046 IdentifierInfo *Getter, IdentifierInfo *Setter);
4047 static MSPropertyDecl *CreateDeserialized(ASTContext &C, unsigned ID);
4048
4049 static bool classof(const Decl *D) { return D->getKind() == MSProperty; }
4050
4051 bool hasGetter() const { return GetterId != nullptr; }
4052 IdentifierInfo* getGetterId() const { return GetterId; }
4053 bool hasSetter() const { return SetterId != nullptr; }
4054 IdentifierInfo* getSetterId() const { return SetterId; }
4055};
4056
4057/// Insertion operator for diagnostics. This allows sending an AccessSpecifier
4058/// into a diagnostic with <<.
4059const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
4060 AccessSpecifier AS);
4061
4062const PartialDiagnostic &operator<<(const PartialDiagnostic &DB,
4063 AccessSpecifier AS);
4064
4065} // namespace clang
4066
4067#endif // LLVM_CLANG_AST_DECLCXX_H