Bug Summary

File:build/source/clang/include/clang/AST/ExprCXX.h
Warning:line 4929, column 18
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaCoroutine.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/Sema/SemaCoroutine.cpp

/build/source/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/Basic/Builtins.h"
22#include "clang/Lex/Preprocessor.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Overload.h"
25#include "clang/Sema/ScopeInfo.h"
26#include "clang/Sema/SemaInternal.h"
27#include "llvm/ADT/SmallSet.h"
28
29using namespace clang;
30using namespace sema;
31
32static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
33 SourceLocation Loc, bool &Res) {
34 DeclarationName DN = S.PP.getIdentifierInfo(Name);
35 LookupResult LR(S, DN, Loc, Sema::LookupMemberName);
36 // Suppress diagnostics when a private member is selected. The same warnings
37 // will be produced again when building the call.
38 LR.suppressDiagnostics();
39 Res = S.LookupQualifiedName(LR, RD);
40 return LR;
41}
42
43static bool lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
44 SourceLocation Loc) {
45 bool Res;
46 lookupMember(S, Name, RD, Loc, Res);
47 return Res;
48}
49
50/// Look up the std::coroutine_traits<...>::promise_type for the given
51/// function type.
52static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD,
53 SourceLocation KwLoc) {
54 const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
55 const SourceLocation FuncLoc = FD->getLocation();
56
57 ClassTemplateDecl *CoroTraits =
58 S.lookupCoroutineTraits(KwLoc, FuncLoc);
59 if (!CoroTraits)
60 return QualType();
61
62 // Form template argument list for coroutine_traits<R, P1, P2, ...> according
63 // to [dcl.fct.def.coroutine]3
64 TemplateArgumentListInfo Args(KwLoc, KwLoc);
65 auto AddArg = [&](QualType T) {
66 Args.addArgument(TemplateArgumentLoc(
67 TemplateArgument(T), S.Context.getTrivialTypeSourceInfo(T, KwLoc)));
68 };
69 AddArg(FnType->getReturnType());
70 // If the function is a non-static member function, add the type
71 // of the implicit object parameter before the formal parameters.
72 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
73 if (MD->isInstance()) {
74 // [over.match.funcs]4
75 // For non-static member functions, the type of the implicit object
76 // parameter is
77 // -- "lvalue reference to cv X" for functions declared without a
78 // ref-qualifier or with the & ref-qualifier
79 // -- "rvalue reference to cv X" for functions declared with the &&
80 // ref-qualifier
81 QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType();
82 T = FnType->getRefQualifier() == RQ_RValue
83 ? S.Context.getRValueReferenceType(T)
84 : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
85 AddArg(T);
86 }
87 }
88 for (QualType T : FnType->getParamTypes())
89 AddArg(T);
90
91 // Build the template-id.
92 QualType CoroTrait =
93 S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
94 if (CoroTrait.isNull())
95 return QualType();
96 if (S.RequireCompleteType(KwLoc, CoroTrait,
97 diag::err_coroutine_type_missing_specialization))
98 return QualType();
99
100 auto *RD = CoroTrait->getAsCXXRecordDecl();
101 assert(RD && "specialization of class template is not a class?")(static_cast <bool> (RD && "specialization of class template is not a class?"
) ? void (0) : __assert_fail ("RD && \"specialization of class template is not a class?\""
, "clang/lib/Sema/SemaCoroutine.cpp", 101, __extension__ __PRETTY_FUNCTION__
))
;
102
103 // Look up the ::promise_type member.
104 LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
105 Sema::LookupOrdinaryName);
106 S.LookupQualifiedName(R, RD);
107 auto *Promise = R.getAsSingle<TypeDecl>();
108 if (!Promise) {
109 S.Diag(FuncLoc,
110 diag::err_implied_std_coroutine_traits_promise_type_not_found)
111 << RD;
112 return QualType();
113 }
114 // The promise type is required to be a class type.
115 QualType PromiseType = S.Context.getTypeDeclType(Promise);
116
117 auto buildElaboratedType = [&]() {
118 auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, S.getStdNamespace());
119 NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
120 CoroTrait.getTypePtr());
121 return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
122 };
123
124 if (!PromiseType->getAsCXXRecordDecl()) {
125 S.Diag(FuncLoc,
126 diag::err_implied_std_coroutine_traits_promise_type_not_class)
127 << buildElaboratedType();
128 return QualType();
129 }
130 if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
131 diag::err_coroutine_promise_type_incomplete))
132 return QualType();
133
134 return PromiseType;
135}
136
137/// Look up the std::coroutine_handle<PromiseType>.
138static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType,
139 SourceLocation Loc) {
140 if (PromiseType.isNull())
141 return QualType();
142
143 NamespaceDecl *CoroNamespace = S.getStdNamespace();
144 assert(CoroNamespace && "Should already be diagnosed")(static_cast <bool> (CoroNamespace && "Should already be diagnosed"
) ? void (0) : __assert_fail ("CoroNamespace && \"Should already be diagnosed\""
, "clang/lib/Sema/SemaCoroutine.cpp", 144, __extension__ __PRETTY_FUNCTION__
))
;
145
146 LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
147 Loc, Sema::LookupOrdinaryName);
148 if (!S.LookupQualifiedName(Result, CoroNamespace)) {
149 S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
150 << "std::coroutine_handle";
151 return QualType();
152 }
153
154 ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
155 if (!CoroHandle) {
156 Result.suppressDiagnostics();
157 // We found something weird. Complain about the first thing we found.
158 NamedDecl *Found = *Result.begin();
159 S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
160 return QualType();
161 }
162
163 // Form template argument list for coroutine_handle<Promise>.
164 TemplateArgumentListInfo Args(Loc, Loc);
165 Args.addArgument(TemplateArgumentLoc(
166 TemplateArgument(PromiseType),
167 S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
168
169 // Build the template-id.
170 QualType CoroHandleType =
171 S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
172 if (CoroHandleType.isNull())
173 return QualType();
174 if (S.RequireCompleteType(Loc, CoroHandleType,
175 diag::err_coroutine_type_missing_specialization))
176 return QualType();
177
178 return CoroHandleType;
179}
180
181static bool isValidCoroutineContext(Sema &S, SourceLocation Loc,
182 StringRef Keyword) {
183 // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
184 // a function body.
185 // FIXME: This also covers [expr.await]p2: "An await-expression shall not
186 // appear in a default argument." But the diagnostic QoI here could be
187 // improved to inform the user that default arguments specifically are not
188 // allowed.
189 auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
190 if (!FD) {
191 S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
192 ? diag::err_coroutine_objc_method
193 : diag::err_coroutine_outside_function) << Keyword;
194 return false;
195 }
196
197 // An enumeration for mapping the diagnostic type to the correct diagnostic
198 // selection index.
199 enum InvalidFuncDiag {
200 DiagCtor = 0,
201 DiagDtor,
202 DiagMain,
203 DiagConstexpr,
204 DiagAutoRet,
205 DiagVarargs,
206 DiagConsteval,
207 };
208 bool Diagnosed = false;
209 auto DiagInvalid = [&](InvalidFuncDiag ID) {
210 S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
211 Diagnosed = true;
212 return false;
213 };
214
215 // Diagnose when a constructor, destructor
216 // or the function 'main' are declared as a coroutine.
217 auto *MD = dyn_cast<CXXMethodDecl>(FD);
218 // [class.ctor]p11: "A constructor shall not be a coroutine."
219 if (MD && isa<CXXConstructorDecl>(MD))
220 return DiagInvalid(DiagCtor);
221 // [class.dtor]p17: "A destructor shall not be a coroutine."
222 else if (MD && isa<CXXDestructorDecl>(MD))
223 return DiagInvalid(DiagDtor);
224 // [basic.start.main]p3: "The function main shall not be a coroutine."
225 else if (FD->isMain())
226 return DiagInvalid(DiagMain);
227
228 // Emit a diagnostics for each of the following conditions which is not met.
229 // [expr.const]p2: "An expression e is a core constant expression unless the
230 // evaluation of e [...] would evaluate one of the following expressions:
231 // [...] an await-expression [...] a yield-expression."
232 if (FD->isConstexpr())
233 DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
234 // [dcl.spec.auto]p15: "A function declared with a return type that uses a
235 // placeholder type shall not be a coroutine."
236 if (FD->getReturnType()->isUndeducedType())
237 DiagInvalid(DiagAutoRet);
238 // [dcl.fct.def.coroutine]p1
239 // The parameter-declaration-clause of the coroutine shall not terminate with
240 // an ellipsis that is not part of a parameter-declaration.
241 if (FD->isVariadic())
242 DiagInvalid(DiagVarargs);
243
244 return !Diagnosed;
245}
246
247/// Build a call to 'operator co_await' if there is a suitable operator for
248/// the given expression.
249ExprResult Sema::BuildOperatorCoawaitCall(SourceLocation Loc, Expr *E,
250 UnresolvedLookupExpr *Lookup) {
251 UnresolvedSet<16> Functions;
252 Functions.append(Lookup->decls_begin(), Lookup->decls_end());
253 return CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
254}
255
256static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, Scope *S,
257 SourceLocation Loc, Expr *E) {
258 ExprResult R = SemaRef.BuildOperatorCoawaitLookupExpr(S, Loc);
259 if (R.isInvalid())
260 return ExprError();
261 return SemaRef.BuildOperatorCoawaitCall(Loc, E,
262 cast<UnresolvedLookupExpr>(R.get()));
263}
264
265static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType,
266 SourceLocation Loc) {
267 QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
268 if (CoroHandleType.isNull())
269 return ExprError();
270
271 DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
272 LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
273 Sema::LookupOrdinaryName);
274 if (!S.LookupQualifiedName(Found, LookupCtx)) {
275 S.Diag(Loc, diag::err_coroutine_handle_missing_member)
276 << "from_address";
277 return ExprError();
278 }
279
280 Expr *FramePtr =
281 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
282
283 CXXScopeSpec SS;
284 ExprResult FromAddr =
285 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
286 if (FromAddr.isInvalid())
287 return ExprError();
288
289 return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
290}
291
292struct ReadySuspendResumeResult {
293 enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
294 Expr *Results[3];
295 OpaqueValueExpr *OpaqueValue;
296 bool IsInvalid;
297};
298
299static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc,
300 StringRef Name, MultiExprArg Args) {
301 DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
302
303 // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
304 CXXScopeSpec SS;
305 ExprResult Result = S.BuildMemberReferenceExpr(
306 Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
307 SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
308 /*Scope=*/nullptr);
309 if (Result.isInvalid())
310 return ExprError();
311
312 // We meant exactly what we asked for. No need for typo correction.
313 if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
314 S.clearDelayedTypo(TE);
315 S.Diag(Loc, diag::err_no_member)
316 << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
317 << Base->getSourceRange();
318 return ExprError();
319 }
320
321 return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
322}
323
324// See if return type is coroutine-handle and if so, invoke builtin coro-resume
325// on its address. This is to enable the support for coroutine-handle
326// returning await_suspend that results in a guaranteed tail call to the target
327// coroutine.
328static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
329 SourceLocation Loc) {
330 if (RetType->isReferenceType())
331 return nullptr;
332 Type const *T = RetType.getTypePtr();
333 if (!T->isClassType() && !T->isStructureType())
334 return nullptr;
335
336 // FIXME: Add convertability check to coroutine_handle<>. Possibly via
337 // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
338 // a private function in SemaExprCXX.cpp
339
340 ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", std::nullopt);
341 if (AddressExpr.isInvalid())
342 return nullptr;
343
344 Expr *JustAddress = AddressExpr.get();
345
346 // Check that the type of AddressExpr is void*
347 if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
348 S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
349 diag::warn_coroutine_handle_address_invalid_return_type)
350 << JustAddress->getType();
351
352 // Clean up temporary objects so that they don't live across suspension points
353 // unnecessarily. We choose to clean up before the call to
354 // __builtin_coro_resume so that the cleanup code are not inserted in-between
355 // the resume call and return instruction, which would interfere with the
356 // musttail call contract.
357 JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
358 return S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_resume,
359 JustAddress);
360}
361
362/// Build calls to await_ready, await_suspend, and await_resume for a co_await
363/// expression.
364/// The generated AST tries to clean up temporary objects as early as
365/// possible so that they don't live across suspension points if possible.
366/// Having temporary objects living across suspension points unnecessarily can
367/// lead to large frame size, and also lead to memory corruptions if the
368/// coroutine frame is destroyed after coming back from suspension. This is done
369/// by wrapping both the await_ready call and the await_suspend call with
370/// ExprWithCleanups. In the end of this function, we also need to explicitly
371/// set cleanup state so that the CoawaitExpr is also wrapped with an
372/// ExprWithCleanups to clean up the awaiter associated with the co_await
373/// expression.
374static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise,
375 SourceLocation Loc, Expr *E) {
376 OpaqueValueExpr *Operand = new (S.Context)
377 OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
378
379 // Assume valid until we see otherwise.
380 // Further operations are responsible for setting IsInalid to true.
381 ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
31
'Calls.IsInvalid' initialized to 0, which participates in a condition later
32
Initializing to a null pointer value
33
'Calls' initialized here
382
383 using ACT = ReadySuspendResumeResult::AwaitCallType;
384
385 auto BuildSubExpr = [&](ACT CallType, StringRef Func,
386 MultiExprArg Arg) -> Expr * {
387 ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
388 if (Result.isInvalid()) {
389 Calls.IsInvalid = true;
390 return nullptr;
391 }
392 Calls.Results[CallType] = Result.get();
393 return Result.get();
394 };
395
396 CallExpr *AwaitReady = cast_or_null<CallExpr>(
34
Assuming null pointer is passed into cast
397 BuildSubExpr(ACT::ACT_Ready, "await_ready", std::nullopt));
398 if (!AwaitReady
34.1
'AwaitReady' is null
34.1
'AwaitReady' is null
34.1
'AwaitReady' is null
)
35
Taking true branch
399 return Calls;
36
The value 0 is assigned to 'RSS.IsInvalid', which participates in a condition later
37
Storing null pointer value
400 if (!AwaitReady->getType()->isDependentType()) {
401 // [expr.await]p3 [...]
402 // — await-ready is the expression e.await_ready(), contextually converted
403 // to bool.
404 ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
405 if (Conv.isInvalid()) {
406 S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
407 diag::note_await_ready_no_bool_conversion);
408 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
409 << AwaitReady->getDirectCallee() << E->getSourceRange();
410 Calls.IsInvalid = true;
411 } else
412 Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
413 }
414
415 ExprResult CoroHandleRes =
416 buildCoroutineHandle(S, CoroPromise->getType(), Loc);
417 if (CoroHandleRes.isInvalid()) {
418 Calls.IsInvalid = true;
419 return Calls;
420 }
421 Expr *CoroHandle = CoroHandleRes.get();
422 CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
423 BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
424 if (!AwaitSuspend)
425 return Calls;
426 if (!AwaitSuspend->getType()->isDependentType()) {
427 // [expr.await]p3 [...]
428 // - await-suspend is the expression e.await_suspend(h), which shall be
429 // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
430 // type Z.
431 QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
432
433 // Support for coroutine_handle returning await_suspend.
434 if (Expr *TailCallSuspend =
435 maybeTailCall(S, RetType, AwaitSuspend, Loc))
436 // Note that we don't wrap the expression with ExprWithCleanups here
437 // because that might interfere with tailcall contract (e.g. inserting
438 // clean up instructions in-between tailcall and return). Instead
439 // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
440 // call.
441 Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
442 else {
443 // non-class prvalues always have cv-unqualified types
444 if (RetType->isReferenceType() ||
445 (!RetType->isBooleanType() && !RetType->isVoidType())) {
446 S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
447 diag::err_await_suspend_invalid_return_type)
448 << RetType;
449 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
450 << AwaitSuspend->getDirectCallee();
451 Calls.IsInvalid = true;
452 } else
453 Calls.Results[ACT::ACT_Suspend] =
454 S.MaybeCreateExprWithCleanups(AwaitSuspend);
455 }
456 }
457
458 BuildSubExpr(ACT::ACT_Resume, "await_resume", std::nullopt);
459
460 // Make sure the awaiter object gets a chance to be cleaned up.
461 S.Cleanup.setExprNeedsCleanups(true);
462
463 return Calls;
464}
465
466static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise,
467 SourceLocation Loc, StringRef Name,
468 MultiExprArg Args) {
469
470 // Form a reference to the promise.
471 ExprResult PromiseRef = S.BuildDeclRefExpr(
472 Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
473 if (PromiseRef.isInvalid())
474 return ExprError();
475
476 return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
477}
478
479VarDecl *Sema::buildCoroutinePromise(SourceLocation Loc) {
480 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "clang/lib/Sema/SemaCoroutine.cpp", 480, __extension__ __PRETTY_FUNCTION__
))
;
481 auto *FD = cast<FunctionDecl>(CurContext);
482 bool IsThisDependentType = [&] {
483 if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
484 return MD->isInstance() && MD->getThisType()->isDependentType();
485 else
486 return false;
487 }();
488
489 QualType T = FD->getType()->isDependentType() || IsThisDependentType
490 ? Context.DependentTy
491 : lookupPromiseType(*this, FD, Loc);
492 if (T.isNull())
493 return nullptr;
494
495 auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
496 &PP.getIdentifierTable().get("__promise"), T,
497 Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
498 VD->setImplicit();
499 CheckVariableDeclarationType(VD);
500 if (VD->isInvalidDecl())
501 return nullptr;
502
503 auto *ScopeInfo = getCurFunction();
504
505 // Build a list of arguments, based on the coroutine function's arguments,
506 // that if present will be passed to the promise type's constructor.
507 llvm::SmallVector<Expr *, 4> CtorArgExprs;
508
509 // Add implicit object parameter.
510 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
511 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
512 ExprResult ThisExpr = ActOnCXXThis(Loc);
513 if (ThisExpr.isInvalid())
514 return nullptr;
515 ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
516 if (ThisExpr.isInvalid())
517 return nullptr;
518 CtorArgExprs.push_back(ThisExpr.get());
519 }
520 }
521
522 // Add the coroutine function's parameters.
523 auto &Moves = ScopeInfo->CoroutineParameterMoves;
524 for (auto *PD : FD->parameters()) {
525 if (PD->getType()->isDependentType())
526 continue;
527
528 auto RefExpr = ExprEmpty();
529 auto Move = Moves.find(PD);
530 assert(Move != Moves.end() &&(static_cast <bool> (Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? void (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "clang/lib/Sema/SemaCoroutine.cpp", 531, __extension__ __PRETTY_FUNCTION__
))
531 "Coroutine function parameter not inserted into move map")(static_cast <bool> (Move != Moves.end() && "Coroutine function parameter not inserted into move map"
) ? void (0) : __assert_fail ("Move != Moves.end() && \"Coroutine function parameter not inserted into move map\""
, "clang/lib/Sema/SemaCoroutine.cpp", 531, __extension__ __PRETTY_FUNCTION__
))
;
532 // If a reference to the function parameter exists in the coroutine
533 // frame, use that reference.
534 auto *MoveDecl =
535 cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
536 RefExpr =
537 BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
538 ExprValueKind::VK_LValue, FD->getLocation());
539 if (RefExpr.isInvalid())
540 return nullptr;
541 CtorArgExprs.push_back(RefExpr.get());
542 }
543
544 // If we have a non-zero number of constructor arguments, try to use them.
545 // Otherwise, fall back to the promise type's default constructor.
546 if (!CtorArgExprs.empty()) {
547 // Create an initialization sequence for the promise type using the
548 // constructor arguments, wrapped in a parenthesized list expression.
549 Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
550 CtorArgExprs, FD->getLocation());
551 InitializedEntity Entity = InitializedEntity::InitializeVariable(VD);
552 InitializationKind Kind = InitializationKind::CreateForInit(
553 VD->getLocation(), /*DirectInit=*/true, PLE);
554 InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
555 /*TopLevelOfInitList=*/false,
556 /*TreatUnavailableAsInvalid=*/false);
557
558 // [dcl.fct.def.coroutine]5.7
559 // promise-constructor-arguments is determined as follows: overload
560 // resolution is performed on a promise constructor call created by
561 // assembling an argument list q_1 ... q_n . If a viable constructor is
562 // found ([over.match.viable]), then promise-constructor-arguments is ( q_1
563 // , ..., q_n ), otherwise promise-constructor-arguments is empty.
564 if (InitSeq) {
565 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
566 if (Result.isInvalid()) {
567 VD->setInvalidDecl();
568 } else if (Result.get()) {
569 VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
570 VD->setInitStyle(VarDecl::CallInit);
571 CheckCompleteVariableDeclaration(VD);
572 }
573 } else
574 ActOnUninitializedDecl(VD);
575 } else
576 ActOnUninitializedDecl(VD);
577
578 FD->addDecl(VD);
579 return VD;
580}
581
582/// Check that this is a context in which a coroutine suspension can appear.
583static FunctionScopeInfo *checkCoroutineContext(Sema &S, SourceLocation Loc,
584 StringRef Keyword,
585 bool IsImplicit = false) {
586 if (!isValidCoroutineContext(S, Loc, Keyword))
587 return nullptr;
588
589 assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(S.CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(S.CurContext) && \"not in a function scope\""
, "clang/lib/Sema/SemaCoroutine.cpp", 589, __extension__ __PRETTY_FUNCTION__
))
;
9
Taking false branch
10
Field 'CurContext' is a 'FunctionDecl'
11
'?' condition is true
590
591 auto *ScopeInfo = S.getCurFunction();
12
Calling 'Sema::getCurFunction'
15
Returning from 'Sema::getCurFunction'
592 assert(ScopeInfo && "missing function scope for function")(static_cast <bool> (ScopeInfo && "missing function scope for function"
) ? void (0) : __assert_fail ("ScopeInfo && \"missing function scope for function\""
, "clang/lib/Sema/SemaCoroutine.cpp", 592, __extension__ __PRETTY_FUNCTION__
))
;
16
Assuming 'ScopeInfo' is non-null
17
'?' condition is true
593
594 if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
595 ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
596
597 if (ScopeInfo->CoroutinePromise)
18
Assuming field 'CoroutinePromise' is null
19
Taking false branch
598 return ScopeInfo;
599
600 if (!S.buildCoroutineParameterMoves(Loc))
20
Taking false branch
601 return nullptr;
602
603 ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
604 if (!ScopeInfo->CoroutinePromise)
21
Assuming field 'CoroutinePromise' is non-null
22
Taking false branch
605 return nullptr;
606
607 return ScopeInfo;
23
Returning pointer (loaded from 'ScopeInfo'), which participates in a condition later
608}
609
610/// Recursively check \p E and all its children to see if any call target
611/// (including constructor call) is declared noexcept. Also any value returned
612/// from the call has a noexcept destructor.
613static void checkNoThrow(Sema &S, const Stmt *E,
614 llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
615 auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
616 // In the case of dtor, the call to dtor is implicit and hence we should
617 // pass nullptr to canCalleeThrow.
618 if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
619 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
620 // co_await promise.final_suspend() could end up calling
621 // __builtin_coro_resume for symmetric transfer if await_suspend()
622 // returns a handle. In that case, even __builtin_coro_resume is not
623 // declared as noexcept and may throw, it does not throw _into_ the
624 // coroutine that just suspended, but rather throws back out from
625 // whoever called coroutine_handle::resume(), hence we claim that
626 // logically it does not throw.
627 if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
628 return;
629 }
630 if (ThrowingDecls.empty()) {
631 // [dcl.fct.def.coroutine]p15
632 // The expression co_await promise.final_suspend() shall not be
633 // potentially-throwing ([except.spec]).
634 //
635 // First time seeing an error, emit the error message.
636 S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
637 diag::err_coroutine_promise_final_suspend_requires_nothrow);
638 }
639 ThrowingDecls.insert(D);
640 }
641 };
642
643 if (auto *CE = dyn_cast<CXXConstructExpr>(E)) {
644 CXXConstructorDecl *Ctor = CE->getConstructor();
645 checkDeclNoexcept(Ctor);
646 // Check the corresponding destructor of the constructor.
647 checkDeclNoexcept(Ctor->getParent()->getDestructor(), /*IsDtor=*/true);
648 } else if (auto *CE = dyn_cast<CallExpr>(E)) {
649 if (CE->isTypeDependent())
650 return;
651
652 checkDeclNoexcept(CE->getCalleeDecl());
653 QualType ReturnType = CE->getCallReturnType(S.getASTContext());
654 // Check the destructor of the call return type, if any.
655 if (ReturnType.isDestructedType() ==
656 QualType::DestructionKind::DK_cxx_destructor) {
657 const auto *T =
658 cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
659 checkDeclNoexcept(cast<CXXRecordDecl>(T->getDecl())->getDestructor(),
660 /*IsDtor=*/true);
661 }
662 } else
663 for (const auto *Child : E->children()) {
664 if (!Child)
665 continue;
666 checkNoThrow(S, Child, ThrowingDecls);
667 }
668}
669
670bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
671 llvm::SmallPtrSet<const Decl *, 4> ThrowingDecls;
672 // We first collect all declarations that should not throw but not declared
673 // with noexcept. We then sort them based on the location before printing.
674 // This is to avoid emitting the same note multiple times on the same
675 // declaration, and also provide a deterministic order for the messages.
676 checkNoThrow(*this, FinalSuspend, ThrowingDecls);
677 auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
678 ThrowingDecls.end()};
679 sort(SortedDecls, [](const Decl *A, const Decl *B) {
680 return A->getEndLoc() < B->getEndLoc();
681 });
682 for (const auto *D : SortedDecls) {
683 Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
684 }
685 return ThrowingDecls.empty();
686}
687
688bool Sema::ActOnCoroutineBodyStart(Scope *SC, SourceLocation KWLoc,
689 StringRef Keyword) {
690 if (!checkCoroutineContext(*this, KWLoc, Keyword))
691 return false;
692 auto *ScopeInfo = getCurFunction();
693 assert(ScopeInfo->CoroutinePromise)(static_cast <bool> (ScopeInfo->CoroutinePromise) ? void
(0) : __assert_fail ("ScopeInfo->CoroutinePromise", "clang/lib/Sema/SemaCoroutine.cpp"
, 693, __extension__ __PRETTY_FUNCTION__))
;
694
695 // If we have existing coroutine statements then we have already built
696 // the initial and final suspend points.
697 if (!ScopeInfo->NeedsCoroutineSuspends)
698 return true;
699
700 ScopeInfo->setNeedsCoroutineSuspends(false);
701
702 auto *Fn = cast<FunctionDecl>(CurContext);
703 SourceLocation Loc = Fn->getLocation();
704 // Build the initial suspend point
705 auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
706 ExprResult Operand = buildPromiseCall(*this, ScopeInfo->CoroutinePromise,
707 Loc, Name, std::nullopt);
708 if (Operand.isInvalid())
709 return StmtError();
710 ExprResult Suspend =
711 buildOperatorCoawaitCall(*this, SC, Loc, Operand.get());
712 if (Suspend.isInvalid())
713 return StmtError();
714 Suspend = BuildResolvedCoawaitExpr(Loc, Operand.get(), Suspend.get(),
715 /*IsImplicit*/ true);
716 Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
717 if (Suspend.isInvalid()) {
718 Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
719 << ((Name == "initial_suspend") ? 0 : 1);
720 Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
721 return StmtError();
722 }
723 return cast<Stmt>(Suspend.get());
724 };
725
726 StmtResult InitSuspend = buildSuspends("initial_suspend");
727 if (InitSuspend.isInvalid())
728 return true;
729
730 StmtResult FinalSuspend = buildSuspends("final_suspend");
731 if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
732 return true;
733
734 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
735
736 return true;
737}
738
739// Recursively walks up the scope hierarchy until either a 'catch' or a function
740// scope is found, whichever comes first.
741static bool isWithinCatchScope(Scope *S) {
742 // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
743 // lambdas that use 'co_await' are allowed. The loop below ends when a
744 // function scope is found in order to ensure the following behavior:
745 //
746 // void foo() { // <- function scope
747 // try { //
748 // co_await x; // <- 'co_await' is OK within a function scope
749 // } catch { // <- catch scope
750 // co_await x; // <- 'co_await' is not OK within a catch scope
751 // []() { // <- function scope
752 // co_await x; // <- 'co_await' is OK within a function scope
753 // }();
754 // }
755 // }
756 while (S && !S->isFunctionScope()) {
757 if (S->isCatchScope())
758 return true;
759 S = S->getParent();
760 }
761 return false;
762}
763
764// [expr.await]p2, emphasis added: "An await-expression shall appear only in
765// a *potentially evaluated* expression within the compound-statement of a
766// function-body *outside of a handler* [...] A context within a function
767// where an await-expression can appear is called a suspension context of the
768// function."
769static bool checkSuspensionContext(Sema &S, SourceLocation Loc,
770 StringRef Keyword) {
771 // First emphasis of [expr.await]p2: must be a potentially evaluated context.
772 // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
773 // \c sizeof.
774 if (S.isUnevaluatedContext()) {
775 S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
776 return false;
777 }
778
779 // Second emphasis of [expr.await]p2: must be outside of an exception handler.
780 if (isWithinCatchScope(S.getCurScope())) {
781 S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
782 return false;
783 }
784
785 return true;
786}
787
788ExprResult Sema::ActOnCoawaitExpr(Scope *S, SourceLocation Loc, Expr *E) {
789 if (!checkSuspensionContext(*this, Loc, "co_await"))
790 return ExprError();
791
792 if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
793 CorrectDelayedTyposInExpr(E);
794 return ExprError();
795 }
796
797 if (E->hasPlaceholderType()) {
798 ExprResult R = CheckPlaceholderExpr(E);
799 if (R.isInvalid()) return ExprError();
800 E = R.get();
801 }
802 ExprResult Lookup = BuildOperatorCoawaitLookupExpr(S, Loc);
803 if (Lookup.isInvalid())
804 return ExprError();
805 return BuildUnresolvedCoawaitExpr(Loc, E,
806 cast<UnresolvedLookupExpr>(Lookup.get()));
807}
808
809ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
810 DeclarationName OpName =
811 Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
812 LookupResult Operators(*this, OpName, SourceLocation(),
813 Sema::LookupOperatorName);
814 LookupName(Operators, S);
815
816 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous")(static_cast <bool> (!Operators.isAmbiguous() &&
"Operator lookup cannot be ambiguous") ? void (0) : __assert_fail
("!Operators.isAmbiguous() && \"Operator lookup cannot be ambiguous\""
, "clang/lib/Sema/SemaCoroutine.cpp", 816, __extension__ __PRETTY_FUNCTION__
))
;
817 const auto &Functions = Operators.asUnresolvedSet();
818 bool IsOverloaded =
819 Functions.size() > 1 ||
820 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
821 Expr *CoawaitOp = UnresolvedLookupExpr::Create(
822 Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
823 DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
824 Functions.begin(), Functions.end());
825 assert(CoawaitOp)(static_cast <bool> (CoawaitOp) ? void (0) : __assert_fail
("CoawaitOp", "clang/lib/Sema/SemaCoroutine.cpp", 825, __extension__
__PRETTY_FUNCTION__))
;
826 return CoawaitOp;
827}
828
829// Attempts to resolve and build a CoawaitExpr from "raw" inputs, bailing out to
830// DependentCoawaitExpr if needed.
831ExprResult Sema::BuildUnresolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
832 UnresolvedLookupExpr *Lookup) {
833 auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
834 if (!FSI)
835 return ExprError();
836
837 if (Operand->hasPlaceholderType()) {
838 ExprResult R = CheckPlaceholderExpr(Operand);
839 if (R.isInvalid())
840 return ExprError();
841 Operand = R.get();
842 }
843
844 auto *Promise = FSI->CoroutinePromise;
845 if (Promise->getType()->isDependentType()) {
846 Expr *Res = new (Context)
847 DependentCoawaitExpr(Loc, Context.DependentTy, Operand, Lookup);
848 return Res;
849 }
850
851 auto *RD = Promise->getType()->getAsCXXRecordDecl();
852 auto *Transformed = Operand;
853 if (lookupMember(*this, "await_transform", RD, Loc)) {
854 ExprResult R =
855 buildPromiseCall(*this, Promise, Loc, "await_transform", Operand);
856 if (R.isInvalid()) {
857 Diag(Loc,
858 diag::note_coroutine_promise_implicit_await_transform_required_here)
859 << Operand->getSourceRange();
860 return ExprError();
861 }
862 Transformed = R.get();
863 }
864 ExprResult Awaiter = BuildOperatorCoawaitCall(Loc, Transformed, Lookup);
865 if (Awaiter.isInvalid())
866 return ExprError();
867
868 return BuildResolvedCoawaitExpr(Loc, Operand, Awaiter.get());
869}
870
871ExprResult Sema::BuildResolvedCoawaitExpr(SourceLocation Loc, Expr *Operand,
872 Expr *Awaiter, bool IsImplicit) {
873 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
874 if (!Coroutine)
875 return ExprError();
876
877 if (Awaiter->hasPlaceholderType()) {
878 ExprResult R = CheckPlaceholderExpr(Awaiter);
879 if (R.isInvalid()) return ExprError();
880 Awaiter = R.get();
881 }
882
883 if (Awaiter->getType()->isDependentType()) {
884 Expr *Res = new (Context)
885 CoawaitExpr(Loc, Context.DependentTy, Operand, Awaiter, IsImplicit);
886 return Res;
887 }
888
889 // If the expression is a temporary, materialize it as an lvalue so that we
890 // can use it multiple times.
891 if (Awaiter->isPRValue())
892 Awaiter = CreateMaterializeTemporaryExpr(Awaiter->getType(), Awaiter, true);
893
894 // The location of the `co_await` token cannot be used when constructing
895 // the member call expressions since it's before the location of `Expr`, which
896 // is used as the start of the member call expression.
897 SourceLocation CallLoc = Awaiter->getExprLoc();
898
899 // Build the await_ready, await_suspend, await_resume calls.
900 ReadySuspendResumeResult RSS =
901 buildCoawaitCalls(*this, Coroutine->CoroutinePromise, CallLoc, Awaiter);
902 if (RSS.IsInvalid)
903 return ExprError();
904
905 Expr *Res = new (Context)
906 CoawaitExpr(Loc, Operand, Awaiter, RSS.Results[0], RSS.Results[1],
907 RSS.Results[2], RSS.OpaqueValue, IsImplicit);
908
909 return Res;
910}
911
912ExprResult Sema::ActOnCoyieldExpr(Scope *S, SourceLocation Loc, Expr *E) {
913 if (!checkSuspensionContext(*this, Loc, "co_yield"))
1
Taking false branch
914 return ExprError();
915
916 if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
2
Taking false branch
917 CorrectDelayedTyposInExpr(E);
918 return ExprError();
919 }
920
921 // Build yield_value call.
922 ExprResult Awaitable = buildPromiseCall(
923 *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
924 if (Awaitable.isInvalid())
3
Assuming the condition is false
4
Taking false branch
925 return ExprError();
926
927 // Build 'operator co_await' call.
928 Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
929 if (Awaitable.isInvalid())
5
Assuming the condition is false
6
Taking false branch
930 return ExprError();
931
932 return BuildCoyieldExpr(Loc, Awaitable.get());
7
Calling 'Sema::BuildCoyieldExpr'
933}
934ExprResult Sema::BuildCoyieldExpr(SourceLocation Loc, Expr *E) {
935 auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
8
Calling 'checkCoroutineContext'
24
Returning from 'checkCoroutineContext'
936 if (!Coroutine
24.1
'Coroutine' is non-null
24.1
'Coroutine' is non-null
24.1
'Coroutine' is non-null
)
25
Taking false branch
937 return ExprError();
938
939 if (E->hasPlaceholderType()) {
26
Taking false branch
940 ExprResult R = CheckPlaceholderExpr(E);
941 if (R.isInvalid()) return ExprError();
942 E = R.get();
943 }
944
945 Expr *Operand = E;
946
947 if (E->getType()->isDependentType()) {
27
Assuming the condition is false
28
Taking false branch
948 Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, Operand, E);
949 return Res;
950 }
951
952 // If the expression is a temporary, materialize it as an lvalue so that we
953 // can use it multiple times.
954 if (E->isPRValue())
29
Taking false branch
955 E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
956
957 // Build the await_ready, await_suspend, await_resume calls.
958 ReadySuspendResumeResult RSS = buildCoawaitCalls(
30
Calling 'buildCoawaitCalls'
38
Returning from 'buildCoawaitCalls'
959 *this, Coroutine->CoroutinePromise, Loc, E);
960 if (RSS.IsInvalid
38.1
Field 'IsInvalid' is false
38.1
Field 'IsInvalid' is false
38.1
Field 'IsInvalid' is false
)
39
Taking false branch
961 return ExprError();
962
963 Expr *Res =
964 new (Context) CoyieldExpr(Loc, Operand, E, RSS.Results[0], RSS.Results[1],
41
Calling constructor for 'CoyieldExpr'
965 RSS.Results[2], RSS.OpaqueValue);
40
Passing null pointer value via 6th parameter 'Resume'
966
967 return Res;
968}
969
970StmtResult Sema::ActOnCoreturnStmt(Scope *S, SourceLocation Loc, Expr *E) {
971 if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
972 CorrectDelayedTyposInExpr(E);
973 return StmtError();
974 }
975 return BuildCoreturnStmt(Loc, E);
976}
977
978StmtResult Sema::BuildCoreturnStmt(SourceLocation Loc, Expr *E,
979 bool IsImplicit) {
980 auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
981 if (!FSI)
982 return StmtError();
983
984 if (E && E->hasPlaceholderType() &&
985 !E->hasPlaceholderType(BuiltinType::Overload)) {
986 ExprResult R = CheckPlaceholderExpr(E);
987 if (R.isInvalid()) return StmtError();
988 E = R.get();
989 }
990
991 VarDecl *Promise = FSI->CoroutinePromise;
992 ExprResult PC;
993 if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
994 getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
995 PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
996 } else {
997 E = MakeFullDiscardedValueExpr(E).get();
998 PC = buildPromiseCall(*this, Promise, Loc, "return_void", std::nullopt);
999 }
1000 if (PC.isInvalid())
1001 return StmtError();
1002
1003 Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
1004
1005 Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
1006 return Res;
1007}
1008
1009/// Look up the std::nothrow object.
1010static Expr *buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc) {
1011 NamespaceDecl *Std = S.getStdNamespace();
1012 assert(Std && "Should already be diagnosed")(static_cast <bool> (Std && "Should already be diagnosed"
) ? void (0) : __assert_fail ("Std && \"Should already be diagnosed\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1012, __extension__ __PRETTY_FUNCTION__
))
;
1013
1014 LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
1015 Sema::LookupOrdinaryName);
1016 if (!S.LookupQualifiedName(Result, Std)) {
1017 // <coroutine> is not requred to include <new>, so we couldn't omit
1018 // the check here.
1019 S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
1020 return nullptr;
1021 }
1022
1023 auto *VD = Result.getAsSingle<VarDecl>();
1024 if (!VD) {
1025 Result.suppressDiagnostics();
1026 // We found something weird. Complain about the first thing we found.
1027 NamedDecl *Found = *Result.begin();
1028 S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
1029 return nullptr;
1030 }
1031
1032 ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
1033 if (DR.isInvalid())
1034 return nullptr;
1035
1036 return DR.get();
1037}
1038
1039static TypeSourceInfo *getTypeSourceInfoForStdAlignValT(Sema &S,
1040 SourceLocation Loc) {
1041 EnumDecl *StdAlignValT = S.getStdAlignValT();
1042 QualType StdAlignValDecl = S.Context.getTypeDeclType(StdAlignValT);
1043 return S.Context.getTrivialTypeSourceInfo(StdAlignValDecl);
1044}
1045
1046// Find an appropriate delete for the promise.
1047static bool findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType,
1048 FunctionDecl *&OperatorDelete) {
1049 DeclarationName DeleteName =
1050 S.Context.DeclarationNames.getCXXOperatorName(OO_Delete);
1051
1052 auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1053 assert(PointeeRD && "PromiseType must be a CxxRecordDecl type")(static_cast <bool> (PointeeRD && "PromiseType must be a CxxRecordDecl type"
) ? void (0) : __assert_fail ("PointeeRD && \"PromiseType must be a CxxRecordDecl type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1053, __extension__ __PRETTY_FUNCTION__
))
;
1054
1055 const bool Overaligned = S.getLangOpts().CoroAlignedAllocation;
1056
1057 // [dcl.fct.def.coroutine]p12
1058 // The deallocation function's name is looked up by searching for it in the
1059 // scope of the promise type. If nothing is found, a search is performed in
1060 // the global scope.
1061 if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete,
1062 /*Diagnose*/ true, /*WantSize*/ true,
1063 /*WantAligned*/ Overaligned))
1064 return false;
1065
1066 // [dcl.fct.def.coroutine]p12
1067 // If both a usual deallocation function with only a pointer parameter and a
1068 // usual deallocation function with both a pointer parameter and a size
1069 // parameter are found, then the selected deallocation function shall be the
1070 // one with two parameters. Otherwise, the selected deallocation function
1071 // shall be the function with one parameter.
1072 if (!OperatorDelete) {
1073 // Look for a global declaration.
1074 // Coroutines can always provide their required size.
1075 const bool CanProvideSize = true;
1076 // Sema::FindUsualDeallocationFunction will try to find the one with two
1077 // parameters first. It will return the deallocation function with one
1078 // parameter if failed.
1079 OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
1080 Overaligned, DeleteName);
1081
1082 if (!OperatorDelete)
1083 return false;
1084 }
1085
1086 S.MarkFunctionReferenced(Loc, OperatorDelete);
1087 return true;
1088}
1089
1090
1091void Sema::CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body) {
1092 FunctionScopeInfo *Fn = getCurFunction();
1093 assert(Fn && Fn->isCoroutine() && "not a coroutine")(static_cast <bool> (Fn && Fn->isCoroutine()
&& "not a coroutine") ? void (0) : __assert_fail ("Fn && Fn->isCoroutine() && \"not a coroutine\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1093, __extension__ __PRETTY_FUNCTION__
))
;
1094 if (!Body) {
1095 assert(FD->isInvalidDecl() &&(static_cast <bool> (FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? void (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1096, __extension__ __PRETTY_FUNCTION__
))
1096 "a null body is only allowed for invalid declarations")(static_cast <bool> (FD->isInvalidDecl() && "a null body is only allowed for invalid declarations"
) ? void (0) : __assert_fail ("FD->isInvalidDecl() && \"a null body is only allowed for invalid declarations\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1096, __extension__ __PRETTY_FUNCTION__
))
;
1097 return;
1098 }
1099 // We have a function that uses coroutine keywords, but we failed to build
1100 // the promise type.
1101 if (!Fn->CoroutinePromise)
1102 return FD->setInvalidDecl();
1103
1104 if (isa<CoroutineBodyStmt>(Body)) {
1105 // Nothing todo. the body is already a transformed coroutine body statement.
1106 return;
1107 }
1108
1109 // The always_inline attribute doesn't reliably apply to a coroutine,
1110 // because the coroutine will be split into pieces and some pieces
1111 // might be called indirectly, as in a virtual call. Even the ramp
1112 // function cannot be inlined at -O0, due to pipeline ordering
1113 // problems (see https://llvm.org/PR53413). Tell the user about it.
1114 if (FD->hasAttr<AlwaysInlineAttr>())
1115 Diag(FD->getLocation(), diag::warn_always_inline_coroutine);
1116
1117 // [stmt.return.coroutine]p1:
1118 // A coroutine shall not enclose a return statement ([stmt.return]).
1119 if (Fn->FirstReturnLoc.isValid()) {
1120 assert(Fn->FirstCoroutineStmtLoc.isValid() &&(static_cast <bool> (Fn->FirstCoroutineStmtLoc.isValid
() && "first coroutine location not set") ? void (0) :
__assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1121, __extension__ __PRETTY_FUNCTION__
))
1121 "first coroutine location not set")(static_cast <bool> (Fn->FirstCoroutineStmtLoc.isValid
() && "first coroutine location not set") ? void (0) :
__assert_fail ("Fn->FirstCoroutineStmtLoc.isValid() && \"first coroutine location not set\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1121, __extension__ __PRETTY_FUNCTION__
))
;
1122 Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
1123 Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1124 << Fn->getFirstCoroutineStmtKeyword();
1125 }
1126
1127 // Coroutines will get splitted into pieces. The GNU address of label
1128 // extension wouldn't be meaningful in coroutines.
1129 for (AddrLabelExpr *ALE : Fn->AddrLabels)
1130 Diag(ALE->getBeginLoc(), diag::err_coro_invalid_addr_of_label);
1131
1132 CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1133 if (Builder.isInvalid() || !Builder.buildStatements())
1134 return FD->setInvalidDecl();
1135
1136 // Build body for the coroutine wrapper statement.
1137 Body = CoroutineBodyStmt::Create(Context, Builder);
1138}
1139
1140static CompoundStmt *buildCoroutineBody(Stmt *Body, ASTContext &Context) {
1141 if (auto *CS = dyn_cast<CompoundStmt>(Body))
1142 return CS;
1143
1144 // The body of the coroutine may be a try statement if it is in
1145 // 'function-try-block' syntax. Here we wrap it into a compound
1146 // statement for consistency.
1147 assert(isa<CXXTryStmt>(Body) && "Unimaged coroutine body type")(static_cast <bool> (isa<CXXTryStmt>(Body) &&
"Unimaged coroutine body type") ? void (0) : __assert_fail (
"isa<CXXTryStmt>(Body) && \"Unimaged coroutine body type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1147, __extension__ __PRETTY_FUNCTION__
))
;
1148 return CompoundStmt::Create(Context, {Body}, FPOptionsOverride(),
1149 SourceLocation(), SourceLocation());
1150}
1151
1152CoroutineStmtBuilder::CoroutineStmtBuilder(Sema &S, FunctionDecl &FD,
1153 sema::FunctionScopeInfo &Fn,
1154 Stmt *Body)
1155 : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1156 IsPromiseDependentType(
1157 !Fn.CoroutinePromise ||
1158 Fn.CoroutinePromise->getType()->isDependentType()) {
1159 this->Body = buildCoroutineBody(Body, S.getASTContext());
1160
1161 for (auto KV : Fn.CoroutineParameterMoves)
1162 this->ParamMovesVector.push_back(KV.second);
1163 this->ParamMoves = this->ParamMovesVector;
1164
1165 if (!IsPromiseDependentType) {
1166 PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1167 assert(PromiseRecordDecl && "Type should have already been checked")(static_cast <bool> (PromiseRecordDecl && "Type should have already been checked"
) ? void (0) : __assert_fail ("PromiseRecordDecl && \"Type should have already been checked\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1167, __extension__ __PRETTY_FUNCTION__
))
;
1168 }
1169 this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1170}
1171
1172bool CoroutineStmtBuilder::buildStatements() {
1173 assert(this->IsValid && "coroutine already invalid")(static_cast <bool> (this->IsValid && "coroutine already invalid"
) ? void (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1173, __extension__ __PRETTY_FUNCTION__
))
;
1174 this->IsValid = makeReturnObject();
1175 if (this->IsValid && !IsPromiseDependentType)
1176 buildDependentStatements();
1177 return this->IsValid;
1178}
1179
1180bool CoroutineStmtBuilder::buildDependentStatements() {
1181 assert(this->IsValid && "coroutine already invalid")(static_cast <bool> (this->IsValid && "coroutine already invalid"
) ? void (0) : __assert_fail ("this->IsValid && \"coroutine already invalid\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1181, __extension__ __PRETTY_FUNCTION__
))
;
1182 assert(!this->IsPromiseDependentType &&(static_cast <bool> (!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type") ? void (0)
: __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1183, __extension__ __PRETTY_FUNCTION__
))
1183 "coroutine cannot have a dependent promise type")(static_cast <bool> (!this->IsPromiseDependentType &&
"coroutine cannot have a dependent promise type") ? void (0)
: __assert_fail ("!this->IsPromiseDependentType && \"coroutine cannot have a dependent promise type\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1183, __extension__ __PRETTY_FUNCTION__
))
;
1184 this->IsValid = makeOnException() && makeOnFallthrough() &&
1185 makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1186 makeNewAndDeleteExpr();
1187 return this->IsValid;
1188}
1189
1190bool CoroutineStmtBuilder::makePromiseStmt() {
1191 // Form a declaration statement for the promise declaration, so that AST
1192 // visitors can more easily find it.
1193 StmtResult PromiseStmt =
1194 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(Fn.CoroutinePromise), Loc, Loc);
1195 if (PromiseStmt.isInvalid())
1196 return false;
1197
1198 this->Promise = PromiseStmt.get();
1199 return true;
1200}
1201
1202bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1203 if (Fn.hasInvalidCoroutineSuspends())
1204 return false;
1205 this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1206 this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1207 return true;
1208}
1209
1210static bool diagReturnOnAllocFailure(Sema &S, Expr *E,
1211 CXXRecordDecl *PromiseRecordDecl,
1212 FunctionScopeInfo &Fn) {
1213 auto Loc = E->getExprLoc();
1214 if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1215 auto *Decl = DeclRef->getDecl();
1216 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1217 if (Method->isStatic())
1218 return true;
1219 else
1220 Loc = Decl->getLocation();
1221 }
1222 }
1223
1224 S.Diag(
1225 Loc,
1226 diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1227 << PromiseRecordDecl;
1228 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1229 << Fn.getFirstCoroutineStmtKeyword();
1230 return false;
1231}
1232
1233bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1234 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1235, __extension__ __PRETTY_FUNCTION__
))
1235 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1235, __extension__ __PRETTY_FUNCTION__
))
;
1236
1237 // [dcl.fct.def.coroutine]p10
1238 // If a search for the name get_return_object_on_allocation_failure in
1239 // the scope of the promise type ([class.member.lookup]) finds any
1240 // declarations, then the result of a call to an allocation function used to
1241 // obtain storage for the coroutine state is assumed to return nullptr if it
1242 // fails to obtain storage, ... If the allocation function returns nullptr,
1243 // ... and the return value is obtained by a call to
1244 // T::get_return_object_on_allocation_failure(), where T is the
1245 // promise type.
1246 DeclarationName DN =
1247 S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1248 LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1249 if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1250 return true;
1251
1252 CXXScopeSpec SS;
1253 ExprResult DeclNameExpr =
1254 S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1255 if (DeclNameExpr.isInvalid())
1256 return false;
1257
1258 if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1259 return false;
1260
1261 ExprResult ReturnObjectOnAllocationFailure =
1262 S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1263 if (ReturnObjectOnAllocationFailure.isInvalid())
1264 return false;
1265
1266 StmtResult ReturnStmt =
1267 S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1268 if (ReturnStmt.isInvalid()) {
1269 S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1270 << DN;
1271 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1272 << Fn.getFirstCoroutineStmtKeyword();
1273 return false;
1274 }
1275
1276 this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1277 return true;
1278}
1279
1280// Collect placement arguments for allocation function of coroutine FD.
1281// Return true if we collect placement arguments succesfully. Return false,
1282// otherwise.
1283static bool collectPlacementArgs(Sema &S, FunctionDecl &FD, SourceLocation Loc,
1284 SmallVectorImpl<Expr *> &PlacementArgs) {
1285 if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1286 if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1287 ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1288 if (ThisExpr.isInvalid())
1289 return false;
1290 ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1291 if (ThisExpr.isInvalid())
1292 return false;
1293 PlacementArgs.push_back(ThisExpr.get());
1294 }
1295 }
1296
1297 for (auto *PD : FD.parameters()) {
1298 if (PD->getType()->isDependentType())
1299 continue;
1300
1301 // Build a reference to the parameter.
1302 auto PDLoc = PD->getLocation();
1303 ExprResult PDRefExpr =
1304 S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1305 ExprValueKind::VK_LValue, PDLoc);
1306 if (PDRefExpr.isInvalid())
1307 return false;
1308
1309 PlacementArgs.push_back(PDRefExpr.get());
1310 }
1311
1312 return true;
1313}
1314
1315bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1316 // Form and check allocation and deallocation calls.
1317 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1318, __extension__ __PRETTY_FUNCTION__
))
1318 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1318, __extension__ __PRETTY_FUNCTION__
))
;
1319 QualType PromiseType = Fn.CoroutinePromise->getType();
1320
1321 if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1322 return false;
1323
1324 const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1325
1326 // According to [dcl.fct.def.coroutine]p9, Lookup allocation functions using a
1327 // parameter list composed of the requested size of the coroutine state being
1328 // allocated, followed by the coroutine function's arguments. If a matching
1329 // allocation function exists, use it. Otherwise, use an allocation function
1330 // that just takes the requested size.
1331 //
1332 // [dcl.fct.def.coroutine]p9
1333 // An implementation may need to allocate additional storage for a
1334 // coroutine.
1335 // This storage is known as the coroutine state and is obtained by calling a
1336 // non-array allocation function ([basic.stc.dynamic.allocation]). The
1337 // allocation function's name is looked up by searching for it in the scope of
1338 // the promise type.
1339 // - If any declarations are found, overload resolution is performed on a
1340 // function call created by assembling an argument list. The first argument is
1341 // the amount of space requested, and has type std::size_t. The
1342 // lvalues p1 ... pn are the succeeding arguments.
1343 //
1344 // ...where "p1 ... pn" are defined earlier as:
1345 //
1346 // [dcl.fct.def.coroutine]p3
1347 // The promise type of a coroutine is `std::coroutine_traits<R, P1, ...,
1348 // Pn>`
1349 // , where R is the return type of the function, and `P1, ..., Pn` are the
1350 // sequence of types of the non-object function parameters, preceded by the
1351 // type of the object parameter ([dcl.fct]) if the coroutine is a non-static
1352 // member function. [dcl.fct.def.coroutine]p4 In the following, p_i is an
1353 // lvalue of type P_i, where p1 denotes the object parameter and p_i+1 denotes
1354 // the i-th non-object function parameter for a non-static member function,
1355 // and p_i denotes the i-th function parameter otherwise. For a non-static
1356 // member function, q_1 is an lvalue that denotes *this; any other q_i is an
1357 // lvalue that denotes the parameter copy corresponding to p_i.
1358
1359 FunctionDecl *OperatorNew = nullptr;
1360 SmallVector<Expr *, 1> PlacementArgs;
1361
1362 const bool PromiseContainsNew = [this, &PromiseType]() -> bool {
1363 DeclarationName NewName =
1364 S.getASTContext().DeclarationNames.getCXXOperatorName(OO_New);
1365 LookupResult R(S, NewName, Loc, Sema::LookupOrdinaryName);
1366
1367 if (PromiseType->isRecordType())
1368 S.LookupQualifiedName(R, PromiseType->getAsCXXRecordDecl());
1369
1370 return !R.empty() && !R.isAmbiguous();
1371 }();
1372
1373 // Helper function to indicate whether the last lookup found the aligned
1374 // allocation function.
1375 bool PassAlignment = S.getLangOpts().CoroAlignedAllocation;
1376 auto LookupAllocationFunction = [&](Sema::AllocationFunctionScope NewScope =
1377 Sema::AFS_Both,
1378 bool WithoutPlacementArgs = false,
1379 bool ForceNonAligned = false) {
1380 // [dcl.fct.def.coroutine]p9
1381 // The allocation function's name is looked up by searching for it in the
1382 // scope of the promise type.
1383 // - If any declarations are found, ...
1384 // - If no declarations are found in the scope of the promise type, a search
1385 // is performed in the global scope.
1386 if (NewScope == Sema::AFS_Both)
1387 NewScope = PromiseContainsNew ? Sema::AFS_Class : Sema::AFS_Global;
1388
1389 PassAlignment = !ForceNonAligned && S.getLangOpts().CoroAlignedAllocation;
1390 FunctionDecl *UnusedResult = nullptr;
1391 S.FindAllocationFunctions(Loc, SourceRange(), NewScope,
1392 /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1393 /*isArray*/ false, PassAlignment,
1394 WithoutPlacementArgs ? MultiExprArg{}
1395 : PlacementArgs,
1396 OperatorNew, UnusedResult, /*Diagnose*/ false);
1397 };
1398
1399 // We don't expect to call to global operator new with (size, p0, …, pn).
1400 // So if we choose to lookup the allocation function in global scope, we
1401 // shouldn't lookup placement arguments.
1402 if (PromiseContainsNew && !collectPlacementArgs(S, FD, Loc, PlacementArgs))
1403 return false;
1404
1405 LookupAllocationFunction();
1406
1407 if (PromiseContainsNew && !PlacementArgs.empty()) {
1408 // [dcl.fct.def.coroutine]p9
1409 // If no viable function is found ([over.match.viable]), overload
1410 // resolution
1411 // is performed again on a function call created by passing just the amount
1412 // of space required as an argument of type std::size_t.
1413 //
1414 // Proposed Change of [dcl.fct.def.coroutine]p9 in P2014R0:
1415 // Otherwise, overload resolution is performed again on a function call
1416 // created
1417 // by passing the amount of space requested as an argument of type
1418 // std::size_t as the first argument, and the requested alignment as
1419 // an argument of type std:align_val_t as the second argument.
1420 if (!OperatorNew ||
1421 (S.getLangOpts().CoroAlignedAllocation && !PassAlignment))
1422 LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1423 /*WithoutPlacementArgs*/ true);
1424 }
1425
1426 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1427 // Otherwise, overload resolution is performed again on a function call
1428 // created
1429 // by passing the amount of space requested as an argument of type
1430 // std::size_t as the first argument, and the lvalues p1 ... pn as the
1431 // succeeding arguments. Otherwise, overload resolution is performed again
1432 // on a function call created by passing just the amount of space required as
1433 // an argument of type std::size_t.
1434 //
1435 // So within the proposed change in P2014RO, the priority order of aligned
1436 // allocation functions wiht promise_type is:
1437 //
1438 // void* operator new( std::size_t, std::align_val_t, placement_args... );
1439 // void* operator new( std::size_t, std::align_val_t);
1440 // void* operator new( std::size_t, placement_args... );
1441 // void* operator new( std::size_t);
1442
1443 // Helper variable to emit warnings.
1444 bool FoundNonAlignedInPromise = false;
1445 if (PromiseContainsNew && S.getLangOpts().CoroAlignedAllocation)
1446 if (!OperatorNew || !PassAlignment) {
1447 FoundNonAlignedInPromise = OperatorNew;
1448
1449 LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1450 /*WithoutPlacementArgs*/ false,
1451 /*ForceNonAligned*/ true);
1452
1453 if (!OperatorNew && !PlacementArgs.empty())
1454 LookupAllocationFunction(/*NewScope*/ Sema::AFS_Class,
1455 /*WithoutPlacementArgs*/ true,
1456 /*ForceNonAligned*/ true);
1457 }
1458
1459 bool IsGlobalOverload =
1460 OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1461 // If we didn't find a class-local new declaration and non-throwing new
1462 // was is required then we need to lookup the non-throwing global operator
1463 // instead.
1464 if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1465 auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1466 if (!StdNoThrow)
1467 return false;
1468 PlacementArgs = {StdNoThrow};
1469 OperatorNew = nullptr;
1470 LookupAllocationFunction(Sema::AFS_Global);
1471 }
1472
1473 // If we found a non-aligned allocation function in the promise_type,
1474 // it indicates the user forgot to update the allocation function. Let's emit
1475 // a warning here.
1476 if (FoundNonAlignedInPromise) {
1477 S.Diag(OperatorNew->getLocation(),
1478 diag::warn_non_aligned_allocation_function)
1479 << &FD;
1480 }
1481
1482 if (!OperatorNew) {
1483 if (PromiseContainsNew)
1484 S.Diag(Loc, diag::err_coroutine_unusable_new) << PromiseType << &FD;
1485 else if (RequiresNoThrowAlloc)
1486 S.Diag(Loc, diag::err_coroutine_unfound_nothrow_new)
1487 << &FD << S.getLangOpts().CoroAlignedAllocation;
1488
1489 return false;
1490 }
1491
1492 if (RequiresNoThrowAlloc) {
1493 const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1494 if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1495 S.Diag(OperatorNew->getLocation(),
1496 diag::err_coroutine_promise_new_requires_nothrow)
1497 << OperatorNew;
1498 S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1499 << OperatorNew;
1500 return false;
1501 }
1502 }
1503
1504 FunctionDecl *OperatorDelete = nullptr;
1505 if (!findDeleteForPromise(S, Loc, PromiseType, OperatorDelete)) {
1506 // FIXME: We should add an error here. According to:
1507 // [dcl.fct.def.coroutine]p12
1508 // If no usual deallocation function is found, the program is ill-formed.
1509 return false;
1510 }
1511
1512 Expr *FramePtr =
1513 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
1514
1515 Expr *FrameSize =
1516 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
1517
1518 Expr *FrameAlignment = nullptr;
1519
1520 if (S.getLangOpts().CoroAlignedAllocation) {
1521 FrameAlignment =
1522 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_align, {});
1523
1524 TypeSourceInfo *AlignValTy = getTypeSourceInfoForStdAlignValT(S, Loc);
1525 if (!AlignValTy)
1526 return false;
1527
1528 FrameAlignment = S.BuildCXXNamedCast(Loc, tok::kw_static_cast, AlignValTy,
1529 FrameAlignment, SourceRange(Loc, Loc),
1530 SourceRange(Loc, Loc))
1531 .get();
1532 }
1533
1534 // Make new call.
1535 ExprResult NewRef =
1536 S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1537 if (NewRef.isInvalid())
1538 return false;
1539
1540 SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1541 if (S.getLangOpts().CoroAlignedAllocation && PassAlignment)
1542 NewArgs.push_back(FrameAlignment);
1543
1544 if (OperatorNew->getNumParams() > NewArgs.size())
1545 llvm::append_range(NewArgs, PlacementArgs);
1546
1547 ExprResult NewExpr =
1548 S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1549 NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1550 if (NewExpr.isInvalid())
1551 return false;
1552
1553 // Make delete call.
1554
1555 QualType OpDeleteQualType = OperatorDelete->getType();
1556
1557 ExprResult DeleteRef =
1558 S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1559 if (DeleteRef.isInvalid())
1560 return false;
1561
1562 Expr *CoroFree =
1563 S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1564
1565 SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1566
1567 // [dcl.fct.def.coroutine]p12
1568 // The selected deallocation function shall be called with the address of
1569 // the block of storage to be reclaimed as its first argument. If a
1570 // deallocation function with a parameter of type std::size_t is
1571 // used, the size of the block is passed as the corresponding argument.
1572 const auto *OpDeleteType =
1573 OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1574 if (OpDeleteType->getNumParams() > DeleteArgs.size() &&
1575 S.getASTContext().hasSameUnqualifiedType(
1576 OpDeleteType->getParamType(DeleteArgs.size()), FrameSize->getType()))
1577 DeleteArgs.push_back(FrameSize);
1578
1579 // Proposed Change of [dcl.fct.def.coroutine]p12 in P2014R0:
1580 // If deallocation function lookup finds a usual deallocation function with
1581 // a pointer parameter, size parameter and alignment parameter then this
1582 // will be the selected deallocation function, otherwise if lookup finds a
1583 // usual deallocation function with both a pointer parameter and a size
1584 // parameter, then this will be the selected deallocation function.
1585 // Otherwise, if lookup finds a usual deallocation function with only a
1586 // pointer parameter, then this will be the selected deallocation
1587 // function.
1588 //
1589 // So we are not forced to pass alignment to the deallocation function.
1590 if (S.getLangOpts().CoroAlignedAllocation &&
1591 OpDeleteType->getNumParams() > DeleteArgs.size() &&
1592 S.getASTContext().hasSameUnqualifiedType(
1593 OpDeleteType->getParamType(DeleteArgs.size()),
1594 FrameAlignment->getType()))
1595 DeleteArgs.push_back(FrameAlignment);
1596
1597 ExprResult DeleteExpr =
1598 S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1599 DeleteExpr =
1600 S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1601 if (DeleteExpr.isInvalid())
1602 return false;
1603
1604 this->Allocate = NewExpr.get();
1605 this->Deallocate = DeleteExpr.get();
1606
1607 return true;
1608}
1609
1610bool CoroutineStmtBuilder::makeOnFallthrough() {
1611 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1612, __extension__ __PRETTY_FUNCTION__
))
1612 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1612, __extension__ __PRETTY_FUNCTION__
))
;
1613
1614 // [dcl.fct.def.coroutine]/p6
1615 // If searches for the names return_void and return_value in the scope of
1616 // the promise type each find any declarations, the program is ill-formed.
1617 // [Note 1: If return_void is found, flowing off the end of a coroutine is
1618 // equivalent to a co_return with no operand. Otherwise, flowing off the end
1619 // of a coroutine results in undefined behavior ([stmt.return.coroutine]). —
1620 // end note]
1621 bool HasRVoid, HasRValue;
1622 LookupResult LRVoid =
1623 lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1624 LookupResult LRValue =
1625 lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1626
1627 StmtResult Fallthrough;
1628 if (HasRVoid && HasRValue) {
1629 // FIXME Improve this diagnostic
1630 S.Diag(FD.getLocation(),
1631 diag::err_coroutine_promise_incompatible_return_functions)
1632 << PromiseRecordDecl;
1633 S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1634 diag::note_member_first_declared_here)
1635 << LRVoid.getLookupName();
1636 S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1637 diag::note_member_first_declared_here)
1638 << LRValue.getLookupName();
1639 return false;
1640 } else if (!HasRVoid && !HasRValue) {
1641 // We need to set 'Fallthrough'. Otherwise the other analysis part might
1642 // think the coroutine has defined a return_value method. So it might emit
1643 // **false** positive warning. e.g.,
1644 //
1645 // promise_without_return_func foo() {
1646 // co_await something();
1647 // }
1648 //
1649 // Then AnalysisBasedWarning would emit a warning about `foo()` lacking a
1650 // co_return statements, which isn't correct.
1651 Fallthrough = S.ActOnNullStmt(PromiseRecordDecl->getLocation());
1652 if (Fallthrough.isInvalid())
1653 return false;
1654 } else if (HasRVoid) {
1655 Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1656 /*IsImplicit*/false);
1657 Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1658 if (Fallthrough.isInvalid())
1659 return false;
1660 }
1661
1662 this->OnFallthrough = Fallthrough.get();
1663 return true;
1664}
1665
1666bool CoroutineStmtBuilder::makeOnException() {
1667 // Try to form 'p.unhandled_exception();'
1668 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1669, __extension__ __PRETTY_FUNCTION__
))
1669 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1669, __extension__ __PRETTY_FUNCTION__
))
;
1670
1671 const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1672
1673 if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1674 auto DiagID =
1675 RequireUnhandledException
1676 ? diag::err_coroutine_promise_unhandled_exception_required
1677 : diag::
1678 warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1679 S.Diag(Loc, DiagID) << PromiseRecordDecl;
1680 S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1681 << PromiseRecordDecl;
1682 return !RequireUnhandledException;
1683 }
1684
1685 // If exceptions are disabled, don't try to build OnException.
1686 if (!S.getLangOpts().CXXExceptions)
1687 return true;
1688
1689 ExprResult UnhandledException = buildPromiseCall(
1690 S, Fn.CoroutinePromise, Loc, "unhandled_exception", std::nullopt);
1691 UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1692 /*DiscardedValue*/ false);
1693 if (UnhandledException.isInvalid())
1694 return false;
1695
1696 // Since the body of the coroutine will be wrapped in try-catch, it will
1697 // be incompatible with SEH __try if present in a function.
1698 if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1699 S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1700 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1701 << Fn.getFirstCoroutineStmtKeyword();
1702 return false;
1703 }
1704
1705 this->OnException = UnhandledException.get();
1706 return true;
1707}
1708
1709bool CoroutineStmtBuilder::makeReturnObject() {
1710 // [dcl.fct.def.coroutine]p7
1711 // The expression promise.get_return_object() is used to initialize the
1712 // returned reference or prvalue result object of a call to a coroutine.
1713 ExprResult ReturnObject = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1714 "get_return_object", std::nullopt);
1715 if (ReturnObject.isInvalid())
1716 return false;
1717
1718 this->ReturnValue = ReturnObject.get();
1719 return true;
1720}
1721
1722static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn) {
1723 if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1724 auto *MethodDecl = MbrRef->getMethodDecl();
1725 S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1726 << MethodDecl;
1727 }
1728 S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1729 << Fn.getFirstCoroutineStmtKeyword();
1730}
1731
1732bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1733 assert(!IsPromiseDependentType &&(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1734, __extension__ __PRETTY_FUNCTION__
))
1734 "cannot make statement while the promise type is dependent")(static_cast <bool> (!IsPromiseDependentType &&
"cannot make statement while the promise type is dependent")
? void (0) : __assert_fail ("!IsPromiseDependentType && \"cannot make statement while the promise type is dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1734, __extension__ __PRETTY_FUNCTION__
))
;
1735 assert(this->ReturnValue && "ReturnValue must be already formed")(static_cast <bool> (this->ReturnValue && "ReturnValue must be already formed"
) ? void (0) : __assert_fail ("this->ReturnValue && \"ReturnValue must be already formed\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1735, __extension__ __PRETTY_FUNCTION__
))
;
1736
1737 QualType const GroType = this->ReturnValue->getType();
1738 assert(!GroType->isDependentType() &&(static_cast <bool> (!GroType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1739, __extension__ __PRETTY_FUNCTION__
))
1739 "get_return_object type must no longer be dependent")(static_cast <bool> (!GroType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!GroType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1739, __extension__ __PRETTY_FUNCTION__
))
;
1740
1741 QualType const FnRetType = FD.getReturnType();
1742 assert(!FnRetType->isDependentType() &&(static_cast <bool> (!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1743, __extension__ __PRETTY_FUNCTION__
))
1743 "get_return_object type must no longer be dependent")(static_cast <bool> (!FnRetType->isDependentType() &&
"get_return_object type must no longer be dependent") ? void
(0) : __assert_fail ("!FnRetType->isDependentType() && \"get_return_object type must no longer be dependent\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1743, __extension__ __PRETTY_FUNCTION__
))
;
1744
1745 // The call to get_­return_­object is sequenced before the call to
1746 // initial_­suspend and is invoked at most once, but there are caveats
1747 // regarding on whether the prvalue result object may be initialized
1748 // directly/eager or delayed, depending on the types involved.
1749 //
1750 // More info at https://github.com/cplusplus/papers/issues/1414
1751 bool GroMatchesRetType = S.getASTContext().hasSameType(GroType, FnRetType);
1752
1753 if (FnRetType->isVoidType()) {
1754 ExprResult Res =
1755 S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1756 if (Res.isInvalid())
1757 return false;
1758
1759 if (!GroMatchesRetType)
1760 this->ResultDecl = Res.get();
1761 return true;
1762 }
1763
1764 if (GroType->isVoidType()) {
1765 // Trigger a nice error message.
1766 InitializedEntity Entity =
1767 InitializedEntity::InitializeResult(Loc, FnRetType);
1768 S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1769 noteMemberDeclaredHere(S, ReturnValue, Fn);
1770 return false;
1771 }
1772
1773 StmtResult ReturnStmt;
1774 clang::VarDecl *GroDecl = nullptr;
1775 if (GroMatchesRetType) {
1776 ReturnStmt = S.BuildReturnStmt(Loc, ReturnValue);
1777 } else {
1778 GroDecl = VarDecl::Create(
1779 S.Context, &FD, FD.getLocation(), FD.getLocation(),
1780 &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1781 S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1782 GroDecl->setImplicit();
1783
1784 S.CheckVariableDeclarationType(GroDecl);
1785 if (GroDecl->isInvalidDecl())
1786 return false;
1787
1788 InitializedEntity Entity = InitializedEntity::InitializeVariable(GroDecl);
1789 ExprResult Res =
1790 S.PerformCopyInitialization(Entity, SourceLocation(), ReturnValue);
1791 if (Res.isInvalid())
1792 return false;
1793
1794 Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1795 if (Res.isInvalid())
1796 return false;
1797
1798 S.AddInitializerToDecl(GroDecl, Res.get(),
1799 /*DirectInit=*/false);
1800
1801 S.FinalizeDeclaration(GroDecl);
1802
1803 // Form a declaration statement for the return declaration, so that AST
1804 // visitors can more easily find it.
1805 StmtResult GroDeclStmt =
1806 S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1807 if (GroDeclStmt.isInvalid())
1808 return false;
1809
1810 this->ResultDecl = GroDeclStmt.get();
1811
1812 ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1813 if (declRef.isInvalid())
1814 return false;
1815
1816 ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1817 }
1818
1819 if (ReturnStmt.isInvalid()) {
1820 noteMemberDeclaredHere(S, ReturnValue, Fn);
1821 return false;
1822 }
1823
1824 if (!GroMatchesRetType &&
1825 cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1826 GroDecl->setNRVOVariable(true);
1827
1828 this->ReturnStmt = ReturnStmt.get();
1829 return true;
1830}
1831
1832// Create a static_cast\<T&&>(expr).
1833static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1834 if (T.isNull())
1835 T = E->getType();
1836 QualType TargetType = S.BuildReferenceType(
1837 T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1838 SourceLocation ExprLoc = E->getBeginLoc();
1839 TypeSourceInfo *TargetLoc =
1840 S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1841
1842 return S
1843 .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1844 SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1845 .get();
1846}
1847
1848/// Build a variable declaration for move parameter.
1849static VarDecl *buildVarDecl(Sema &S, SourceLocation Loc, QualType Type,
1850 IdentifierInfo *II) {
1851 TypeSourceInfo *TInfo = S.Context.getTrivialTypeSourceInfo(Type, Loc);
1852 VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1853 TInfo, SC_None);
1854 Decl->setImplicit();
1855 return Decl;
1856}
1857
1858// Build statements that move coroutine function parameters to the coroutine
1859// frame, and store them on the function scope info.
1860bool Sema::buildCoroutineParameterMoves(SourceLocation Loc) {
1861 assert(isa<FunctionDecl>(CurContext) && "not in a function scope")(static_cast <bool> (isa<FunctionDecl>(CurContext
) && "not in a function scope") ? void (0) : __assert_fail
("isa<FunctionDecl>(CurContext) && \"not in a function scope\""
, "clang/lib/Sema/SemaCoroutine.cpp", 1861, __extension__ __PRETTY_FUNCTION__
))
;
1862 auto *FD = cast<FunctionDecl>(CurContext);
1863
1864 auto *ScopeInfo = getCurFunction();
1865 if (!ScopeInfo->CoroutineParameterMoves.empty())
1866 return false;
1867
1868 // [dcl.fct.def.coroutine]p13
1869 // When a coroutine is invoked, after initializing its parameters
1870 // ([expr.call]), a copy is created for each coroutine parameter. For a
1871 // parameter of type cv T, the copy is a variable of type cv T with
1872 // automatic storage duration that is direct-initialized from an xvalue of
1873 // type T referring to the parameter.
1874 for (auto *PD : FD->parameters()) {
1875 if (PD->getType()->isDependentType())
1876 continue;
1877
1878 ExprResult PDRefExpr =
1879 BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1880 ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1881 if (PDRefExpr.isInvalid())
1882 return false;
1883
1884 Expr *CExpr = nullptr;
1885 if (PD->getType()->getAsCXXRecordDecl() ||
1886 PD->getType()->isRValueReferenceType())
1887 CExpr = castForMoving(*this, PDRefExpr.get());
1888 else
1889 CExpr = PDRefExpr.get();
1890 // [dcl.fct.def.coroutine]p13
1891 // The initialization and destruction of each parameter copy occurs in the
1892 // context of the called coroutine.
1893 auto *D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1894 AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1895
1896 // Convert decl to a statement.
1897 StmtResult Stmt = ActOnDeclStmt(ConvertDeclToDeclGroup(D), Loc, Loc);
1898 if (Stmt.isInvalid())
1899 return false;
1900
1901 ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1902 }
1903 return true;
1904}
1905
1906StmtResult Sema::BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1907 CoroutineBodyStmt *Res = CoroutineBodyStmt::Create(Context, Args);
1908 if (!Res)
1909 return StmtError();
1910 return Res;
1911}
1912
1913ClassTemplateDecl *Sema::lookupCoroutineTraits(SourceLocation KwLoc,
1914 SourceLocation FuncLoc) {
1915 if (StdCoroutineTraitsCache)
1916 return StdCoroutineTraitsCache;
1917
1918 IdentifierInfo const &TraitIdent =
1919 PP.getIdentifierTable().get("coroutine_traits");
1920
1921 NamespaceDecl *StdSpace = getStdNamespace();
1922 LookupResult Result(*this, &TraitIdent, FuncLoc, LookupOrdinaryName);
1923 bool Found = StdSpace && LookupQualifiedName(Result, StdSpace);
1924
1925 if (!Found) {
1926 // The goggles, we found nothing!
1927 Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1928 << "std::coroutine_traits";
1929 return nullptr;
1930 }
1931
1932 // coroutine_traits is required to be a class template.
1933 StdCoroutineTraitsCache = Result.getAsSingle<ClassTemplateDecl>();
1934 if (!StdCoroutineTraitsCache) {
1935 Result.suppressDiagnostics();
1936 NamedDecl *Found = *Result.begin();
1937 Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1938 return nullptr;
1939 }
1940
1941 return StdCoroutineTraitsCache;
1942}

/build/source/clang/include/clang/Sema/Sema.h

1//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Sema class, which performs semantic analysis and
10// builds ASTs.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_SEMA_SEMA_H
15#define LLVM_CLANG_SEMA_SEMA_H
16
17#include "clang/AST/ASTConcept.h"
18#include "clang/AST/ASTFwd.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Availability.h"
21#include "clang/AST/ComparisonCategories.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/DeclarationName.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprConcepts.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/ExprOpenMP.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LocInfoType.h"
31#include "clang/AST/MangleNumberingContext.h"
32#include "clang/AST/NSAPI.h"
33#include "clang/AST/PrettyPrinter.h"
34#include "clang/AST/StmtCXX.h"
35#include "clang/AST/StmtOpenMP.h"
36#include "clang/AST/TypeLoc.h"
37#include "clang/AST/TypeOrdering.h"
38#include "clang/Basic/BitmaskEnum.h"
39#include "clang/Basic/Builtins.h"
40#include "clang/Basic/DarwinSDKInfo.h"
41#include "clang/Basic/ExpressionTraits.h"
42#include "clang/Basic/Module.h"
43#include "clang/Basic/OpenCLOptions.h"
44#include "clang/Basic/OpenMPKinds.h"
45#include "clang/Basic/PragmaKinds.h"
46#include "clang/Basic/Specifiers.h"
47#include "clang/Basic/TemplateKinds.h"
48#include "clang/Basic/TypeTraits.h"
49#include "clang/Sema/AnalysisBasedWarnings.h"
50#include "clang/Sema/CleanupInfo.h"
51#include "clang/Sema/DeclSpec.h"
52#include "clang/Sema/ExternalSemaSource.h"
53#include "clang/Sema/IdentifierResolver.h"
54#include "clang/Sema/ObjCMethodList.h"
55#include "clang/Sema/Ownership.h"
56#include "clang/Sema/Scope.h"
57#include "clang/Sema/SemaConcept.h"
58#include "clang/Sema/TypoCorrection.h"
59#include "clang/Sema/Weak.h"
60#include "llvm/ADT/ArrayRef.h"
61#include "llvm/ADT/SetVector.h"
62#include "llvm/ADT/SmallBitVector.h"
63#include "llvm/ADT/SmallPtrSet.h"
64#include "llvm/ADT/SmallSet.h"
65#include "llvm/ADT/SmallVector.h"
66#include "llvm/ADT/TinyPtrVector.h"
67#include "llvm/Frontend/OpenMP/OMPConstants.h"
68#include <deque>
69#include <memory>
70#include <optional>
71#include <string>
72#include <tuple>
73#include <vector>
74
75namespace llvm {
76 class APSInt;
77 template <typename ValueT, typename ValueInfoT> class DenseSet;
78 class SmallBitVector;
79 struct InlineAsmIdentifierInfo;
80}
81
82namespace clang {
83 class ADLResult;
84 class ASTConsumer;
85 class ASTContext;
86 class ASTMutationListener;
87 class ASTReader;
88 class ASTWriter;
89 class ArrayType;
90 class ParsedAttr;
91 class BindingDecl;
92 class BlockDecl;
93 class CapturedDecl;
94 class CXXBasePath;
95 class CXXBasePaths;
96 class CXXBindTemporaryExpr;
97 typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
98 class CXXConstructorDecl;
99 class CXXConversionDecl;
100 class CXXDeleteExpr;
101 class CXXDestructorDecl;
102 class CXXFieldCollector;
103 class CXXMemberCallExpr;
104 class CXXMethodDecl;
105 class CXXScopeSpec;
106 class CXXTemporary;
107 class CXXTryStmt;
108 class CallExpr;
109 class ClassTemplateDecl;
110 class ClassTemplatePartialSpecializationDecl;
111 class ClassTemplateSpecializationDecl;
112 class VarTemplatePartialSpecializationDecl;
113 class CodeCompleteConsumer;
114 class CodeCompletionAllocator;
115 class CodeCompletionTUInfo;
116 class CodeCompletionResult;
117 class CoroutineBodyStmt;
118 class Decl;
119 class DeclAccessPair;
120 class DeclContext;
121 class DeclRefExpr;
122 class DeclaratorDecl;
123 class DeducedTemplateArgument;
124 class DependentDiagnostic;
125 class DesignatedInitExpr;
126 class Designation;
127 class EnableIfAttr;
128 class EnumConstantDecl;
129 class Expr;
130 class ExtVectorType;
131 class FormatAttr;
132 class FriendDecl;
133 class FunctionDecl;
134 class FunctionProtoType;
135 class FunctionTemplateDecl;
136 class ImplicitConversionSequence;
137 typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList;
138 class InitListExpr;
139 class InitializationKind;
140 class InitializationSequence;
141 class InitializedEntity;
142 class IntegerLiteral;
143 class LabelStmt;
144 class LambdaExpr;
145 class LangOptions;
146 class LocalInstantiationScope;
147 class LookupResult;
148 class MacroInfo;
149 typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath;
150 class ModuleLoader;
151 class MultiLevelTemplateArgumentList;
152 class NamedDecl;
153 class ObjCCategoryDecl;
154 class ObjCCategoryImplDecl;
155 class ObjCCompatibleAliasDecl;
156 class ObjCContainerDecl;
157 class ObjCImplDecl;
158 class ObjCImplementationDecl;
159 class ObjCInterfaceDecl;
160 class ObjCIvarDecl;
161 template <class T> class ObjCList;
162 class ObjCMessageExpr;
163 class ObjCMethodDecl;
164 class ObjCPropertyDecl;
165 class ObjCProtocolDecl;
166 class OMPThreadPrivateDecl;
167 class OMPRequiresDecl;
168 class OMPDeclareReductionDecl;
169 class OMPDeclareSimdDecl;
170 class OMPClause;
171 struct OMPVarListLocTy;
172 struct OverloadCandidate;
173 enum class OverloadCandidateParamOrder : char;
174 enum OverloadCandidateRewriteKind : unsigned;
175 class OverloadCandidateSet;
176 class OverloadExpr;
177 class ParenListExpr;
178 class ParmVarDecl;
179 class Preprocessor;
180 class PseudoDestructorTypeStorage;
181 class PseudoObjectExpr;
182 class QualType;
183 class StandardConversionSequence;
184 class Stmt;
185 class StringLiteral;
186 class SwitchStmt;
187 class TemplateArgument;
188 class TemplateArgumentList;
189 class TemplateArgumentLoc;
190 class TemplateDecl;
191 class TemplateInstantiationCallback;
192 class TemplateParameterList;
193 class TemplatePartialOrderingContext;
194 class TemplateTemplateParmDecl;
195 class Token;
196 class TypeAliasDecl;
197 class TypedefDecl;
198 class TypedefNameDecl;
199 class TypeLoc;
200 class TypoCorrectionConsumer;
201 class UnqualifiedId;
202 class UnresolvedLookupExpr;
203 class UnresolvedMemberExpr;
204 class UnresolvedSetImpl;
205 class UnresolvedSetIterator;
206 class UsingDecl;
207 class UsingShadowDecl;
208 class ValueDecl;
209 class VarDecl;
210 class VarTemplateSpecializationDecl;
211 class VisibilityAttr;
212 class VisibleDeclConsumer;
213 class IndirectFieldDecl;
214 struct DeductionFailureInfo;
215 class TemplateSpecCandidateSet;
216
217namespace sema {
218 class AccessedEntity;
219 class BlockScopeInfo;
220 class Capture;
221 class CapturedRegionScopeInfo;
222 class CapturingScopeInfo;
223 class CompoundScopeInfo;
224 class DelayedDiagnostic;
225 class DelayedDiagnosticPool;
226 class FunctionScopeInfo;
227 class LambdaScopeInfo;
228 class PossiblyUnreachableDiag;
229 class RISCVIntrinsicManager;
230 class SemaPPCallbacks;
231 class TemplateDeductionInfo;
232}
233
234namespace threadSafety {
235 class BeforeSet;
236 void threadSafetyCleanup(BeforeSet* Cache);
237}
238
239// FIXME: No way to easily map from TemplateTypeParmTypes to
240// TemplateTypeParmDecls, so we have this horrible PointerUnion.
241typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType *, NamedDecl *>,
242 SourceLocation>
243 UnexpandedParameterPack;
244
245/// Describes whether we've seen any nullability information for the given
246/// file.
247struct FileNullability {
248 /// The first pointer declarator (of any pointer kind) in the file that does
249 /// not have a corresponding nullability annotation.
250 SourceLocation PointerLoc;
251
252 /// The end location for the first pointer declarator in the file. Used for
253 /// placing fix-its.
254 SourceLocation PointerEndLoc;
255
256 /// Which kind of pointer declarator we saw.
257 uint8_t PointerKind;
258
259 /// Whether we saw any type nullability annotations in the given file.
260 bool SawTypeNullability = false;
261};
262
263/// A mapping from file IDs to a record of whether we've seen nullability
264/// information in that file.
265class FileNullabilityMap {
266 /// A mapping from file IDs to the nullability information for each file ID.
267 llvm::DenseMap<FileID, FileNullability> Map;
268
269 /// A single-element cache based on the file ID.
270 struct {
271 FileID File;
272 FileNullability Nullability;
273 } Cache;
274
275public:
276 FileNullability &operator[](FileID file) {
277 // Check the single-element cache.
278 if (file == Cache.File)
279 return Cache.Nullability;
280
281 // It's not in the single-element cache; flush the cache if we have one.
282 if (!Cache.File.isInvalid()) {
283 Map[Cache.File] = Cache.Nullability;
284 }
285
286 // Pull this entry into the cache.
287 Cache.File = file;
288 Cache.Nullability = Map[file];
289 return Cache.Nullability;
290 }
291};
292
293/// Tracks expected type during expression parsing, for use in code completion.
294/// The type is tied to a particular token, all functions that update or consume
295/// the type take a start location of the token they are looking at as a
296/// parameter. This avoids updating the type on hot paths in the parser.
297class PreferredTypeBuilder {
298public:
299 PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {}
300
301 void enterCondition(Sema &S, SourceLocation Tok);
302 void enterReturn(Sema &S, SourceLocation Tok);
303 void enterVariableInit(SourceLocation Tok, Decl *D);
304 /// Handles e.g. BaseType{ .D = Tok...
305 void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType,
306 const Designation &D);
307 /// Computing a type for the function argument may require running
308 /// overloading, so we postpone its computation until it is actually needed.
309 ///
310 /// Clients should be very careful when using this function, as it stores a
311 /// function_ref, clients should make sure all calls to get() with the same
312 /// location happen while function_ref is alive.
313 ///
314 /// The callback should also emit signature help as a side-effect, but only
315 /// if the completion point has been reached.
316 void enterFunctionArgument(SourceLocation Tok,
317 llvm::function_ref<QualType()> ComputeType);
318
319 void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc);
320 void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind,
321 SourceLocation OpLoc);
322 void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op);
323 void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base);
324 void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS);
325 /// Handles all type casts, including C-style cast, C++ casts, etc.
326 void enterTypeCast(SourceLocation Tok, QualType CastType);
327
328 /// Get the expected type associated with this location, if any.
329 ///
330 /// If the location is a function argument, determining the expected type
331 /// involves considering all function overloads and the arguments so far.
332 /// In this case, signature help for these function overloads will be reported
333 /// as a side-effect (only if the completion point has been reached).
334 QualType get(SourceLocation Tok) const {
335 if (!Enabled || Tok != ExpectedLoc)
336 return QualType();
337 if (!Type.isNull())
338 return Type;
339 if (ComputeType)
340 return ComputeType();
341 return QualType();
342 }
343
344private:
345 bool Enabled;
346 /// Start position of a token for which we store expected type.
347 SourceLocation ExpectedLoc;
348 /// Expected type for a token starting at ExpectedLoc.
349 QualType Type;
350 /// A function to compute expected type at ExpectedLoc. It is only considered
351 /// if Type is null.
352 llvm::function_ref<QualType()> ComputeType;
353};
354
355/// Sema - This implements semantic analysis and AST building for C.
356class Sema final {
357 Sema(const Sema &) = delete;
358 void operator=(const Sema &) = delete;
359
360 ///Source of additional semantic information.
361 IntrusiveRefCntPtr<ExternalSemaSource> ExternalSource;
362
363 static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD);
364
365 /// Determine whether two declarations should be linked together, given that
366 /// the old declaration might not be visible and the new declaration might
367 /// not have external linkage.
368 bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old,
369 const NamedDecl *New) {
370 if (isVisible(Old))
371 return true;
372 // See comment in below overload for why it's safe to compute the linkage
373 // of the new declaration here.
374 if (New->isExternallyDeclarable()) {
375 assert(Old->isExternallyDeclarable() &&(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 376, __extension__ __PRETTY_FUNCTION__
))
376 "should not have found a non-externally-declarable previous decl")(static_cast <bool> (Old->isExternallyDeclarable() &&
"should not have found a non-externally-declarable previous decl"
) ? void (0) : __assert_fail ("Old->isExternallyDeclarable() && \"should not have found a non-externally-declarable previous decl\""
, "clang/include/clang/Sema/Sema.h", 376, __extension__ __PRETTY_FUNCTION__
))
;
377 return true;
378 }
379 return false;
380 }
381 bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New);
382
383 void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
384 QualType ResultTy,
385 ArrayRef<QualType> Args);
386
387public:
388 /// The maximum alignment, same as in llvm::Value. We duplicate them here
389 /// because that allows us not to duplicate the constants in clang code,
390 /// which we must to since we can't directly use the llvm constants.
391 /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp
392 ///
393 /// This is the greatest alignment value supported by load, store, and alloca
394 /// instructions, and global values.
395 static const unsigned MaxAlignmentExponent = 32;
396 static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent;
397
398 typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy;
399 typedef OpaquePtr<TemplateName> TemplateTy;
400 typedef OpaquePtr<QualType> TypeTy;
401
402 OpenCLOptions OpenCLFeatures;
403 FPOptions CurFPFeatures;
404
405 const LangOptions &LangOpts;
406 Preprocessor &PP;
407 ASTContext &Context;
408 ASTConsumer &Consumer;
409 DiagnosticsEngine &Diags;
410 SourceManager &SourceMgr;
411
412 /// Flag indicating whether or not to collect detailed statistics.
413 bool CollectStats;
414
415 /// Code-completion consumer.
416 CodeCompleteConsumer *CodeCompleter;
417
418 /// CurContext - This is the current declaration context of parsing.
419 DeclContext *CurContext;
420
421 /// Generally null except when we temporarily switch decl contexts,
422 /// like in \see ActOnObjCTemporaryExitContainerContext.
423 DeclContext *OriginalLexicalContext;
424
425 /// VAListTagName - The declaration name corresponding to __va_list_tag.
426 /// This is used as part of a hack to omit that class from ADL results.
427 DeclarationName VAListTagName;
428
429 bool MSStructPragmaOn; // True when \#pragma ms_struct on
430
431 /// Controls member pointer representation format under the MS ABI.
432 LangOptions::PragmaMSPointersToMembersKind
433 MSPointerToMemberRepresentationMethod;
434
435 /// Stack of active SEH __finally scopes. Can be empty.
436 SmallVector<Scope*, 2> CurrentSEHFinally;
437
438 /// Source location for newly created implicit MSInheritanceAttrs
439 SourceLocation ImplicitMSInheritanceAttrLoc;
440
441 /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by
442 /// `TransformTypos` in order to keep track of any TypoExprs that are created
443 /// recursively during typo correction and wipe them away if the correction
444 /// fails.
445 llvm::SmallVector<TypoExpr *, 2> TypoExprs;
446
447 /// pragma clang section kind
448 enum PragmaClangSectionKind {
449 PCSK_Invalid = 0,
450 PCSK_BSS = 1,
451 PCSK_Data = 2,
452 PCSK_Rodata = 3,
453 PCSK_Text = 4,
454 PCSK_Relro = 5
455 };
456
457 enum PragmaClangSectionAction {
458 PCSA_Set = 0,
459 PCSA_Clear = 1
460 };
461
462 struct PragmaClangSection {
463 std::string SectionName;
464 bool Valid = false;
465 SourceLocation PragmaLocation;
466 };
467
468 PragmaClangSection PragmaClangBSSSection;
469 PragmaClangSection PragmaClangDataSection;
470 PragmaClangSection PragmaClangRodataSection;
471 PragmaClangSection PragmaClangRelroSection;
472 PragmaClangSection PragmaClangTextSection;
473
474 enum PragmaMsStackAction {
475 PSK_Reset = 0x0, // #pragma ()
476 PSK_Set = 0x1, // #pragma (value)
477 PSK_Push = 0x2, // #pragma (push[, id])
478 PSK_Pop = 0x4, // #pragma (pop[, id])
479 PSK_Show = 0x8, // #pragma (show) -- only for "pack"!
480 PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value)
481 PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value)
482 };
483
484 struct PragmaPackInfo {
485 PragmaMsStackAction Action;
486 StringRef SlotLabel;
487 Token Alignment;
488 };
489
490 // #pragma pack and align.
491 class AlignPackInfo {
492 public:
493 // `Native` represents default align mode, which may vary based on the
494 // platform.
495 enum Mode : unsigned char { Native, Natural, Packed, Mac68k };
496
497 // #pragma pack info constructor
498 AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL)
499 : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) {
500 assert(Num == PackNumber && "The pack number has been truncated.")(static_cast <bool> (Num == PackNumber && "The pack number has been truncated."
) ? void (0) : __assert_fail ("Num == PackNumber && \"The pack number has been truncated.\""
, "clang/include/clang/Sema/Sema.h", 500, __extension__ __PRETTY_FUNCTION__
))
;
501 }
502
503 // #pragma align info constructor
504 AlignPackInfo(AlignPackInfo::Mode M, bool IsXL)
505 : PackAttr(false), AlignMode(M),
506 PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {}
507
508 explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {}
509
510 AlignPackInfo() : AlignPackInfo(Native, false) {}
511
512 // When a AlignPackInfo itself cannot be used, this returns an 32-bit
513 // integer encoding for it. This should only be passed to
514 // AlignPackInfo::getFromRawEncoding, it should not be inspected directly.
515 static uint32_t getRawEncoding(const AlignPackInfo &Info) {
516 std::uint32_t Encoding{};
517 if (Info.IsXLStack())
518 Encoding |= IsXLMask;
519
520 Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1;
521
522 if (Info.IsPackAttr())
523 Encoding |= PackAttrMask;
524
525 Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4;
526
527 return Encoding;
528 }
529
530 static AlignPackInfo getFromRawEncoding(unsigned Encoding) {
531 bool IsXL = static_cast<bool>(Encoding & IsXLMask);
532 AlignPackInfo::Mode M =
533 static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1);
534 int PackNumber = (Encoding & PackNumMask) >> 4;
535
536 if (Encoding & PackAttrMask)
537 return AlignPackInfo(M, PackNumber, IsXL);
538
539 return AlignPackInfo(M, IsXL);
540 }
541
542 bool IsPackAttr() const { return PackAttr; }
543
544 bool IsAlignAttr() const { return !PackAttr; }
545
546 Mode getAlignMode() const { return AlignMode; }
547
548 unsigned getPackNumber() const { return PackNumber; }
549
550 bool IsPackSet() const {
551 // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack
552 // attriute on a decl.
553 return PackNumber != UninitPackVal && PackNumber != 0;
554 }
555
556 bool IsXLStack() const { return XLStack; }
557
558 bool operator==(const AlignPackInfo &Info) const {
559 return std::tie(AlignMode, PackNumber, PackAttr, XLStack) ==
560 std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr,
561 Info.XLStack);
562 }
563
564 bool operator!=(const AlignPackInfo &Info) const {
565 return !(*this == Info);
566 }
567
568 private:
569 /// \brief True if this is a pragma pack attribute,
570 /// not a pragma align attribute.
571 bool PackAttr;
572
573 /// \brief The alignment mode that is in effect.
574 Mode AlignMode;
575
576 /// \brief The pack number of the stack.
577 unsigned char PackNumber;
578
579 /// \brief True if it is a XL #pragma align/pack stack.
580 bool XLStack;
581
582 /// \brief Uninitialized pack value.
583 static constexpr unsigned char UninitPackVal = -1;
584
585 // Masks to encode and decode an AlignPackInfo.
586 static constexpr uint32_t IsXLMask{0x0000'0001};
587 static constexpr uint32_t AlignModeMask{0x0000'0006};
588 static constexpr uint32_t PackAttrMask{0x00000'0008};
589 static constexpr uint32_t PackNumMask{0x0000'01F0};
590 };
591
592 template<typename ValueType>
593 struct PragmaStack {
594 struct Slot {
595 llvm::StringRef StackSlotLabel;
596 ValueType Value;
597 SourceLocation PragmaLocation;
598 SourceLocation PragmaPushLocation;
599 Slot(llvm::StringRef StackSlotLabel, ValueType Value,
600 SourceLocation PragmaLocation, SourceLocation PragmaPushLocation)
601 : StackSlotLabel(StackSlotLabel), Value(Value),
602 PragmaLocation(PragmaLocation),
603 PragmaPushLocation(PragmaPushLocation) {}
604 };
605
606 void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action,
607 llvm::StringRef StackSlotLabel, ValueType Value) {
608 if (Action == PSK_Reset) {
609 CurrentValue = DefaultValue;
610 CurrentPragmaLocation = PragmaLocation;
611 return;
612 }
613 if (Action & PSK_Push)
614 Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation,
615 PragmaLocation);
616 else if (Action & PSK_Pop) {
617 if (!StackSlotLabel.empty()) {
618 // If we've got a label, try to find it and jump there.
619 auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) {
620 return x.StackSlotLabel == StackSlotLabel;
621 });
622 // If we found the label so pop from there.
623 if (I != Stack.rend()) {
624 CurrentValue = I->Value;
625 CurrentPragmaLocation = I->PragmaLocation;
626 Stack.erase(std::prev(I.base()), Stack.end());
627 }
628 } else if (!Stack.empty()) {
629 // We do not have a label, just pop the last entry.
630 CurrentValue = Stack.back().Value;
631 CurrentPragmaLocation = Stack.back().PragmaLocation;
632 Stack.pop_back();
633 }
634 }
635 if (Action & PSK_Set) {
636 CurrentValue = Value;
637 CurrentPragmaLocation = PragmaLocation;
638 }
639 }
640
641 // MSVC seems to add artificial slots to #pragma stacks on entering a C++
642 // method body to restore the stacks on exit, so it works like this:
643 //
644 // struct S {
645 // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>)
646 // void Method {}
647 // #pragma <name>(pop, InternalPragmaSlot)
648 // };
649 //
650 // It works even with #pragma vtordisp, although MSVC doesn't support
651 // #pragma vtordisp(push [, id], n)
652 // syntax.
653 //
654 // Push / pop a named sentinel slot.
655 void SentinelAction(PragmaMsStackAction Action, StringRef Label) {
656 assert((Action == PSK_Push || Action == PSK_Pop) &&(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 657, __extension__ __PRETTY_FUNCTION__
))
657 "Can only push / pop #pragma stack sentinels!")(static_cast <bool> ((Action == PSK_Push || Action == PSK_Pop
) && "Can only push / pop #pragma stack sentinels!") ?
void (0) : __assert_fail ("(Action == PSK_Push || Action == PSK_Pop) && \"Can only push / pop #pragma stack sentinels!\""
, "clang/include/clang/Sema/Sema.h", 657, __extension__ __PRETTY_FUNCTION__
))
;
658 Act(CurrentPragmaLocation, Action, Label, CurrentValue);
659 }
660
661 // Constructors.
662 explicit PragmaStack(const ValueType &Default)
663 : DefaultValue(Default), CurrentValue(Default) {}
664
665 bool hasValue() const { return CurrentValue != DefaultValue; }
666
667 SmallVector<Slot, 2> Stack;
668 ValueType DefaultValue; // Value used for PSK_Reset action.
669 ValueType CurrentValue;
670 SourceLocation CurrentPragmaLocation;
671 };
672 // FIXME: We should serialize / deserialize these if they occur in a PCH (but
673 // we shouldn't do so if they're in a module).
674
675 /// Whether to insert vtordisps prior to virtual bases in the Microsoft
676 /// C++ ABI. Possible values are 0, 1, and 2, which mean:
677 ///
678 /// 0: Suppress all vtordisps
679 /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial
680 /// structors
681 /// 2: Always insert vtordisps to support RTTI on partially constructed
682 /// objects
683 PragmaStack<MSVtorDispMode> VtorDispStack;
684 PragmaStack<AlignPackInfo> AlignPackStack;
685 // The current #pragma align/pack values and locations at each #include.
686 struct AlignPackIncludeState {
687 AlignPackInfo CurrentValue;
688 SourceLocation CurrentPragmaLocation;
689 bool HasNonDefaultValue, ShouldWarnOnInclude;
690 };
691 SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack;
692 // Segment #pragmas.
693 PragmaStack<StringLiteral *> DataSegStack;
694 PragmaStack<StringLiteral *> BSSSegStack;
695 PragmaStack<StringLiteral *> ConstSegStack;
696 PragmaStack<StringLiteral *> CodeSegStack;
697
698 // #pragma strict_gs_check.
699 PragmaStack<bool> StrictGuardStackCheckStack;
700
701 // This stack tracks the current state of Sema.CurFPFeatures.
702 PragmaStack<FPOptionsOverride> FpPragmaStack;
703 FPOptionsOverride CurFPFeatureOverrides() {
704 FPOptionsOverride result;
705 if (!FpPragmaStack.hasValue()) {
706 result = FPOptionsOverride();
707 } else {
708 result = FpPragmaStack.CurrentValue;
709 }
710 return result;
711 }
712
713 // RAII object to push / pop sentinel slots for all MS #pragma stacks.
714 // Actions should be performed only if we enter / exit a C++ method body.
715 class PragmaStackSentinelRAII {
716 public:
717 PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct);
718 ~PragmaStackSentinelRAII();
719
720 private:
721 Sema &S;
722 StringRef SlotLabel;
723 bool ShouldAct;
724 };
725
726 /// A mapping that describes the nullability we've seen in each header file.
727 FileNullabilityMap NullabilityMap;
728
729 /// Last section used with #pragma init_seg.
730 StringLiteral *CurInitSeg;
731 SourceLocation CurInitSegLoc;
732
733 /// Sections used with #pragma alloc_text.
734 llvm::StringMap<std::tuple<StringRef, SourceLocation>> FunctionToSectionMap;
735
736 /// VisContext - Manages the stack for \#pragma GCC visibility.
737 void *VisContext; // Really a "PragmaVisStack*"
738
739 /// This an attribute introduced by \#pragma clang attribute.
740 struct PragmaAttributeEntry {
741 SourceLocation Loc;
742 ParsedAttr *Attribute;
743 SmallVector<attr::SubjectMatchRule, 4> MatchRules;
744 bool IsUsed;
745 };
746
747 /// A push'd group of PragmaAttributeEntries.
748 struct PragmaAttributeGroup {
749 /// The location of the push attribute.
750 SourceLocation Loc;
751 /// The namespace of this push group.
752 const IdentifierInfo *Namespace;
753 SmallVector<PragmaAttributeEntry, 2> Entries;
754 };
755
756 SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack;
757
758 /// The declaration that is currently receiving an attribute from the
759 /// #pragma attribute stack.
760 const Decl *PragmaAttributeCurrentTargetDecl;
761
762 /// This represents the last location of a "#pragma clang optimize off"
763 /// directive if such a directive has not been closed by an "on" yet. If
764 /// optimizations are currently "on", this is set to an invalid location.
765 SourceLocation OptimizeOffPragmaLocation;
766
767 /// The "on" or "off" argument passed by \#pragma optimize, that denotes
768 /// whether the optimizations in the list passed to the pragma should be
769 /// turned off or on. This boolean is true by default because command line
770 /// options are honored when `#pragma optimize("", on)`.
771 /// (i.e. `ModifyFnAttributeMSPragmaOptimze()` does nothing)
772 bool MSPragmaOptimizeIsOn = true;
773
774 /// Set of no-builtin functions listed by \#pragma function.
775 llvm::SmallSetVector<StringRef, 4> MSFunctionNoBuiltins;
776
777 /// Flag indicating if Sema is building a recovery call expression.
778 ///
779 /// This flag is used to avoid building recovery call expressions
780 /// if Sema is already doing so, which would cause infinite recursions.
781 bool IsBuildingRecoveryCallExpr;
782
783 /// Used to control the generation of ExprWithCleanups.
784 CleanupInfo Cleanup;
785
786 /// ExprCleanupObjects - This is the stack of objects requiring
787 /// cleanup that are created by the current full expression.
788 SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects;
789
790 /// Store a set of either DeclRefExprs or MemberExprs that contain a reference
791 /// to a variable (constant) that may or may not be odr-used in this Expr, and
792 /// we won't know until all lvalue-to-rvalue and discarded value conversions
793 /// have been applied to all subexpressions of the enclosing full expression.
794 /// This is cleared at the end of each full expression.
795 using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>,
796 llvm::SmallPtrSet<Expr *, 4>>;
797 MaybeODRUseExprSet MaybeODRUseExprs;
798
799 std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope;
800
801 /// Stack containing information about each of the nested
802 /// function, block, and method scopes that are currently active.
803 SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes;
804
805 /// The index of the first FunctionScope that corresponds to the current
806 /// context.
807 unsigned FunctionScopesStart = 0;
808
809 /// Track the number of currently active capturing scopes.
810 unsigned CapturingFunctionScopes = 0;
811
812 ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const {
813 return llvm::ArrayRef(FunctionScopes.begin() + FunctionScopesStart,
814 FunctionScopes.end());
815 }
816
817 /// Stack containing information needed when in C++2a an 'auto' is encountered
818 /// in a function declaration parameter type specifier in order to invent a
819 /// corresponding template parameter in the enclosing abbreviated function
820 /// template. This information is also present in LambdaScopeInfo, stored in
821 /// the FunctionScopes stack.
822 SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos;
823
824 /// The index of the first InventedParameterInfo that refers to the current
825 /// context.
826 unsigned InventedParameterInfosStart = 0;
827
828 ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const {
829 return llvm::ArrayRef(InventedParameterInfos.begin() +
830 InventedParameterInfosStart,
831 InventedParameterInfos.end());
832 }
833
834 typedef LazyVector<TypedefNameDecl *, ExternalSemaSource,
835 &ExternalSemaSource::ReadExtVectorDecls, 2, 2>
836 ExtVectorDeclsType;
837
838 /// ExtVectorDecls - This is a list all the extended vector types. This allows
839 /// us to associate a raw vector type with one of the ext_vector type names.
840 /// This is only necessary for issuing pretty diagnostics.
841 ExtVectorDeclsType ExtVectorDecls;
842
843 /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes.
844 std::unique_ptr<CXXFieldCollector> FieldCollector;
845
846 typedef llvm::SmallSetVector<const NamedDecl *, 16> NamedDeclSetType;
847
848 /// Set containing all declared private fields that are not used.
849 NamedDeclSetType UnusedPrivateFields;
850
851 /// Set containing all typedefs that are likely unused.
852 llvm::SmallSetVector<const TypedefNameDecl *, 4>
853 UnusedLocalTypedefNameCandidates;
854
855 /// Delete-expressions to be analyzed at the end of translation unit
856 ///
857 /// This list contains class members, and locations of delete-expressions
858 /// that could not be proven as to whether they mismatch with new-expression
859 /// used in initializer of the field.
860 typedef std::pair<SourceLocation, bool> DeleteExprLoc;
861 typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs;
862 llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs;
863
864 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy;
865
866 /// PureVirtualClassDiagSet - a set of class declarations which we have
867 /// emitted a list of pure virtual functions. Used to prevent emitting the
868 /// same list more than once.
869 std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet;
870
871 /// ParsingInitForAutoVars - a set of declarations with auto types for which
872 /// we are currently parsing the initializer.
873 llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars;
874
875 /// Look for a locally scoped extern "C" declaration by the given name.
876 NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name);
877
878 typedef LazyVector<VarDecl *, ExternalSemaSource,
879 &ExternalSemaSource::ReadTentativeDefinitions, 2, 2>
880 TentativeDefinitionsType;
881
882 /// All the tentative definitions encountered in the TU.
883 TentativeDefinitionsType TentativeDefinitions;
884
885 /// All the external declarations encoutered and used in the TU.
886 SmallVector<VarDecl *, 4> ExternalDeclarations;
887
888 typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource,
889 &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2>
890 UnusedFileScopedDeclsType;
891
892 /// The set of file scoped decls seen so far that have not been used
893 /// and must warn if not used. Only contains the first declaration.
894 UnusedFileScopedDeclsType UnusedFileScopedDecls;
895
896 typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource,
897 &ExternalSemaSource::ReadDelegatingConstructors, 2, 2>
898 DelegatingCtorDeclsType;
899
900 /// All the delegating constructors seen so far in the file, used for
901 /// cycle detection at the end of the TU.
902 DelegatingCtorDeclsType DelegatingCtorDecls;
903
904 /// All the overriding functions seen during a class definition
905 /// that had their exception spec checks delayed, plus the overridden
906 /// function.
907 SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2>
908 DelayedOverridingExceptionSpecChecks;
909
910 /// All the function redeclarations seen during a class definition that had
911 /// their exception spec checks delayed, plus the prior declaration they
912 /// should be checked against. Except during error recovery, the new decl
913 /// should always be a friend declaration, as that's the only valid way to
914 /// redeclare a special member before its class is complete.
915 SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2>
916 DelayedEquivalentExceptionSpecChecks;
917
918 typedef llvm::MapVector<const FunctionDecl *,
919 std::unique_ptr<LateParsedTemplate>>
920 LateParsedTemplateMapT;
921 LateParsedTemplateMapT LateParsedTemplateMap;
922
923 /// Callback to the parser to parse templated functions when needed.
924 typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT);
925 typedef void LateTemplateParserCleanupCB(void *P);
926 LateTemplateParserCB *LateTemplateParser;
927 LateTemplateParserCleanupCB *LateTemplateParserCleanup;
928 void *OpaqueParser;
929
930 void SetLateTemplateParser(LateTemplateParserCB *LTP,
931 LateTemplateParserCleanupCB *LTPCleanup,
932 void *P) {
933 LateTemplateParser = LTP;
934 LateTemplateParserCleanup = LTPCleanup;
935 OpaqueParser = P;
936 }
937
938 class DelayedDiagnostics;
939
940 class DelayedDiagnosticsState {
941 sema::DelayedDiagnosticPool *SavedPool;
942 friend class Sema::DelayedDiagnostics;
943 };
944 typedef DelayedDiagnosticsState ParsingDeclState;
945 typedef DelayedDiagnosticsState ProcessingContextState;
946
947 /// A class which encapsulates the logic for delaying diagnostics
948 /// during parsing and other processing.
949 class DelayedDiagnostics {
950 /// The current pool of diagnostics into which delayed
951 /// diagnostics should go.
952 sema::DelayedDiagnosticPool *CurPool = nullptr;
953
954 public:
955 DelayedDiagnostics() = default;
956
957 /// Adds a delayed diagnostic.
958 void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h
959
960 /// Determines whether diagnostics should be delayed.
961 bool shouldDelayDiagnostics() { return CurPool != nullptr; }
962
963 /// Returns the current delayed-diagnostics pool.
964 sema::DelayedDiagnosticPool *getCurrentPool() const {
965 return CurPool;
966 }
967
968 /// Enter a new scope. Access and deprecation diagnostics will be
969 /// collected in this pool.
970 DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) {
971 DelayedDiagnosticsState state;
972 state.SavedPool = CurPool;
973 CurPool = &pool;
974 return state;
975 }
976
977 /// Leave a delayed-diagnostic state that was previously pushed.
978 /// Do not emit any of the diagnostics. This is performed as part
979 /// of the bookkeeping of popping a pool "properly".
980 void popWithoutEmitting(DelayedDiagnosticsState state) {
981 CurPool = state.SavedPool;
982 }
983
984 /// Enter a new scope where access and deprecation diagnostics are
985 /// not delayed.
986 DelayedDiagnosticsState pushUndelayed() {
987 DelayedDiagnosticsState state;
988 state.SavedPool = CurPool;
989 CurPool = nullptr;
990 return state;
991 }
992
993 /// Undo a previous pushUndelayed().
994 void popUndelayed(DelayedDiagnosticsState state) {
995 assert(CurPool == nullptr)(static_cast <bool> (CurPool == nullptr) ? void (0) : __assert_fail
("CurPool == nullptr", "clang/include/clang/Sema/Sema.h", 995
, __extension__ __PRETTY_FUNCTION__))
;
996 CurPool = state.SavedPool;
997 }
998 } DelayedDiagnostics;
999
1000 /// A RAII object to temporarily push a declaration context.
1001 class ContextRAII {
1002 private:
1003 Sema &S;
1004 DeclContext *SavedContext;
1005 ProcessingContextState SavedContextState;
1006 QualType SavedCXXThisTypeOverride;
1007 unsigned SavedFunctionScopesStart;
1008 unsigned SavedInventedParameterInfosStart;
1009
1010 public:
1011 ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true)
1012 : S(S), SavedContext(S.CurContext),
1013 SavedContextState(S.DelayedDiagnostics.pushUndelayed()),
1014 SavedCXXThisTypeOverride(S.CXXThisTypeOverride),
1015 SavedFunctionScopesStart(S.FunctionScopesStart),
1016 SavedInventedParameterInfosStart(S.InventedParameterInfosStart)
1017 {
1018 assert(ContextToPush && "pushing null context")(static_cast <bool> (ContextToPush && "pushing null context"
) ? void (0) : __assert_fail ("ContextToPush && \"pushing null context\""
, "clang/include/clang/Sema/Sema.h", 1018, __extension__ __PRETTY_FUNCTION__
))
;
1019 S.CurContext = ContextToPush;
1020 if (NewThisContext)
1021 S.CXXThisTypeOverride = QualType();
1022 // Any saved FunctionScopes do not refer to this context.
1023 S.FunctionScopesStart = S.FunctionScopes.size();
1024 S.InventedParameterInfosStart = S.InventedParameterInfos.size();
1025 }
1026
1027 void pop() {
1028 if (!SavedContext) return;
1029 S.CurContext = SavedContext;
1030 S.DelayedDiagnostics.popUndelayed(SavedContextState);
1031 S.CXXThisTypeOverride = SavedCXXThisTypeOverride;
1032 S.FunctionScopesStart = SavedFunctionScopesStart;
1033 S.InventedParameterInfosStart = SavedInventedParameterInfosStart;
1034 SavedContext = nullptr;
1035 }
1036
1037 ~ContextRAII() {
1038 pop();
1039 }
1040 };
1041
1042 /// Whether the AST is currently being rebuilt to correct immediate
1043 /// invocations. Immediate invocation candidates and references to consteval
1044 /// functions aren't tracked when this is set.
1045 bool RebuildingImmediateInvocation = false;
1046
1047 /// Used to change context to isConstantEvaluated without pushing a heavy
1048 /// ExpressionEvaluationContextRecord object.
1049 bool isConstantEvaluatedOverride;
1050
1051 bool isConstantEvaluated() const {
1052 return ExprEvalContexts.back().isConstantEvaluated() ||
1053 isConstantEvaluatedOverride;
1054 }
1055
1056 /// RAII object to handle the state changes required to synthesize
1057 /// a function body.
1058 class SynthesizedFunctionScope {
1059 Sema &S;
1060 Sema::ContextRAII SavedContext;
1061 bool PushedCodeSynthesisContext = false;
1062
1063 public:
1064 SynthesizedFunctionScope(Sema &S, DeclContext *DC)
1065 : S(S), SavedContext(S, DC) {
1066 S.PushFunctionScope();
1067 S.PushExpressionEvaluationContext(
1068 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
1069 if (auto *FD = dyn_cast<FunctionDecl>(DC))
1070 FD->setWillHaveBody(true);
1071 else
1072 assert(isa<ObjCMethodDecl>(DC))(static_cast <bool> (isa<ObjCMethodDecl>(DC)) ? void
(0) : __assert_fail ("isa<ObjCMethodDecl>(DC)", "clang/include/clang/Sema/Sema.h"
, 1072, __extension__ __PRETTY_FUNCTION__))
;
1073 }
1074
1075 void addContextNote(SourceLocation UseLoc) {
1076 assert(!PushedCodeSynthesisContext)(static_cast <bool> (!PushedCodeSynthesisContext) ? void
(0) : __assert_fail ("!PushedCodeSynthesisContext", "clang/include/clang/Sema/Sema.h"
, 1076, __extension__ __PRETTY_FUNCTION__))
;
1077
1078 Sema::CodeSynthesisContext Ctx;
1079 Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction;
1080 Ctx.PointOfInstantiation = UseLoc;
1081 Ctx.Entity = cast<Decl>(S.CurContext);
1082 S.pushCodeSynthesisContext(Ctx);
1083
1084 PushedCodeSynthesisContext = true;
1085 }
1086
1087 ~SynthesizedFunctionScope() {
1088 if (PushedCodeSynthesisContext)
1089 S.popCodeSynthesisContext();
1090 if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext))
1091 FD->setWillHaveBody(false);
1092 S.PopExpressionEvaluationContext();
1093 S.PopFunctionScopeInfo();
1094 }
1095 };
1096
1097 /// WeakUndeclaredIdentifiers - Identifiers contained in \#pragma weak before
1098 /// declared. Rare. May alias another identifier, declared or undeclared.
1099 ///
1100 /// For aliases, the target identifier is used as a key for eventual
1101 /// processing when the target is declared. For the single-identifier form,
1102 /// the sole identifier is used as the key. Each entry is a `SetVector`
1103 /// (ordered by parse order) of aliases (identified by the alias name) in case
1104 /// of multiple aliases to the same undeclared identifier.
1105 llvm::MapVector<
1106 IdentifierInfo *,
1107 llvm::SetVector<
1108 WeakInfo, llvm::SmallVector<WeakInfo, 1u>,
1109 llvm::SmallDenseSet<WeakInfo, 2u, WeakInfo::DenseMapInfoByAliasOnly>>>
1110 WeakUndeclaredIdentifiers;
1111
1112 /// ExtnameUndeclaredIdentifiers - Identifiers contained in
1113 /// \#pragma redefine_extname before declared. Used in Solaris system headers
1114 /// to define functions that occur in multiple standards to call the version
1115 /// in the currently selected standard.
1116 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers;
1117
1118
1119 /// Load weak undeclared identifiers from the external source.
1120 void LoadExternalWeakUndeclaredIdentifiers();
1121
1122 /// WeakTopLevelDecl - Translation-unit scoped declarations generated by
1123 /// \#pragma weak during processing of other Decls.
1124 /// I couldn't figure out a clean way to generate these in-line, so
1125 /// we store them here and handle separately -- which is a hack.
1126 /// It would be best to refactor this.
1127 SmallVector<Decl*,2> WeakTopLevelDecl;
1128
1129 IdentifierResolver IdResolver;
1130
1131 /// Translation Unit Scope - useful to Objective-C actions that need
1132 /// to lookup file scope declarations in the "ordinary" C decl namespace.
1133 /// For example, user-defined classes, built-in "id" type, etc.
1134 Scope *TUScope;
1135
1136 /// The C++ "std" namespace, where the standard library resides.
1137 LazyDeclPtr StdNamespace;
1138
1139 /// The C++ "std::bad_alloc" class, which is defined by the C++
1140 /// standard library.
1141 LazyDeclPtr StdBadAlloc;
1142
1143 /// The C++ "std::align_val_t" enum class, which is defined by the C++
1144 /// standard library.
1145 LazyDeclPtr StdAlignValT;
1146
1147 /// The C++ "std::initializer_list" template, which is defined in
1148 /// \<initializer_list>.
1149 ClassTemplateDecl *StdInitializerList;
1150
1151 /// The C++ "std::coroutine_traits" template, which is defined in
1152 /// \<coroutine_traits>
1153 ClassTemplateDecl *StdCoroutineTraitsCache;
1154
1155 /// The C++ "type_info" declaration, which is defined in \<typeinfo>.
1156 RecordDecl *CXXTypeInfoDecl;
1157
1158 /// The MSVC "_GUID" struct, which is defined in MSVC header files.
1159 RecordDecl *MSVCGuidDecl;
1160
1161 /// The C++ "std::source_location::__impl" struct, defined in
1162 /// \<source_location>.
1163 RecordDecl *StdSourceLocationImplDecl;
1164
1165 /// Caches identifiers/selectors for NSFoundation APIs.
1166 std::unique_ptr<NSAPI> NSAPIObj;
1167
1168 /// The declaration of the Objective-C NSNumber class.
1169 ObjCInterfaceDecl *NSNumberDecl;
1170
1171 /// The declaration of the Objective-C NSValue class.
1172 ObjCInterfaceDecl *NSValueDecl;
1173
1174 /// Pointer to NSNumber type (NSNumber *).
1175 QualType NSNumberPointer;
1176
1177 /// Pointer to NSValue type (NSValue *).
1178 QualType NSValuePointer;
1179
1180 /// The Objective-C NSNumber methods used to create NSNumber literals.
1181 ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods];
1182
1183 /// The declaration of the Objective-C NSString class.
1184 ObjCInterfaceDecl *NSStringDecl;
1185
1186 /// Pointer to NSString type (NSString *).
1187 QualType NSStringPointer;
1188
1189 /// The declaration of the stringWithUTF8String: method.
1190 ObjCMethodDecl *StringWithUTF8StringMethod;
1191
1192 /// The declaration of the valueWithBytes:objCType: method.
1193 ObjCMethodDecl *ValueWithBytesObjCTypeMethod;
1194
1195 /// The declaration of the Objective-C NSArray class.
1196 ObjCInterfaceDecl *NSArrayDecl;
1197
1198 /// The declaration of the arrayWithObjects:count: method.
1199 ObjCMethodDecl *ArrayWithObjectsMethod;
1200
1201 /// The declaration of the Objective-C NSDictionary class.
1202 ObjCInterfaceDecl *NSDictionaryDecl;
1203
1204 /// The declaration of the dictionaryWithObjects:forKeys:count: method.
1205 ObjCMethodDecl *DictionaryWithObjectsMethod;
1206
1207 /// id<NSCopying> type.
1208 QualType QIDNSCopying;
1209
1210 /// will hold 'respondsToSelector:'
1211 Selector RespondsToSelectorSel;
1212
1213 /// A flag to remember whether the implicit forms of operator new and delete
1214 /// have been declared.
1215 bool GlobalNewDeleteDeclared;
1216
1217 /// Describes how the expressions currently being parsed are
1218 /// evaluated at run-time, if at all.
1219 enum class ExpressionEvaluationContext {
1220 /// The current expression and its subexpressions occur within an
1221 /// unevaluated operand (C++11 [expr]p7), such as the subexpression of
1222 /// \c sizeof, where the type of the expression may be significant but
1223 /// no code will be generated to evaluate the value of the expression at
1224 /// run time.
1225 Unevaluated,
1226
1227 /// The current expression occurs within a braced-init-list within
1228 /// an unevaluated operand. This is mostly like a regular unevaluated
1229 /// context, except that we still instantiate constexpr functions that are
1230 /// referenced here so that we can perform narrowing checks correctly.
1231 UnevaluatedList,
1232
1233 /// The current expression occurs within a discarded statement.
1234 /// This behaves largely similarly to an unevaluated operand in preventing
1235 /// definitions from being required, but not in other ways.
1236 DiscardedStatement,
1237
1238 /// The current expression occurs within an unevaluated
1239 /// operand that unconditionally permits abstract references to
1240 /// fields, such as a SIZE operator in MS-style inline assembly.
1241 UnevaluatedAbstract,
1242
1243 /// The current context is "potentially evaluated" in C++11 terms,
1244 /// but the expression is evaluated at compile-time (like the values of
1245 /// cases in a switch statement).
1246 ConstantEvaluated,
1247
1248 /// In addition of being constant evaluated, the current expression
1249 /// occurs in an immediate function context - either a consteval function
1250 /// or a consteval if function.
1251 ImmediateFunctionContext,
1252
1253 /// The current expression is potentially evaluated at run time,
1254 /// which means that code may be generated to evaluate the value of the
1255 /// expression at run time.
1256 PotentiallyEvaluated,
1257
1258 /// The current expression is potentially evaluated, but any
1259 /// declarations referenced inside that expression are only used if
1260 /// in fact the current expression is used.
1261 ///
1262 /// This value is used when parsing default function arguments, for which
1263 /// we would like to provide diagnostics (e.g., passing non-POD arguments
1264 /// through varargs) but do not want to mark declarations as "referenced"
1265 /// until the default argument is used.
1266 PotentiallyEvaluatedIfUsed
1267 };
1268
1269 using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>;
1270
1271 /// Data structure used to record current or nested
1272 /// expression evaluation contexts.
1273 struct ExpressionEvaluationContextRecord {
1274 /// The expression evaluation context.
1275 ExpressionEvaluationContext Context;
1276
1277 /// Whether the enclosing context needed a cleanup.
1278 CleanupInfo ParentCleanup;
1279
1280 /// The number of active cleanup objects when we entered
1281 /// this expression evaluation context.
1282 unsigned NumCleanupObjects;
1283
1284 /// The number of typos encountered during this expression evaluation
1285 /// context (i.e. the number of TypoExprs created).
1286 unsigned NumTypos;
1287
1288 MaybeODRUseExprSet SavedMaybeODRUseExprs;
1289
1290 /// The lambdas that are present within this context, if it
1291 /// is indeed an unevaluated context.
1292 SmallVector<LambdaExpr *, 2> Lambdas;
1293
1294 /// The declaration that provides context for lambda expressions
1295 /// and block literals if the normal declaration context does not
1296 /// suffice, e.g., in a default function argument.
1297 Decl *ManglingContextDecl;
1298
1299 /// If we are processing a decltype type, a set of call expressions
1300 /// for which we have deferred checking the completeness of the return type.
1301 SmallVector<CallExpr *, 8> DelayedDecltypeCalls;
1302
1303 /// If we are processing a decltype type, a set of temporary binding
1304 /// expressions for which we have deferred checking the destructor.
1305 SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds;
1306
1307 llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs;
1308
1309 /// Expressions appearing as the LHS of a volatile assignment in this
1310 /// context. We produce a warning for these when popping the context if
1311 /// they are not discarded-value expressions nor unevaluated operands.
1312 SmallVector<Expr*, 2> VolatileAssignmentLHSs;
1313
1314 /// Set of candidates for starting an immediate invocation.
1315 llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates;
1316
1317 /// Set of DeclRefExprs referencing a consteval function when used in a
1318 /// context not already known to be immediately invoked.
1319 llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval;
1320
1321 /// \brief Describes whether we are in an expression constext which we have
1322 /// to handle differently.
1323 enum ExpressionKind {
1324 EK_Decltype, EK_TemplateArgument, EK_Other
1325 } ExprContext;
1326
1327 // A context can be nested in both a discarded statement context and
1328 // an immediate function context, so they need to be tracked independently.
1329 bool InDiscardedStatement;
1330 bool InImmediateFunctionContext;
1331
1332 bool IsCurrentlyCheckingDefaultArgumentOrInitializer = false;
1333
1334 // When evaluating immediate functions in the initializer of a default
1335 // argument or default member initializer, this is the declaration whose
1336 // default initializer is being evaluated and the location of the call
1337 // or constructor definition.
1338 struct InitializationContext {
1339 InitializationContext(SourceLocation Loc, ValueDecl *Decl,
1340 DeclContext *Context)
1341 : Loc(Loc), Decl(Decl), Context(Context) {
1342 assert(Decl && Context && "invalid initialization context")(static_cast <bool> (Decl && Context &&
"invalid initialization context") ? void (0) : __assert_fail
("Decl && Context && \"invalid initialization context\""
, "clang/include/clang/Sema/Sema.h", 1342, __extension__ __PRETTY_FUNCTION__
))
;
1343 }
1344
1345 SourceLocation Loc;
1346 ValueDecl *Decl = nullptr;
1347 DeclContext *Context = nullptr;
1348 };
1349 std::optional<InitializationContext> DelayedDefaultInitializationContext;
1350
1351 ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context,
1352 unsigned NumCleanupObjects,
1353 CleanupInfo ParentCleanup,
1354 Decl *ManglingContextDecl,
1355 ExpressionKind ExprContext)
1356 : Context(Context), ParentCleanup(ParentCleanup),
1357 NumCleanupObjects(NumCleanupObjects), NumTypos(0),
1358 ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext),
1359 InDiscardedStatement(false), InImmediateFunctionContext(false) {}
1360
1361 bool isUnevaluated() const {
1362 return Context == ExpressionEvaluationContext::Unevaluated ||
1363 Context == ExpressionEvaluationContext::UnevaluatedAbstract ||
1364 Context == ExpressionEvaluationContext::UnevaluatedList;
1365 }
1366
1367 bool isConstantEvaluated() const {
1368 return Context == ExpressionEvaluationContext::ConstantEvaluated ||
1369 Context == ExpressionEvaluationContext::ImmediateFunctionContext;
1370 }
1371
1372 bool isImmediateFunctionContext() const {
1373 return Context == ExpressionEvaluationContext::ImmediateFunctionContext ||
1374 (Context == ExpressionEvaluationContext::DiscardedStatement &&
1375 InImmediateFunctionContext) ||
1376 // C++23 [expr.const]p14:
1377 // An expression or conversion is in an immediate function
1378 // context if it is potentially evaluated and either:
1379 // * its innermost enclosing non-block scope is a function
1380 // parameter scope of an immediate function, or
1381 // * its enclosing statement is enclosed by the compound-
1382 // statement of a consteval if statement.
1383 (Context == ExpressionEvaluationContext::PotentiallyEvaluated &&
1384 InImmediateFunctionContext);
1385 }
1386
1387 bool isDiscardedStatementContext() const {
1388 return Context == ExpressionEvaluationContext::DiscardedStatement ||
1389 (Context ==
1390 ExpressionEvaluationContext::ImmediateFunctionContext &&
1391 InDiscardedStatement);
1392 }
1393 };
1394
1395 /// A stack of expression evaluation contexts.
1396 SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts;
1397
1398 // Set of failed immediate invocations to avoid double diagnosing.
1399 llvm::SmallPtrSet<ConstantExpr *, 4> FailedImmediateInvocations;
1400
1401 /// Emit a warning for all pending noderef expressions that we recorded.
1402 void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec);
1403
1404 /// Compute the mangling number context for a lambda expression or
1405 /// block literal. Also return the extra mangling decl if any.
1406 ///
1407 /// \param DC - The DeclContext containing the lambda expression or
1408 /// block literal.
1409 std::tuple<MangleNumberingContext *, Decl *>
1410 getCurrentMangleNumberContext(const DeclContext *DC);
1411
1412
1413 /// SpecialMemberOverloadResult - The overloading result for a special member
1414 /// function.
1415 ///
1416 /// This is basically a wrapper around PointerIntPair. The lowest bits of the
1417 /// integer are used to determine whether overload resolution succeeded.
1418 class SpecialMemberOverloadResult {
1419 public:
1420 enum Kind {
1421 NoMemberOrDeleted,
1422 Ambiguous,
1423 Success
1424 };
1425
1426 private:
1427 llvm::PointerIntPair<CXXMethodDecl *, 2> Pair;
1428
1429 public:
1430 SpecialMemberOverloadResult() {}
1431 SpecialMemberOverloadResult(CXXMethodDecl *MD)
1432 : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {}
1433
1434 CXXMethodDecl *getMethod() const { return Pair.getPointer(); }
1435 void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); }
1436
1437 Kind getKind() const { return static_cast<Kind>(Pair.getInt()); }
1438 void setKind(Kind K) { Pair.setInt(K); }
1439 };
1440
1441 class SpecialMemberOverloadResultEntry
1442 : public llvm::FastFoldingSetNode,
1443 public SpecialMemberOverloadResult {
1444 public:
1445 SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID)
1446 : FastFoldingSetNode(ID)
1447 {}
1448 };
1449
1450 /// A cache of special member function overload resolution results
1451 /// for C++ records.
1452 llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache;
1453
1454 /// A cache of the flags available in enumerations with the flag_bits
1455 /// attribute.
1456 mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache;
1457
1458 /// The kind of translation unit we are processing.
1459 ///
1460 /// When we're processing a complete translation unit, Sema will perform
1461 /// end-of-translation-unit semantic tasks (such as creating
1462 /// initializers for tentative definitions in C) once parsing has
1463 /// completed. Modules and precompiled headers perform different kinds of
1464 /// checks.
1465 const TranslationUnitKind TUKind;
1466
1467 llvm::BumpPtrAllocator BumpAlloc;
1468
1469 /// The number of SFINAE diagnostics that have been trapped.
1470 unsigned NumSFINAEErrors;
1471
1472 typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>>
1473 UnparsedDefaultArgInstantiationsMap;
1474
1475 /// A mapping from parameters with unparsed default arguments to the
1476 /// set of instantiations of each parameter.
1477 ///
1478 /// This mapping is a temporary data structure used when parsing
1479 /// nested class templates or nested classes of class templates,
1480 /// where we might end up instantiating an inner class before the
1481 /// default arguments of its methods have been parsed.
1482 UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations;
1483
1484 // Contains the locations of the beginning of unparsed default
1485 // argument locations.
1486 llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs;
1487
1488 /// UndefinedInternals - all the used, undefined objects which require a
1489 /// definition in this translation unit.
1490 llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed;
1491
1492 /// Determine if VD, which must be a variable or function, is an external
1493 /// symbol that nonetheless can't be referenced from outside this translation
1494 /// unit because its type has no linkage and it's not extern "C".
1495 bool isExternalWithNoLinkageType(const ValueDecl *VD) const;
1496
1497 /// Obtain a sorted list of functions that are undefined but ODR-used.
1498 void getUndefinedButUsed(
1499 SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined);
1500
1501 /// Retrieves list of suspicious delete-expressions that will be checked at
1502 /// the end of translation unit.
1503 const llvm::MapVector<FieldDecl *, DeleteLocs> &
1504 getMismatchingDeleteExpressions() const;
1505
1506 class GlobalMethodPool {
1507 public:
1508 using Lists = std::pair<ObjCMethodList, ObjCMethodList>;
1509 using iterator = llvm::DenseMap<Selector, Lists>::iterator;
1510 iterator begin() { return Methods.begin(); }
1511 iterator end() { return Methods.end(); }
1512 iterator find(Selector Sel) { return Methods.find(Sel); }
1513 std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) {
1514 return Methods.insert(Val);
1515 }
1516 int count(Selector Sel) const { return Methods.count(Sel); }
1517 bool empty() const { return Methods.empty(); }
1518
1519 private:
1520 llvm::DenseMap<Selector, Lists> Methods;
1521 };
1522
1523 /// Method Pool - allows efficient lookup when typechecking messages to "id".
1524 /// We need to maintain a list, since selectors can have differing signatures
1525 /// across classes. In Cocoa, this happens to be extremely uncommon (only 1%
1526 /// of selectors are "overloaded").
1527 /// At the head of the list it is recorded whether there were 0, 1, or >= 2
1528 /// methods inside categories with a particular selector.
1529 GlobalMethodPool MethodPool;
1530
1531 /// Method selectors used in a \@selector expression. Used for implementation
1532 /// of -Wselector.
1533 llvm::MapVector<Selector, SourceLocation> ReferencedSelectors;
1534
1535 /// List of SourceLocations where 'self' is implicitly retained inside a
1536 /// block.
1537 llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1>
1538 ImplicitlyRetainedSelfLocs;
1539
1540 /// Kinds of C++ special members.
1541 enum CXXSpecialMember {
1542 CXXDefaultConstructor,
1543 CXXCopyConstructor,
1544 CXXMoveConstructor,
1545 CXXCopyAssignment,
1546 CXXMoveAssignment,
1547 CXXDestructor,
1548 CXXInvalid
1549 };
1550
1551 typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember>
1552 SpecialMemberDecl;
1553
1554 /// The C++ special members which we are currently in the process of
1555 /// declaring. If this process recursively triggers the declaration of the
1556 /// same special member, we should act as if it is not yet declared.
1557 llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared;
1558
1559 /// Kinds of defaulted comparison operator functions.
1560 enum class DefaultedComparisonKind : unsigned char {
1561 /// This is not a defaultable comparison operator.
1562 None,
1563 /// This is an operator== that should be implemented as a series of
1564 /// subobject comparisons.
1565 Equal,
1566 /// This is an operator<=> that should be implemented as a series of
1567 /// subobject comparisons.
1568 ThreeWay,
1569 /// This is an operator!= that should be implemented as a rewrite in terms
1570 /// of a == comparison.
1571 NotEqual,
1572 /// This is an <, <=, >, or >= that should be implemented as a rewrite in
1573 /// terms of a <=> comparison.
1574 Relational,
1575 };
1576
1577 /// The function definitions which were renamed as part of typo-correction
1578 /// to match their respective declarations. We want to keep track of them
1579 /// to ensure that we don't emit a "redefinition" error if we encounter a
1580 /// correctly named definition after the renamed definition.
1581 llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions;
1582
1583 /// Stack of types that correspond to the parameter entities that are
1584 /// currently being copy-initialized. Can be empty.
1585 llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes;
1586
1587 void ReadMethodPool(Selector Sel);
1588 void updateOutOfDateSelector(Selector Sel);
1589
1590 /// Private Helper predicate to check for 'self'.
1591 bool isSelfExpr(Expr *RExpr);
1592 bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method);
1593
1594 /// Cause the active diagnostic on the DiagosticsEngine to be
1595 /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and
1596 /// should not be used elsewhere.
1597 void EmitCurrentDiagnostic(unsigned DiagID);
1598
1599 /// Records and restores the CurFPFeatures state on entry/exit of compound
1600 /// statements.
1601 class FPFeaturesStateRAII {
1602 public:
1603 FPFeaturesStateRAII(Sema &S);
1604 ~FPFeaturesStateRAII();
1605 FPOptionsOverride getOverrides() { return OldOverrides; }
1606
1607 private:
1608 Sema& S;
1609 FPOptions OldFPFeaturesState;
1610 FPOptionsOverride OldOverrides;
1611 LangOptions::FPEvalMethodKind OldEvalMethod;
1612 SourceLocation OldFPPragmaLocation;
1613 };
1614
1615 void addImplicitTypedef(StringRef Name, QualType T);
1616
1617 bool WarnedStackExhausted = false;
1618
1619 /// Increment when we find a reference; decrement when we find an ignored
1620 /// assignment. Ultimately the value is 0 if every reference is an ignored
1621 /// assignment.
1622 llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments;
1623
1624 /// Indicate RISC-V vector builtin functions enabled or not.
1625 bool DeclareRISCVVBuiltins = false;
1626
1627 /// Indicate RISC-V Sifive vector builtin functions enabled or not.
1628 bool DeclareRISCVVectorBuiltins = false;
1629
1630private:
1631 std::unique_ptr<sema::RISCVIntrinsicManager> RVIntrinsicManager;
1632
1633 std::optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo;
1634
1635 bool WarnedDarwinSDKInfoMissing = false;
1636
1637public:
1638 Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer,
1639 TranslationUnitKind TUKind = TU_Complete,
1640 CodeCompleteConsumer *CompletionConsumer = nullptr);
1641 ~Sema();
1642
1643 /// Perform initialization that occurs after the parser has been
1644 /// initialized but before it parses anything.
1645 void Initialize();
1646
1647 /// This virtual key function only exists to limit the emission of debug info
1648 /// describing the Sema class. GCC and Clang only emit debug info for a class
1649 /// with a vtable when the vtable is emitted. Sema is final and not
1650 /// polymorphic, but the debug info size savings are so significant that it is
1651 /// worth adding a vtable just to take advantage of this optimization.
1652 virtual void anchor();
1653
1654 const LangOptions &getLangOpts() const { return LangOpts; }
1655 OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; }
1656 FPOptions &getCurFPFeatures() { return CurFPFeatures; }
1657
1658 DiagnosticsEngine &getDiagnostics() const { return Diags; }
1659 SourceManager &getSourceManager() const { return SourceMgr; }
1660 Preprocessor &getPreprocessor() const { return PP; }
1661 ASTContext &getASTContext() const { return Context; }
1662 ASTConsumer &getASTConsumer() const { return Consumer; }
1663 ASTMutationListener *getASTMutationListener() const;
1664 ExternalSemaSource *getExternalSource() const { return ExternalSource.get(); }
1665
1666 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc,
1667 StringRef Platform);
1668 DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking();
1669
1670 ///Registers an external source. If an external source already exists,
1671 /// creates a multiplex external source and appends to it.
1672 ///
1673 ///\param[in] E - A non-null external sema source.
1674 ///
1675 void addExternalSource(ExternalSemaSource *E);
1676
1677 void PrintStats() const;
1678
1679 /// Warn that the stack is nearly exhausted.
1680 void warnStackExhausted(SourceLocation Loc);
1681
1682 /// Run some code with "sufficient" stack space. (Currently, at least 256K is
1683 /// guaranteed). Produces a warning if we're low on stack space and allocates
1684 /// more in that case. Use this in code that may recurse deeply (for example,
1685 /// in template instantiation) to avoid stack overflow.
1686 void runWithSufficientStackSpace(SourceLocation Loc,
1687 llvm::function_ref<void()> Fn);
1688
1689 /// Helper class that creates diagnostics with optional
1690 /// template instantiation stacks.
1691 ///
1692 /// This class provides a wrapper around the basic DiagnosticBuilder
1693 /// class that emits diagnostics. ImmediateDiagBuilder is
1694 /// responsible for emitting the diagnostic (as DiagnosticBuilder
1695 /// does) and, if the diagnostic comes from inside a template
1696 /// instantiation, printing the template instantiation stack as
1697 /// well.
1698 class ImmediateDiagBuilder : public DiagnosticBuilder {
1699 Sema &SemaRef;
1700 unsigned DiagID;
1701
1702 public:
1703 ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID)
1704 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1705 ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID)
1706 : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {}
1707
1708 // This is a cunning lie. DiagnosticBuilder actually performs move
1709 // construction in its copy constructor (but due to varied uses, it's not
1710 // possible to conveniently express this as actual move construction). So
1711 // the default copy ctor here is fine, because the base class disables the
1712 // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op
1713 // in that case anwyay.
1714 ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default;
1715
1716 ~ImmediateDiagBuilder() {
1717 // If we aren't active, there is nothing to do.
1718 if (!isActive()) return;
1719
1720 // Otherwise, we need to emit the diagnostic. First clear the diagnostic
1721 // builder itself so it won't emit the diagnostic in its own destructor.
1722 //
1723 // This seems wasteful, in that as written the DiagnosticBuilder dtor will
1724 // do its own needless checks to see if the diagnostic needs to be
1725 // emitted. However, because we take care to ensure that the builder
1726 // objects never escape, a sufficiently smart compiler will be able to
1727 // eliminate that code.
1728 Clear();
1729
1730 // Dispatch to Sema to emit the diagnostic.
1731 SemaRef.EmitCurrentDiagnostic(DiagID);
1732 }
1733
1734 /// Teach operator<< to produce an object of the correct type.
1735 template <typename T>
1736 friend const ImmediateDiagBuilder &
1737 operator<<(const ImmediateDiagBuilder &Diag, const T &Value) {
1738 const DiagnosticBuilder &BaseDiag = Diag;
1739 BaseDiag << Value;
1740 return Diag;
1741 }
1742
1743 // It is necessary to limit this to rvalue reference to avoid calling this
1744 // function with a bitfield lvalue argument since non-const reference to
1745 // bitfield is not allowed.
1746 template <typename T,
1747 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1748 const ImmediateDiagBuilder &operator<<(T &&V) const {
1749 const DiagnosticBuilder &BaseDiag = *this;
1750 BaseDiag << std::move(V);
1751 return *this;
1752 }
1753 };
1754
1755 /// A generic diagnostic builder for errors which may or may not be deferred.
1756 ///
1757 /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch)
1758 /// which are not allowed to appear inside __device__ functions and are
1759 /// allowed to appear in __host__ __device__ functions only if the host+device
1760 /// function is never codegen'ed.
1761 ///
1762 /// To handle this, we use the notion of "deferred diagnostics", where we
1763 /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed.
1764 ///
1765 /// This class lets you emit either a regular diagnostic, a deferred
1766 /// diagnostic, or no diagnostic at all, according to an argument you pass to
1767 /// its constructor, thus simplifying the process of creating these "maybe
1768 /// deferred" diagnostics.
1769 class SemaDiagnosticBuilder {
1770 public:
1771 enum Kind {
1772 /// Emit no diagnostics.
1773 K_Nop,
1774 /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()).
1775 K_Immediate,
1776 /// Emit the diagnostic immediately, and, if it's a warning or error, also
1777 /// emit a call stack showing how this function can be reached by an a
1778 /// priori known-emitted function.
1779 K_ImmediateWithCallStack,
1780 /// Create a deferred diagnostic, which is emitted only if the function
1781 /// it's attached to is codegen'ed. Also emit a call stack as with
1782 /// K_ImmediateWithCallStack.
1783 K_Deferred
1784 };
1785
1786 SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID,
1787 const FunctionDecl *Fn, Sema &S);
1788 SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D);
1789 SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default;
1790 ~SemaDiagnosticBuilder();
1791
1792 bool isImmediate() const { return ImmediateDiag.has_value(); }
1793
1794 /// Convertible to bool: True if we immediately emitted an error, false if
1795 /// we didn't emit an error or we created a deferred error.
1796 ///
1797 /// Example usage:
1798 ///
1799 /// if (SemaDiagnosticBuilder(...) << foo << bar)
1800 /// return ExprError();
1801 ///
1802 /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably
1803 /// want to use these instead of creating a SemaDiagnosticBuilder yourself.
1804 operator bool() const { return isImmediate(); }
1805
1806 template <typename T>
1807 friend const SemaDiagnosticBuilder &
1808 operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) {
1809 if (Diag.ImmediateDiag)
1810 *Diag.ImmediateDiag << Value;
1811 else if (Diag.PartialDiagId)
1812 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second
1813 << Value;
1814 return Diag;
1815 }
1816
1817 // It is necessary to limit this to rvalue reference to avoid calling this
1818 // function with a bitfield lvalue argument since non-const reference to
1819 // bitfield is not allowed.
1820 template <typename T,
1821 typename = std::enable_if_t<!std::is_lvalue_reference<T>::value>>
1822 const SemaDiagnosticBuilder &operator<<(T &&V) const {
1823 if (ImmediateDiag)
1824 *ImmediateDiag << std::move(V);
1825 else if (PartialDiagId)
1826 S.DeviceDeferredDiags[Fn][*PartialDiagId].second << std::move(V);
1827 return *this;
1828 }
1829
1830 friend const SemaDiagnosticBuilder &
1831 operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) {
1832 if (Diag.ImmediateDiag)
1833 PD.Emit(*Diag.ImmediateDiag);
1834 else if (Diag.PartialDiagId)
1835 Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId].second = PD;
1836 return Diag;
1837 }
1838
1839 void AddFixItHint(const FixItHint &Hint) const {
1840 if (ImmediateDiag)
1841 ImmediateDiag->AddFixItHint(Hint);
1842 else if (PartialDiagId)
1843 S.DeviceDeferredDiags[Fn][*PartialDiagId].second.AddFixItHint(Hint);
1844 }
1845
1846 friend ExprResult ExprError(const SemaDiagnosticBuilder &) {
1847 return ExprError();
1848 }
1849 friend StmtResult StmtError(const SemaDiagnosticBuilder &) {
1850 return StmtError();
1851 }
1852 operator ExprResult() const { return ExprError(); }
1853 operator StmtResult() const { return StmtError(); }
1854 operator TypeResult() const { return TypeError(); }
1855 operator DeclResult() const { return DeclResult(true); }
1856 operator MemInitResult() const { return MemInitResult(true); }
1857
1858 private:
1859 Sema &S;
1860 SourceLocation Loc;
1861 unsigned DiagID;
1862 const FunctionDecl *Fn;
1863 bool ShowCallStack;
1864
1865 // Invariant: At most one of these Optionals has a value.
1866 // FIXME: Switch these to a Variant once that exists.
1867 std::optional<ImmediateDiagBuilder> ImmediateDiag;
1868 std::optional<unsigned> PartialDiagId;
1869 };
1870
1871 /// Is the last error level diagnostic immediate. This is used to determined
1872 /// whether the next info diagnostic should be immediate.
1873 bool IsLastErrorImmediate = true;
1874
1875 /// Emit a diagnostic.
1876 SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID,
1877 bool DeferHint = false);
1878
1879 /// Emit a partial diagnostic.
1880 SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD,
1881 bool DeferHint = false);
1882
1883 /// Build a partial diagnostic.
1884 PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h
1885
1886 /// Whether deferrable diagnostics should be deferred.
1887 bool DeferDiags = false;
1888
1889 /// RAII class to control scope of DeferDiags.
1890 class DeferDiagsRAII {
1891 Sema &S;
1892 bool SavedDeferDiags = false;
1893
1894 public:
1895 DeferDiagsRAII(Sema &S, bool DeferDiags)
1896 : S(S), SavedDeferDiags(S.DeferDiags) {
1897 S.DeferDiags = DeferDiags;
1898 }
1899 ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; }
1900 };
1901
1902 /// Whether uncompilable error has occurred. This includes error happens
1903 /// in deferred diagnostics.
1904 bool hasUncompilableErrorOccurred() const;
1905
1906 bool findMacroSpelling(SourceLocation &loc, StringRef name);
1907
1908 /// Get a string to suggest for zero-initialization of a type.
1909 std::string
1910 getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const;
1911 std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const;
1912
1913 /// Calls \c Lexer::getLocForEndOfToken()
1914 SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0);
1915
1916 /// Retrieve the module loader associated with the preprocessor.
1917 ModuleLoader &getModuleLoader() const;
1918
1919 /// Invent a new identifier for parameters of abbreviated templates.
1920 IdentifierInfo *
1921 InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName,
1922 unsigned Index);
1923
1924 void emitAndClearUnusedLocalTypedefWarnings();
1925
1926 private:
1927 /// Function or variable declarations to be checked for whether the deferred
1928 /// diagnostics should be emitted.
1929 llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags;
1930
1931 public:
1932 // Emit all deferred diagnostics.
1933 void emitDeferredDiags();
1934
1935 enum TUFragmentKind {
1936 /// The global module fragment, between 'module;' and a module-declaration.
1937 Global,
1938 /// A normal translation unit fragment. For a non-module unit, this is the
1939 /// entire translation unit. Otherwise, it runs from the module-declaration
1940 /// to the private-module-fragment (if any) or the end of the TU (if not).
1941 Normal,
1942 /// The private module fragment, between 'module :private;' and the end of
1943 /// the translation unit.
1944 Private
1945 };
1946
1947 void ActOnStartOfTranslationUnit();
1948 void ActOnEndOfTranslationUnit();
1949 void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind);
1950
1951 void CheckDelegatingCtorCycles();
1952
1953 Scope *getScopeForContext(DeclContext *Ctx);
1954
1955 void PushFunctionScope();
1956 void PushBlockScope(Scope *BlockScope, BlockDecl *Block);
1957 sema::LambdaScopeInfo *PushLambdaScope();
1958
1959 /// This is used to inform Sema what the current TemplateParameterDepth
1960 /// is during Parsing. Currently it is used to pass on the depth
1961 /// when parsing generic lambda 'auto' parameters.
1962 void RecordParsingTemplateParameterDepth(unsigned Depth);
1963
1964 void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD,
1965 RecordDecl *RD, CapturedRegionKind K,
1966 unsigned OpenMPCaptureLevel = 0);
1967
1968 /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short
1969 /// time after they've been popped.
1970 class PoppedFunctionScopeDeleter {
1971 Sema *Self;
1972
1973 public:
1974 explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {}
1975 void operator()(sema::FunctionScopeInfo *Scope) const;
1976 };
1977
1978 using PoppedFunctionScopePtr =
1979 std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>;
1980
1981 PoppedFunctionScopePtr
1982 PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr,
1983 const Decl *D = nullptr,
1984 QualType BlockType = QualType());
1985
1986 sema::FunctionScopeInfo *getCurFunction() const {
1987 return FunctionScopes.empty() ? nullptr : FunctionScopes.back();
13
'?' condition is false
14
Returning pointer, which participates in a condition later
1988 }
1989
1990 sema::FunctionScopeInfo *getEnclosingFunction() const;
1991
1992 void setFunctionHasBranchIntoScope();
1993 void setFunctionHasBranchProtectedScope();
1994 void setFunctionHasIndirectGoto();
1995 void setFunctionHasMustTail();
1996
1997 void PushCompoundScope(bool IsStmtExpr);
1998 void PopCompoundScope();
1999
2000 sema::CompoundScopeInfo &getCurCompoundScope() const;
2001
2002 bool hasAnyUnrecoverableErrorsInThisFunction() const;
2003
2004 /// Retrieve the current block, if any.
2005 sema::BlockScopeInfo *getCurBlock();
2006
2007 /// Get the innermost lambda enclosing the current location, if any. This
2008 /// looks through intervening non-lambda scopes such as local functions and
2009 /// blocks.
2010 sema::LambdaScopeInfo *getEnclosingLambda() const;
2011
2012 /// Retrieve the current lambda scope info, if any.
2013 /// \param IgnoreNonLambdaCapturingScope true if should find the top-most
2014 /// lambda scope info ignoring all inner capturing scopes that are not
2015 /// lambda scopes.
2016 sema::LambdaScopeInfo *
2017 getCurLambda(bool IgnoreNonLambdaCapturingScope = false);
2018
2019 /// Retrieve the current generic lambda info, if any.
2020 sema::LambdaScopeInfo *getCurGenericLambda();
2021
2022 /// Retrieve the current captured region, if any.
2023 sema::CapturedRegionScopeInfo *getCurCapturedRegion();
2024
2025 /// Retrieve the current function, if any, that should be analyzed for
2026 /// potential availability violations.
2027 sema::FunctionScopeInfo *getCurFunctionAvailabilityContext();
2028
2029 /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls
2030 SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; }
2031
2032 /// Called before parsing a function declarator belonging to a function
2033 /// declaration.
2034 void ActOnStartFunctionDeclarationDeclarator(Declarator &D,
2035 unsigned TemplateParameterDepth);
2036
2037 /// Called after parsing a function declarator belonging to a function
2038 /// declaration.
2039 void ActOnFinishFunctionDeclarationDeclarator(Declarator &D);
2040
2041 void ActOnComment(SourceRange Comment);
2042
2043 //===--------------------------------------------------------------------===//
2044 // Type Analysis / Processing: SemaType.cpp.
2045 //
2046
2047 QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs,
2048 const DeclSpec *DS = nullptr);
2049 QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA,
2050 const DeclSpec *DS = nullptr);
2051 QualType BuildPointerType(QualType T,
2052 SourceLocation Loc, DeclarationName Entity);
2053 QualType BuildReferenceType(QualType T, bool LValueRef,
2054 SourceLocation Loc, DeclarationName Entity);
2055 QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2056 Expr *ArraySize, unsigned Quals,
2057 SourceRange Brackets, DeclarationName Entity);
2058 QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc);
2059 QualType BuildExtVectorType(QualType T, Expr *ArraySize,
2060 SourceLocation AttrLoc);
2061 QualType BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns,
2062 SourceLocation AttrLoc);
2063
2064 QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
2065 SourceLocation AttrLoc);
2066
2067 /// Same as above, but constructs the AddressSpace index if not provided.
2068 QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
2069 SourceLocation AttrLoc);
2070
2071 bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc);
2072
2073 bool CheckFunctionReturnType(QualType T, SourceLocation Loc);
2074
2075 /// Build a function type.
2076 ///
2077 /// This routine checks the function type according to C++ rules and
2078 /// under the assumption that the result type and parameter types have
2079 /// just been instantiated from a template. It therefore duplicates
2080 /// some of the behavior of GetTypeForDeclarator, but in a much
2081 /// simpler form that is only suitable for this narrow use case.
2082 ///
2083 /// \param T The return type of the function.
2084 ///
2085 /// \param ParamTypes The parameter types of the function. This array
2086 /// will be modified to account for adjustments to the types of the
2087 /// function parameters.
2088 ///
2089 /// \param Loc The location of the entity whose type involves this
2090 /// function type or, if there is no such entity, the location of the
2091 /// type that will have function type.
2092 ///
2093 /// \param Entity The name of the entity that involves the function
2094 /// type, if known.
2095 ///
2096 /// \param EPI Extra information about the function type. Usually this will
2097 /// be taken from an existing function with the same prototype.
2098 ///
2099 /// \returns A suitable function type, if there are no errors. The
2100 /// unqualified type will always be a FunctionProtoType.
2101 /// Otherwise, returns a NULL type.
2102 QualType BuildFunctionType(QualType T,
2103 MutableArrayRef<QualType> ParamTypes,
2104 SourceLocation Loc, DeclarationName Entity,
2105 const FunctionProtoType::ExtProtoInfo &EPI);
2106
2107 QualType BuildMemberPointerType(QualType T, QualType Class,
2108 SourceLocation Loc,
2109 DeclarationName Entity);
2110 QualType BuildBlockPointerType(QualType T,
2111 SourceLocation Loc, DeclarationName Entity);
2112 QualType BuildParenType(QualType T);
2113 QualType BuildAtomicType(QualType T, SourceLocation Loc);
2114 QualType BuildReadPipeType(QualType T,
2115 SourceLocation Loc);
2116 QualType BuildWritePipeType(QualType T,
2117 SourceLocation Loc);
2118 QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc);
2119
2120 TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S);
2121 TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy);
2122
2123 /// Package the given type and TSI into a ParsedType.
2124 ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo);
2125 DeclarationNameInfo GetNameForDeclarator(Declarator &D);
2126 DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name);
2127 static QualType GetTypeFromParser(ParsedType Ty,
2128 TypeSourceInfo **TInfo = nullptr);
2129 CanThrowResult canThrow(const Stmt *E);
2130 /// Determine whether the callee of a particular function call can throw.
2131 /// E, D and Loc are all optional.
2132 static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D,
2133 SourceLocation Loc = SourceLocation());
2134 const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc,
2135 const FunctionProtoType *FPT);
2136 void UpdateExceptionSpec(FunctionDecl *FD,
2137 const FunctionProtoType::ExceptionSpecInfo &ESI);
2138 bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range);
2139 bool CheckDistantExceptionSpec(QualType T);
2140 bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New);
2141 bool CheckEquivalentExceptionSpec(
2142 const FunctionProtoType *Old, SourceLocation OldLoc,
2143 const FunctionProtoType *New, SourceLocation NewLoc);
2144 bool CheckEquivalentExceptionSpec(
2145 const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID,
2146 const FunctionProtoType *Old, SourceLocation OldLoc,
2147 const FunctionProtoType *New, SourceLocation NewLoc);
2148 bool handlerCanCatch(QualType HandlerType, QualType ExceptionType);
2149 bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID,
2150 const PartialDiagnostic &NestedDiagID,
2151 const PartialDiagnostic &NoteID,
2152 const PartialDiagnostic &NoThrowDiagID,
2153 const FunctionProtoType *Superset,
2154 SourceLocation SuperLoc,
2155 const FunctionProtoType *Subset,
2156 SourceLocation SubLoc);
2157 bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID,
2158 const PartialDiagnostic &NoteID,
2159 const FunctionProtoType *Target,
2160 SourceLocation TargetLoc,
2161 const FunctionProtoType *Source,
2162 SourceLocation SourceLoc);
2163
2164 TypeResult ActOnTypeName(Scope *S, Declarator &D);
2165
2166 /// The parser has parsed the context-sensitive type 'instancetype'
2167 /// in an Objective-C message declaration. Return the appropriate type.
2168 ParsedType ActOnObjCInstanceType(SourceLocation Loc);
2169
2170 /// Abstract class used to diagnose incomplete types.
2171 struct TypeDiagnoser {
2172 TypeDiagnoser() {}
2173
2174 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0;
2175 virtual ~TypeDiagnoser() {}
2176 };
2177
2178 static int getPrintable(int I) { return I; }
2179 static unsigned getPrintable(unsigned I) { return I; }
2180 static bool getPrintable(bool B) { return B; }
2181 static const char * getPrintable(const char *S) { return S; }
2182 static StringRef getPrintable(StringRef S) { return S; }
2183 static const std::string &getPrintable(const std::string &S) { return S; }
2184 static const IdentifierInfo *getPrintable(const IdentifierInfo *II) {
2185 return II;
2186 }
2187 static DeclarationName getPrintable(DeclarationName N) { return N; }
2188 static QualType getPrintable(QualType T) { return T; }
2189 static SourceRange getPrintable(SourceRange R) { return R; }
2190 static SourceRange getPrintable(SourceLocation L) { return L; }
2191 static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); }
2192 static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();}
2193
2194 template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser {
2195 protected:
2196 unsigned DiagID;
2197 std::tuple<const Ts &...> Args;
2198
2199 template <std::size_t... Is>
2200 void emit(const SemaDiagnosticBuilder &DB,
2201 std::index_sequence<Is...>) const {
2202 // Apply all tuple elements to the builder in order.
2203 bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...};
2204 (void)Dummy;
2205 }
2206
2207 public:
2208 BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args)
2209 : TypeDiagnoser(), DiagID(DiagID), Args(Args...) {
2210 assert(DiagID != 0 && "no diagnostic for type diagnoser")(static_cast <bool> (DiagID != 0 && "no diagnostic for type diagnoser"
) ? void (0) : __assert_fail ("DiagID != 0 && \"no diagnostic for type diagnoser\""
, "clang/include/clang/Sema/Sema.h", 2210, __extension__ __PRETTY_FUNCTION__
))
;
2211 }
2212
2213 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2214 const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID);
2215 emit(DB, std::index_sequence_for<Ts...>());
2216 DB << T;
2217 }
2218 };
2219
2220 /// Do a check to make sure \p Name looks like a legal argument for the
2221 /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name
2222 /// is invalid for the given declaration.
2223 ///
2224 /// \p AL is used to provide caret diagnostics in case of a malformed name.
2225 ///
2226 /// \returns true if the name is a valid swift name for \p D, false otherwise.
2227 bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc,
2228 const ParsedAttr &AL, bool IsAsync);
2229
2230 /// A derivative of BoundTypeDiagnoser for which the diagnostic's type
2231 /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless.
2232 /// For example, a diagnostic with no other parameters would generally have
2233 /// the form "...%select{incomplete|sizeless}0 type %1...".
2234 template <typename... Ts>
2235 class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> {
2236 public:
2237 SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args)
2238 : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {}
2239
2240 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
2241 const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID);
2242 this->emit(DB, std::index_sequence_for<Ts...>());
2243 DB << T->isSizelessType() << T;
2244 }
2245 };
2246
2247 enum class CompleteTypeKind {
2248 /// Apply the normal rules for complete types. In particular,
2249 /// treat all sizeless types as incomplete.
2250 Normal,
2251
2252 /// Relax the normal rules for complete types so that they include
2253 /// sizeless built-in types.
2254 AcceptSizeless,
2255
2256 // FIXME: Eventually we should flip the default to Normal and opt in
2257 // to AcceptSizeless rather than opt out of it.
2258 Default = AcceptSizeless
2259 };
2260
2261 enum class AcceptableKind { Visible, Reachable };
2262
2263private:
2264 /// Methods for marking which expressions involve dereferencing a pointer
2265 /// marked with the 'noderef' attribute. Expressions are checked bottom up as
2266 /// they are parsed, meaning that a noderef pointer may not be accessed. For
2267 /// example, in `&*p` where `p` is a noderef pointer, we will first parse the
2268 /// `*p`, but need to check that `address of` is called on it. This requires
2269 /// keeping a container of all pending expressions and checking if the address
2270 /// of them are eventually taken.
2271 void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E);
2272 void CheckAddressOfNoDeref(const Expr *E);
2273 void CheckMemberAccessOfNoDeref(const MemberExpr *E);
2274
2275 bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
2276 CompleteTypeKind Kind, TypeDiagnoser *Diagnoser);
2277
2278 struct ModuleScope {
2279 SourceLocation BeginLoc;
2280 clang::Module *Module = nullptr;
2281 bool ModuleInterface = false;
2282 VisibleModuleSet OuterVisibleModules;
2283 };
2284 /// The modules we're currently parsing.
2285 llvm::SmallVector<ModuleScope, 16> ModuleScopes;
2286
2287 /// For an interface unit, this is the implicitly imported interface unit.
2288 clang::Module *ThePrimaryInterface = nullptr;
2289
2290 /// The explicit global module fragment of the current translation unit.
2291 /// The explicit Global Module Fragment, as specified in C++
2292 /// [module.global.frag].
2293 clang::Module *TheGlobalModuleFragment = nullptr;
2294
2295 /// The implicit global module fragments of the current translation unit.
2296 /// We would only create at most two implicit global module fragments to
2297 /// avoid performance penalties when there are many language linkage
2298 /// exports.
2299 ///
2300 /// The contents in the implicit global module fragment can't be discarded
2301 /// no matter if it is exported or not.
2302 clang::Module *TheImplicitGlobalModuleFragment = nullptr;
2303 clang::Module *TheExportedImplicitGlobalModuleFragment = nullptr;
2304
2305 /// Namespace definitions that we will export when they finish.
2306 llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces;
2307
2308 /// In a C++ standard module, inline declarations require a definition to be
2309 /// present at the end of a definition domain. This set holds the decls to
2310 /// be checked at the end of the TU.
2311 llvm::SmallPtrSet<const FunctionDecl *, 8> PendingInlineFuncDecls;
2312
2313 /// Helper function to judge if we are in module purview.
2314 /// Return false if we are not in a module.
2315 bool isCurrentModulePurview() const {
2316 return getCurrentModule() ? getCurrentModule()->isModulePurview() : false;
2317 }
2318
2319 /// Enter the scope of the explicit global module fragment.
2320 Module *PushGlobalModuleFragment(SourceLocation BeginLoc);
2321 /// Leave the scope of the explicit global module fragment.
2322 void PopGlobalModuleFragment();
2323
2324 /// Enter the scope of an implicit global module fragment.
2325 Module *PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
2326 bool IsExported);
2327 /// Leave the scope of an implicit global module fragment.
2328 void PopImplicitGlobalModuleFragment();
2329
2330 VisibleModuleSet VisibleModules;
2331
2332 /// Cache for module units which is usable for current module.
2333 llvm::DenseSet<const Module *> UsableModuleUnitsCache;
2334
2335 bool isUsableModule(const Module *M);
2336
2337 bool isAcceptableSlow(const NamedDecl *D, AcceptableKind Kind);
2338
2339public:
2340 /// Get the module unit whose scope we are currently within.
2341 Module *getCurrentModule() const {
2342 return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module;
2343 }
2344
2345 /// Is the module scope we are an interface?
2346 bool currentModuleIsInterface() const {
2347 return ModuleScopes.empty() ? false : ModuleScopes.back().ModuleInterface;
2348 }
2349
2350 /// Is the module scope we are in a C++ Header Unit?
2351 bool currentModuleIsHeaderUnit() const {
2352 return ModuleScopes.empty() ? false
2353 : ModuleScopes.back().Module->isHeaderUnit();
2354 }
2355
2356 /// Get the module owning an entity.
2357 Module *getOwningModule(const Decl *Entity) {
2358 return Entity->getOwningModule();
2359 }
2360
2361 /// Make a merged definition of an existing hidden definition \p ND
2362 /// visible at the specified location.
2363 void makeMergedDefinitionVisible(NamedDecl *ND);
2364
2365 bool isModuleVisible(const Module *M, bool ModulePrivate = false);
2366
2367 // When loading a non-modular PCH files, this is used to restore module
2368 // visibility.
2369 void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) {
2370 VisibleModules.setVisible(Mod, ImportLoc);
2371 }
2372
2373 /// Determine whether a declaration is visible to name lookup.
2374 bool isVisible(const NamedDecl *D) {
2375 return D->isUnconditionallyVisible() ||
2376 isAcceptableSlow(D, AcceptableKind::Visible);
2377 }
2378
2379 /// Determine whether a declaration is reachable.
2380 bool isReachable(const NamedDecl *D) {
2381 // All visible declarations are reachable.
2382 return D->isUnconditionallyVisible() ||
2383 isAcceptableSlow(D, AcceptableKind::Reachable);
2384 }
2385
2386 /// Determine whether a declaration is acceptable (visible/reachable).
2387 bool isAcceptable(const NamedDecl *D, AcceptableKind Kind) {
2388 return Kind == AcceptableKind::Visible ? isVisible(D) : isReachable(D);
2389 }
2390
2391 /// Determine whether any declaration of an entity is visible.
2392 bool
2393 hasVisibleDeclaration(const NamedDecl *D,
2394 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2395 return isVisible(D) || hasVisibleDeclarationSlow(D, Modules);
2396 }
2397
2398 bool hasVisibleDeclarationSlow(const NamedDecl *D,
2399 llvm::SmallVectorImpl<Module *> *Modules);
2400 /// Determine whether any declaration of an entity is reachable.
2401 bool
2402 hasReachableDeclaration(const NamedDecl *D,
2403 llvm::SmallVectorImpl<Module *> *Modules = nullptr) {
2404 return isReachable(D) || hasReachableDeclarationSlow(D, Modules);
2405 }
2406 bool hasReachableDeclarationSlow(
2407 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2408
2409 bool hasVisibleMergedDefinition(const NamedDecl *Def);
2410 bool hasMergedDefinitionInCurrentModule(const NamedDecl *Def);
2411
2412 /// Determine if \p D and \p Suggested have a structurally compatible
2413 /// layout as described in C11 6.2.7/1.
2414 bool hasStructuralCompatLayout(Decl *D, Decl *Suggested);
2415
2416 /// Determine if \p D has a visible definition. If not, suggest a declaration
2417 /// that should be made visible to expose the definition.
2418 bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
2419 bool OnlyNeedComplete = false);
2420 bool hasVisibleDefinition(const NamedDecl *D) {
2421 NamedDecl *Hidden;
2422 return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden);
2423 }
2424
2425 /// Determine if \p D has a reachable definition. If not, suggest a
2426 /// declaration that should be made reachable to expose the definition.
2427 bool hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
2428 bool OnlyNeedComplete = false);
2429 bool hasReachableDefinition(NamedDecl *D) {
2430 NamedDecl *Hidden;
2431 return hasReachableDefinition(D, &Hidden);
2432 }
2433
2434 bool hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
2435 AcceptableKind Kind,
2436 bool OnlyNeedComplete = false);
2437 bool hasAcceptableDefinition(NamedDecl *D, AcceptableKind Kind) {
2438 NamedDecl *Hidden;
2439 return hasAcceptableDefinition(D, &Hidden, Kind);
2440 }
2441
2442 /// Determine if the template parameter \p D has a visible default argument.
2443 bool
2444 hasVisibleDefaultArgument(const NamedDecl *D,
2445 llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2446 /// Determine if the template parameter \p D has a reachable default argument.
2447 bool hasReachableDefaultArgument(
2448 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2449 /// Determine if the template parameter \p D has a reachable default argument.
2450 bool hasAcceptableDefaultArgument(const NamedDecl *D,
2451 llvm::SmallVectorImpl<Module *> *Modules,
2452 Sema::AcceptableKind Kind);
2453
2454 /// Determine if there is a visible declaration of \p D that is an explicit
2455 /// specialization declaration for a specialization of a template. (For a
2456 /// member specialization, use hasVisibleMemberSpecialization.)
2457 bool hasVisibleExplicitSpecialization(
2458 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2459 /// Determine if there is a reachable declaration of \p D that is an explicit
2460 /// specialization declaration for a specialization of a template. (For a
2461 /// member specialization, use hasReachableMemberSpecialization.)
2462 bool hasReachableExplicitSpecialization(
2463 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2464
2465 /// Determine if there is a visible declaration of \p D that is a member
2466 /// specialization declaration (as opposed to an instantiated declaration).
2467 bool hasVisibleMemberSpecialization(
2468 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2469 /// Determine if there is a reachable declaration of \p D that is a member
2470 /// specialization declaration (as opposed to an instantiated declaration).
2471 bool hasReachableMemberSpecialization(
2472 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr);
2473
2474 /// Determine if \p A and \p B are equivalent internal linkage declarations
2475 /// from different modules, and thus an ambiguity error can be downgraded to
2476 /// an extension warning.
2477 bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
2478 const NamedDecl *B);
2479 void diagnoseEquivalentInternalLinkageDeclarations(
2480 SourceLocation Loc, const NamedDecl *D,
2481 ArrayRef<const NamedDecl *> Equiv);
2482
2483 bool isUsualDeallocationFunction(const CXXMethodDecl *FD);
2484
2485 // Check whether the size of array element of type \p EltTy is a multiple of
2486 // its alignment and return false if it isn't.
2487 bool checkArrayElementAlignment(QualType EltTy, SourceLocation Loc);
2488
2489 bool isCompleteType(SourceLocation Loc, QualType T,
2490 CompleteTypeKind Kind = CompleteTypeKind::Default) {
2491 return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr);
2492 }
2493 bool RequireCompleteType(SourceLocation Loc, QualType T,
2494 CompleteTypeKind Kind, TypeDiagnoser &Diagnoser);
2495 bool RequireCompleteType(SourceLocation Loc, QualType T,
2496 CompleteTypeKind Kind, unsigned DiagID);
2497
2498 bool RequireCompleteType(SourceLocation Loc, QualType T,
2499 TypeDiagnoser &Diagnoser) {
2500 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser);
2501 }
2502 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) {
2503 return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID);
2504 }
2505
2506 template <typename... Ts>
2507 bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID,
2508 const Ts &...Args) {
2509 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2510 return RequireCompleteType(Loc, T, Diagnoser);
2511 }
2512
2513 template <typename... Ts>
2514 bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID,
2515 const Ts &... Args) {
2516 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2517 return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser);
2518 }
2519
2520 /// Get the type of expression E, triggering instantiation to complete the
2521 /// type if necessary -- that is, if the expression refers to a templated
2522 /// static data member of incomplete array type.
2523 ///
2524 /// May still return an incomplete type if instantiation was not possible or
2525 /// if the type is incomplete for a different reason. Use
2526 /// RequireCompleteExprType instead if a diagnostic is expected for an
2527 /// incomplete expression type.
2528 QualType getCompletedType(Expr *E);
2529
2530 void completeExprArrayBound(Expr *E);
2531 bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
2532 TypeDiagnoser &Diagnoser);
2533 bool RequireCompleteExprType(Expr *E, unsigned DiagID);
2534
2535 template <typename... Ts>
2536 bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) {
2537 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2538 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
2539 }
2540
2541 template <typename... Ts>
2542 bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID,
2543 const Ts &... Args) {
2544 SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2545 return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser);
2546 }
2547
2548 bool RequireLiteralType(SourceLocation Loc, QualType T,
2549 TypeDiagnoser &Diagnoser);
2550 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID);
2551
2552 template <typename... Ts>
2553 bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID,
2554 const Ts &...Args) {
2555 BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...);
2556 return RequireLiteralType(Loc, T, Diagnoser);
2557 }
2558
2559 QualType getElaboratedType(ElaboratedTypeKeyword Keyword,
2560 const CXXScopeSpec &SS, QualType T,
2561 TagDecl *OwnedTagDecl = nullptr);
2562
2563 // Returns the underlying type of a decltype with the given expression.
2564 QualType getDecltypeForExpr(Expr *E);
2565
2566 QualType BuildTypeofExprType(Expr *E, TypeOfKind Kind);
2567 /// If AsUnevaluated is false, E is treated as though it were an evaluated
2568 /// context, such as when building a type for decltype(auto).
2569 QualType BuildDecltypeType(Expr *E, bool AsUnevaluated = true);
2570
2571 using UTTKind = UnaryTransformType::UTTKind;
2572 QualType BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
2573 SourceLocation Loc);
2574 QualType BuiltinEnumUnderlyingType(QualType BaseType, SourceLocation Loc);
2575 QualType BuiltinAddPointer(QualType BaseType, SourceLocation Loc);
2576 QualType BuiltinRemovePointer(QualType BaseType, SourceLocation Loc);
2577 QualType BuiltinDecay(QualType BaseType, SourceLocation Loc);
2578 QualType BuiltinAddReference(QualType BaseType, UTTKind UKind,
2579 SourceLocation Loc);
2580 QualType BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
2581 SourceLocation Loc);
2582 QualType BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
2583 SourceLocation Loc);
2584 QualType BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
2585 SourceLocation Loc);
2586 QualType BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
2587 SourceLocation Loc);
2588
2589 //===--------------------------------------------------------------------===//
2590 // Symbol table / Decl tracking callbacks: SemaDecl.cpp.
2591 //
2592
2593 struct SkipBodyInfo {
2594 SkipBodyInfo() = default;
2595 bool ShouldSkip = false;
2596 bool CheckSameAsPrevious = false;
2597 NamedDecl *Previous = nullptr;
2598 NamedDecl *New = nullptr;
2599 };
2600
2601 DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr);
2602
2603 void DiagnoseUseOfUnimplementedSelectors();
2604
2605 bool isSimpleTypeSpecifier(tok::TokenKind Kind) const;
2606
2607 ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
2608 Scope *S, CXXScopeSpec *SS = nullptr,
2609 bool isClassName = false, bool HasTrailingDot = false,
2610 ParsedType ObjectType = nullptr,
2611 bool IsCtorOrDtorName = false,
2612 bool WantNontrivialTypeSourceInfo = false,
2613 bool IsClassTemplateDeductionContext = true,
2614 ImplicitTypenameContext AllowImplicitTypename =
2615 ImplicitTypenameContext::No,
2616 IdentifierInfo **CorrectedII = nullptr);
2617 TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S);
2618 bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S);
2619 void DiagnoseUnknownTypeName(IdentifierInfo *&II,
2620 SourceLocation IILoc,
2621 Scope *S,
2622 CXXScopeSpec *SS,
2623 ParsedType &SuggestedType,
2624 bool IsTemplateName = false);
2625
2626 /// Attempt to behave like MSVC in situations where lookup of an unqualified
2627 /// type name has failed in a dependent context. In these situations, we
2628 /// automatically form a DependentTypeName that will retry lookup in a related
2629 /// scope during instantiation.
2630 ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
2631 SourceLocation NameLoc,
2632 bool IsTemplateTypeArg);
2633
2634 /// Describes the result of the name lookup and resolution performed
2635 /// by \c ClassifyName().
2636 enum NameClassificationKind {
2637 /// This name is not a type or template in this context, but might be
2638 /// something else.
2639 NC_Unknown,
2640 /// Classification failed; an error has been produced.
2641 NC_Error,
2642 /// The name has been typo-corrected to a keyword.
2643 NC_Keyword,
2644 /// The name was classified as a type.
2645 NC_Type,
2646 /// The name was classified as a specific non-type, non-template
2647 /// declaration. ActOnNameClassifiedAsNonType should be called to
2648 /// convert the declaration to an expression.
2649 NC_NonType,
2650 /// The name was classified as an ADL-only function name.
2651 /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the
2652 /// result to an expression.
2653 NC_UndeclaredNonType,
2654 /// The name denotes a member of a dependent type that could not be
2655 /// resolved. ActOnNameClassifiedAsDependentNonType should be called to
2656 /// convert the result to an expression.
2657 NC_DependentNonType,
2658 /// The name was classified as an overload set, and an expression
2659 /// representing that overload set has been formed.
2660 /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable
2661 /// expression referencing the overload set.
2662 NC_OverloadSet,
2663 /// The name was classified as a template whose specializations are types.
2664 NC_TypeTemplate,
2665 /// The name was classified as a variable template name.
2666 NC_VarTemplate,
2667 /// The name was classified as a function template name.
2668 NC_FunctionTemplate,
2669 /// The name was classified as an ADL-only function template name.
2670 NC_UndeclaredTemplate,
2671 /// The name was classified as a concept name.
2672 NC_Concept,
2673 };
2674
2675 class NameClassification {
2676 NameClassificationKind Kind;
2677 union {
2678 ExprResult Expr;
2679 NamedDecl *NonTypeDecl;
2680 TemplateName Template;
2681 ParsedType Type;
2682 };
2683
2684 explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {}
2685
2686 public:
2687 NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {}
2688
2689 NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {}
2690
2691 static NameClassification Error() {
2692 return NameClassification(NC_Error);
2693 }
2694
2695 static NameClassification Unknown() {
2696 return NameClassification(NC_Unknown);
2697 }
2698
2699 static NameClassification OverloadSet(ExprResult E) {
2700 NameClassification Result(NC_OverloadSet);
2701 Result.Expr = E;
2702 return Result;
2703 }
2704
2705 static NameClassification NonType(NamedDecl *D) {
2706 NameClassification Result(NC_NonType);
2707 Result.NonTypeDecl = D;
2708 return Result;
2709 }
2710
2711 static NameClassification UndeclaredNonType() {
2712 return NameClassification(NC_UndeclaredNonType);
2713 }
2714
2715 static NameClassification DependentNonType() {
2716 return NameClassification(NC_DependentNonType);
2717 }
2718
2719 static NameClassification TypeTemplate(TemplateName Name) {
2720 NameClassification Result(NC_TypeTemplate);
2721 Result.Template = Name;
2722 return Result;
2723 }
2724
2725 static NameClassification VarTemplate(TemplateName Name) {
2726 NameClassification Result(NC_VarTemplate);
2727 Result.Template = Name;
2728 return Result;
2729 }
2730
2731 static NameClassification FunctionTemplate(TemplateName Name) {
2732 NameClassification Result(NC_FunctionTemplate);
2733 Result.Template = Name;
2734 return Result;
2735 }
2736
2737 static NameClassification Concept(TemplateName Name) {
2738 NameClassification Result(NC_Concept);
2739 Result.Template = Name;
2740 return Result;
2741 }
2742
2743 static NameClassification UndeclaredTemplate(TemplateName Name) {
2744 NameClassification Result(NC_UndeclaredTemplate);
2745 Result.Template = Name;
2746 return Result;
2747 }
2748
2749 NameClassificationKind getKind() const { return Kind; }
2750
2751 ExprResult getExpression() const {
2752 assert(Kind == NC_OverloadSet)(static_cast <bool> (Kind == NC_OverloadSet) ? void (0)
: __assert_fail ("Kind == NC_OverloadSet", "clang/include/clang/Sema/Sema.h"
, 2752, __extension__ __PRETTY_FUNCTION__))
;
2753 return Expr;
2754 }
2755
2756 ParsedType getType() const {
2757 assert(Kind == NC_Type)(static_cast <bool> (Kind == NC_Type) ? void (0) : __assert_fail
("Kind == NC_Type", "clang/include/clang/Sema/Sema.h", 2757,
__extension__ __PRETTY_FUNCTION__))
;
2758 return Type;
2759 }
2760
2761 NamedDecl *getNonTypeDecl() const {
2762 assert(Kind == NC_NonType)(static_cast <bool> (Kind == NC_NonType) ? void (0) : __assert_fail
("Kind == NC_NonType", "clang/include/clang/Sema/Sema.h", 2762
, __extension__ __PRETTY_FUNCTION__))
;
2763 return NonTypeDecl;
2764 }
2765
2766 TemplateName getTemplateName() const {
2767 assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2769, __extension__ __PRETTY_FUNCTION__
))
2768 Kind == NC_VarTemplate || Kind == NC_Concept ||(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2769, __extension__ __PRETTY_FUNCTION__
))
2769 Kind == NC_UndeclaredTemplate)(static_cast <bool> (Kind == NC_TypeTemplate || Kind ==
NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept
|| Kind == NC_UndeclaredTemplate) ? void (0) : __assert_fail
("Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate"
, "clang/include/clang/Sema/Sema.h", 2769, __extension__ __PRETTY_FUNCTION__
))
;
2770 return Template;
2771 }
2772
2773 TemplateNameKind getTemplateNameKind() const {
2774 switch (Kind) {
2775 case NC_TypeTemplate:
2776 return TNK_Type_template;
2777 case NC_FunctionTemplate:
2778 return TNK_Function_template;
2779 case NC_VarTemplate:
2780 return TNK_Var_template;
2781 case NC_Concept:
2782 return TNK_Concept_template;
2783 case NC_UndeclaredTemplate:
2784 return TNK_Undeclared_template;
2785 default:
2786 llvm_unreachable("unsupported name classification.")::llvm::llvm_unreachable_internal("unsupported name classification."
, "clang/include/clang/Sema/Sema.h", 2786)
;
2787 }
2788 }
2789 };
2790
2791 /// Perform name lookup on the given name, classifying it based on
2792 /// the results of name lookup and the following token.
2793 ///
2794 /// This routine is used by the parser to resolve identifiers and help direct
2795 /// parsing. When the identifier cannot be found, this routine will attempt
2796 /// to correct the typo and classify based on the resulting name.
2797 ///
2798 /// \param S The scope in which we're performing name lookup.
2799 ///
2800 /// \param SS The nested-name-specifier that precedes the name.
2801 ///
2802 /// \param Name The identifier. If typo correction finds an alternative name,
2803 /// this pointer parameter will be updated accordingly.
2804 ///
2805 /// \param NameLoc The location of the identifier.
2806 ///
2807 /// \param NextToken The token following the identifier. Used to help
2808 /// disambiguate the name.
2809 ///
2810 /// \param CCC The correction callback, if typo correction is desired.
2811 NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS,
2812 IdentifierInfo *&Name, SourceLocation NameLoc,
2813 const Token &NextToken,
2814 CorrectionCandidateCallback *CCC = nullptr);
2815
2816 /// Act on the result of classifying a name as an undeclared (ADL-only)
2817 /// non-type declaration.
2818 ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name,
2819 SourceLocation NameLoc);
2820 /// Act on the result of classifying a name as an undeclared member of a
2821 /// dependent base class.
2822 ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS,
2823 IdentifierInfo *Name,
2824 SourceLocation NameLoc,
2825 bool IsAddressOfOperand);
2826 /// Act on the result of classifying a name as a specific non-type
2827 /// declaration.
2828 ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS,
2829 NamedDecl *Found,
2830 SourceLocation NameLoc,
2831 const Token &NextToken);
2832 /// Act on the result of classifying a name as an overload set.
2833 ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet);
2834
2835 /// Describes the detailed kind of a template name. Used in diagnostics.
2836 enum class TemplateNameKindForDiagnostics {
2837 ClassTemplate,
2838 FunctionTemplate,
2839 VarTemplate,
2840 AliasTemplate,
2841 TemplateTemplateParam,
2842 Concept,
2843 DependentTemplate
2844 };
2845 TemplateNameKindForDiagnostics
2846 getTemplateNameKindForDiagnostics(TemplateName Name);
2847
2848 /// Determine whether it's plausible that E was intended to be a
2849 /// template-name.
2850 bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) {
2851 if (!getLangOpts().CPlusPlus || E.isInvalid())
2852 return false;
2853 Dependent = false;
2854 if (auto *DRE = dyn_cast<DeclRefExpr>(E.get()))
2855 return !DRE->hasExplicitTemplateArgs();
2856 if (auto *ME = dyn_cast<MemberExpr>(E.get()))
2857 return !ME->hasExplicitTemplateArgs();
2858 Dependent = true;
2859 if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get()))
2860 return !DSDRE->hasExplicitTemplateArgs();
2861 if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get()))
2862 return !DSME->hasExplicitTemplateArgs();
2863 // Any additional cases recognized here should also be handled by
2864 // diagnoseExprIntendedAsTemplateName.
2865 return false;
2866 }
2867 void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName,
2868 SourceLocation Less,
2869 SourceLocation Greater);
2870
2871 void warnOnReservedIdentifier(const NamedDecl *D);
2872
2873 Decl *ActOnDeclarator(Scope *S, Declarator &D);
2874
2875 NamedDecl *HandleDeclarator(Scope *S, Declarator &D,
2876 MultiTemplateParamsArg TemplateParameterLists);
2877 bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo,
2878 QualType &T, SourceLocation Loc,
2879 unsigned FailedFoldDiagID);
2880 void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S);
2881 bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info);
2882 bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
2883 DeclarationName Name, SourceLocation Loc,
2884 bool IsTemplateId);
2885 void
2886 diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2887 SourceLocation FallbackLoc,
2888 SourceLocation ConstQualLoc = SourceLocation(),
2889 SourceLocation VolatileQualLoc = SourceLocation(),
2890 SourceLocation RestrictQualLoc = SourceLocation(),
2891 SourceLocation AtomicQualLoc = SourceLocation(),
2892 SourceLocation UnalignedQualLoc = SourceLocation());
2893
2894 static bool adjustContextForLocalExternDecl(DeclContext *&DC);
2895 void DiagnoseFunctionSpecifiers(const DeclSpec &DS);
2896 NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D,
2897 const LookupResult &R);
2898 NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R);
2899 NamedDecl *getShadowedDeclaration(const BindingDecl *D,
2900 const LookupResult &R);
2901 void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
2902 const LookupResult &R);
2903 void CheckShadow(Scope *S, VarDecl *D);
2904
2905 /// Warn if 'E', which is an expression that is about to be modified, refers
2906 /// to a shadowing declaration.
2907 void CheckShadowingDeclModification(Expr *E, SourceLocation Loc);
2908
2909 void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI);
2910
2911private:
2912 /// Map of current shadowing declarations to shadowed declarations. Warn if
2913 /// it looks like the user is trying to modify the shadowing declaration.
2914 llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls;
2915
2916public:
2917 void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange);
2918 void handleTagNumbering(const TagDecl *Tag, Scope *TagScope);
2919 void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
2920 TypedefNameDecl *NewTD);
2921 void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D);
2922 NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2923 TypeSourceInfo *TInfo,
2924 LookupResult &Previous);
2925 NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D,
2926 LookupResult &Previous, bool &Redeclaration);
2927 NamedDecl *ActOnVariableDeclarator(
2928 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
2929 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
2930 bool &AddToScope, ArrayRef<BindingDecl *> Bindings = std::nullopt);
2931 NamedDecl *
2932 ActOnDecompositionDeclarator(Scope *S, Declarator &D,
2933 MultiTemplateParamsArg TemplateParamLists);
2934 // Returns true if the variable declaration is a redeclaration
2935 bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous);
2936 void CheckVariableDeclarationType(VarDecl *NewVD);
2937 bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
2938 Expr *Init);
2939 void CheckCompleteVariableDeclaration(VarDecl *VD);
2940 void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD);
2941 void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D);
2942
2943 NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
2944 TypeSourceInfo *TInfo,
2945 LookupResult &Previous,
2946 MultiTemplateParamsArg TemplateParamLists,
2947 bool &AddToScope);
2948 bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD);
2949
2950 enum class CheckConstexprKind {
2951 /// Diagnose issues that are non-constant or that are extensions.
2952 Diagnose,
2953 /// Identify whether this function satisfies the formal rules for constexpr
2954 /// functions in the current lanugage mode (with no extensions).
2955 CheckValid
2956 };
2957
2958 bool CheckConstexprFunctionDefinition(const FunctionDecl *FD,
2959 CheckConstexprKind Kind);
2960
2961 void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD);
2962 void FindHiddenVirtualMethods(CXXMethodDecl *MD,
2963 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2964 void NoteHiddenVirtualMethods(CXXMethodDecl *MD,
2965 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods);
2966 // Returns true if the function declaration is a redeclaration
2967 bool CheckFunctionDeclaration(Scope *S,
2968 FunctionDecl *NewFD, LookupResult &Previous,
2969 bool IsMemberSpecialization, bool DeclIsDefn);
2970 bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl);
2971 bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD,
2972 QualType NewT, QualType OldT);
2973 void CheckMain(FunctionDecl *FD, const DeclSpec &D);
2974 void CheckMSVCRTEntryPoint(FunctionDecl *FD);
2975 void CheckHLSLEntryPoint(FunctionDecl *FD);
2976 Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
2977 bool IsDefinition);
2978 void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D);
2979 Decl *ActOnParamDeclarator(Scope *S, Declarator &D);
2980 ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC,
2981 SourceLocation Loc,
2982 QualType T);
2983 ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc,
2984 SourceLocation NameLoc, IdentifierInfo *Name,
2985 QualType T, TypeSourceInfo *TSInfo,
2986 StorageClass SC);
2987 void ActOnParamDefaultArgument(Decl *param,
2988 SourceLocation EqualLoc,
2989 Expr *defarg);
2990 void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc,
2991 SourceLocation ArgLoc);
2992 void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc);
2993 ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2994 SourceLocation EqualLoc);
2995 void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg,
2996 SourceLocation EqualLoc);
2997
2998 // Contexts where using non-trivial C union types can be disallowed. This is
2999 // passed to err_non_trivial_c_union_in_invalid_context.
3000 enum NonTrivialCUnionContext {
3001 // Function parameter.
3002 NTCUC_FunctionParam,
3003 // Function return.
3004 NTCUC_FunctionReturn,
3005 // Default-initialized object.
3006 NTCUC_DefaultInitializedObject,
3007 // Variable with automatic storage duration.
3008 NTCUC_AutoVar,
3009 // Initializer expression that might copy from another object.
3010 NTCUC_CopyInit,
3011 // Assignment.
3012 NTCUC_Assignment,
3013 // Compound literal.
3014 NTCUC_CompoundLiteral,
3015 // Block capture.
3016 NTCUC_BlockCapture,
3017 // lvalue-to-rvalue conversion of volatile type.
3018 NTCUC_LValueToRValueVolatile,
3019 };
3020
3021 /// Emit diagnostics if the initializer or any of its explicit or
3022 /// implicitly-generated subexpressions require copying or
3023 /// default-initializing a type that is or contains a C union type that is
3024 /// non-trivial to copy or default-initialize.
3025 void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc);
3026
3027 // These flags are passed to checkNonTrivialCUnion.
3028 enum NonTrivialCUnionKind {
3029 NTCUK_Init = 0x1,
3030 NTCUK_Destruct = 0x2,
3031 NTCUK_Copy = 0x4,
3032 };
3033
3034 /// Emit diagnostics if a non-trivial C union type or a struct that contains
3035 /// a non-trivial C union is used in an invalid context.
3036 void checkNonTrivialCUnion(QualType QT, SourceLocation Loc,
3037 NonTrivialCUnionContext UseContext,
3038 unsigned NonTrivialKind);
3039
3040 void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit);
3041 void ActOnUninitializedDecl(Decl *dcl);
3042 void ActOnInitializerError(Decl *Dcl);
3043
3044 void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc);
3045 void ActOnCXXForRangeDecl(Decl *D);
3046 StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
3047 IdentifierInfo *Ident,
3048 ParsedAttributes &Attrs);
3049 void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc);
3050 void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc);
3051 void CheckStaticLocalForDllExport(VarDecl *VD);
3052 void CheckThreadLocalForLargeAlignment(VarDecl *VD);
3053 void FinalizeDeclaration(Decl *D);
3054 DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
3055 ArrayRef<Decl *> Group);
3056 DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group);
3057
3058 /// Should be called on all declarations that might have attached
3059 /// documentation comments.
3060 void ActOnDocumentableDecl(Decl *D);
3061 void ActOnDocumentableDecls(ArrayRef<Decl *> Group);
3062
3063 enum class FnBodyKind {
3064 /// C++ [dcl.fct.def.general]p1
3065 /// function-body:
3066 /// ctor-initializer[opt] compound-statement
3067 /// function-try-block
3068 Other,
3069 /// = default ;
3070 Default,
3071 /// = delete ;
3072 Delete
3073 };
3074
3075 void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
3076 SourceLocation LocAfterDecls);
3077 void CheckForFunctionRedefinition(
3078 FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr,
3079 SkipBodyInfo *SkipBody = nullptr);
3080 Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D,
3081 MultiTemplateParamsArg TemplateParamLists,
3082 SkipBodyInfo *SkipBody = nullptr,
3083 FnBodyKind BodyKind = FnBodyKind::Other);
3084 Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D,
3085 SkipBodyInfo *SkipBody = nullptr,
3086 FnBodyKind BodyKind = FnBodyKind::Other);
3087 void SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind);
3088 void ActOnStartTrailingRequiresClause(Scope *S, Declarator &D);
3089 ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr);
3090 ExprResult ActOnRequiresClause(ExprResult ConstraintExpr);
3091 void ActOnStartOfObjCMethodDef(Scope *S, Decl *D);
3092 bool isObjCMethodDecl(Decl *D) {
3093 return D && isa<ObjCMethodDecl>(D);
3094 }
3095
3096 /// Determine whether we can delay parsing the body of a function or
3097 /// function template until it is used, assuming we don't care about emitting
3098 /// code for that function.
3099 ///
3100 /// This will be \c false if we may need the body of the function in the
3101 /// middle of parsing an expression (where it's impractical to switch to
3102 /// parsing a different function), for instance, if it's constexpr in C++11
3103 /// or has an 'auto' return type in C++14. These cases are essentially bugs.
3104 bool canDelayFunctionBody(const Declarator &D);
3105
3106 /// Determine whether we can skip parsing the body of a function
3107 /// definition, assuming we don't care about analyzing its body or emitting
3108 /// code for that function.
3109 ///
3110 /// This will be \c false only if we may need the body of the function in
3111 /// order to parse the rest of the program (for instance, if it is
3112 /// \c constexpr in C++11 or has an 'auto' return type in C++14).
3113 bool canSkipFunctionBody(Decl *D);
3114
3115 /// Determine whether \param D is function like (function or function
3116 /// template) for parsing.
3117 bool isDeclaratorFunctionLike(Declarator &D);
3118
3119 void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope);
3120 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body);
3121 Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation);
3122 Decl *ActOnSkippedFunctionBody(Decl *Decl);
3123 void ActOnFinishInlineFunctionDef(FunctionDecl *D);
3124
3125 /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an
3126 /// attribute for which parsing is delayed.
3127 void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs);
3128
3129 /// Diagnose any unused parameters in the given sequence of
3130 /// ParmVarDecl pointers.
3131 void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters);
3132
3133 /// Diagnose whether the size of parameters or return value of a
3134 /// function or obj-c method definition is pass-by-value and larger than a
3135 /// specified threshold.
3136 void
3137 DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters,
3138 QualType ReturnTy, NamedDecl *D);
3139
3140 void DiagnoseInvalidJumps(Stmt *Body);
3141 Decl *ActOnFileScopeAsmDecl(Expr *expr,
3142 SourceLocation AsmLoc,
3143 SourceLocation RParenLoc);
3144
3145 Decl *ActOnTopLevelStmtDecl(Stmt *Statement);
3146
3147 /// Handle a C++11 empty-declaration and attribute-declaration.
3148 Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList,
3149 SourceLocation SemiLoc);
3150
3151 enum class ModuleDeclKind {
3152 Interface, ///< 'export module X;'
3153 Implementation, ///< 'module X;'
3154 PartitionInterface, ///< 'export module X:Y;'
3155 PartitionImplementation, ///< 'module X:Y;'
3156 };
3157
3158 /// An enumeration to represent the transition of states in parsing module
3159 /// fragments and imports. If we are not parsing a C++20 TU, or we find
3160 /// an error in state transition, the state is set to NotACXX20Module.
3161 enum class ModuleImportState {
3162 FirstDecl, ///< Parsing the first decl in a TU.
3163 GlobalFragment, ///< after 'module;' but before 'module X;'
3164 ImportAllowed, ///< after 'module X;' but before any non-import decl.
3165 ImportFinished, ///< after any non-import decl.
3166 PrivateFragmentImportAllowed, ///< after 'module :private;' but before any
3167 ///< non-import decl.
3168 PrivateFragmentImportFinished, ///< after 'module :private;' but a
3169 ///< non-import decl has already been seen.
3170 NotACXX20Module ///< Not a C++20 TU, or an invalid state was found.
3171 };
3172
3173private:
3174 /// The parser has begun a translation unit to be compiled as a C++20
3175 /// Header Unit, helper for ActOnStartOfTranslationUnit() only.
3176 void HandleStartOfHeaderUnit();
3177
3178public:
3179 /// The parser has processed a module-declaration that begins the definition
3180 /// of a module interface or implementation.
3181 DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc,
3182 SourceLocation ModuleLoc, ModuleDeclKind MDK,
3183 ModuleIdPath Path, ModuleIdPath Partition,
3184 ModuleImportState &ImportState);
3185
3186 /// The parser has processed a global-module-fragment declaration that begins
3187 /// the definition of the global module fragment of the current module unit.
3188 /// \param ModuleLoc The location of the 'module' keyword.
3189 DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc);
3190
3191 /// The parser has processed a private-module-fragment declaration that begins
3192 /// the definition of the private module fragment of the current module unit.
3193 /// \param ModuleLoc The location of the 'module' keyword.
3194 /// \param PrivateLoc The location of the 'private' keyword.
3195 DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
3196 SourceLocation PrivateLoc);
3197
3198 /// The parser has processed a module import declaration.
3199 ///
3200 /// \param StartLoc The location of the first token in the declaration. This
3201 /// could be the location of an '@', 'export', or 'import'.
3202 /// \param ExportLoc The location of the 'export' keyword, if any.
3203 /// \param ImportLoc The location of the 'import' keyword.
3204 /// \param Path The module toplevel name as an access path.
3205 /// \param IsPartition If the name is for a partition.
3206 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3207 SourceLocation ExportLoc,
3208 SourceLocation ImportLoc, ModuleIdPath Path,
3209 bool IsPartition = false);
3210 DeclResult ActOnModuleImport(SourceLocation StartLoc,
3211 SourceLocation ExportLoc,
3212 SourceLocation ImportLoc, Module *M,
3213 ModuleIdPath Path = {});
3214
3215 /// The parser has processed a module import translated from a
3216 /// #include or similar preprocessing directive.
3217 void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3218 void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod);
3219
3220 /// The parsed has entered a submodule.
3221 void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod);
3222 /// The parser has left a submodule.
3223 void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod);
3224
3225 /// Create an implicit import of the given module at the given
3226 /// source location, for error recovery, if possible.
3227 ///
3228 /// This routine is typically used when an entity found by name lookup
3229 /// is actually hidden within a module that we know about but the user
3230 /// has forgotten to import.
3231 void createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
3232 Module *Mod);
3233
3234 /// Kinds of missing import. Note, the values of these enumerators correspond
3235 /// to %select values in diagnostics.
3236 enum class MissingImportKind {
3237 Declaration,
3238 Definition,
3239 DefaultArgument,
3240 ExplicitSpecialization,
3241 PartialSpecialization
3242 };
3243
3244 /// Diagnose that the specified declaration needs to be visible but
3245 /// isn't, and suggest a module import that would resolve the problem.
3246 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3247 MissingImportKind MIK, bool Recover = true);
3248 void diagnoseMissingImport(SourceLocation Loc, const NamedDecl *Decl,
3249 SourceLocation DeclLoc, ArrayRef<Module *> Modules,
3250 MissingImportKind MIK, bool Recover);
3251
3252 Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
3253 SourceLocation LBraceLoc);
3254 Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl,
3255 SourceLocation RBraceLoc);
3256
3257 /// We've found a use of a templated declaration that would trigger an
3258 /// implicit instantiation. Check that any relevant explicit specializations
3259 /// and partial specializations are visible/reachable, and diagnose if not.
3260 void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec);
3261 void checkSpecializationReachability(SourceLocation Loc, NamedDecl *Spec);
3262
3263 /// Retrieve a suitable printing policy for diagnostics.
3264 PrintingPolicy getPrintingPolicy() const {
3265 return getPrintingPolicy(Context, PP);
3266 }
3267
3268 /// Retrieve a suitable printing policy for diagnostics.
3269 static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx,
3270 const Preprocessor &PP);
3271
3272 /// Scope actions.
3273 void ActOnPopScope(SourceLocation Loc, Scope *S);
3274 void ActOnTranslationUnitScope(Scope *S);
3275
3276 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3277 const ParsedAttributesView &DeclAttrs,
3278 RecordDecl *&AnonRecord);
3279 Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3280 const ParsedAttributesView &DeclAttrs,
3281 MultiTemplateParamsArg TemplateParams,
3282 bool IsExplicitInstantiation,
3283 RecordDecl *&AnonRecord);
3284
3285 Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
3286 AccessSpecifier AS,
3287 RecordDecl *Record,
3288 const PrintingPolicy &Policy);
3289
3290 Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
3291 RecordDecl *Record);
3292
3293 /// Common ways to introduce type names without a tag for use in diagnostics.
3294 /// Keep in sync with err_tag_reference_non_tag.
3295 enum NonTagKind {
3296 NTK_NonStruct,
3297 NTK_NonClass,
3298 NTK_NonUnion,
3299 NTK_NonEnum,
3300 NTK_Typedef,
3301 NTK_TypeAlias,
3302 NTK_Template,
3303 NTK_TypeAliasTemplate,
3304 NTK_TemplateTemplateArgument,
3305 };
3306
3307 /// Given a non-tag type declaration, returns an enum useful for indicating
3308 /// what kind of non-tag type this is.
3309 NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK);
3310
3311 bool isAcceptableTagRedeclaration(const TagDecl *Previous,
3312 TagTypeKind NewTag, bool isDefinition,
3313 SourceLocation NewTagLoc,
3314 const IdentifierInfo *Name);
3315
3316 enum TagUseKind {
3317 TUK_Reference, // Reference to a tag: 'struct foo *X;'
3318 TUK_Declaration, // Fwd decl of a tag: 'struct foo;'
3319 TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;'
3320 TUK_Friend // Friend declaration: 'friend struct foo;'
3321 };
3322
3323 enum OffsetOfKind {
3324 // Not parsing a type within __builtin_offsetof.
3325 OOK_Outside,
3326 // Parsing a type within __builtin_offsetof.
3327 OOK_Builtin,
3328 // Parsing a type within macro "offsetof", defined in __buitin_offsetof
3329 // To improve our diagnostic message.
3330 OOK_Macro,
3331 };
3332
3333 DeclResult ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
3334 SourceLocation KWLoc, CXXScopeSpec &SS,
3335 IdentifierInfo *Name, SourceLocation NameLoc,
3336 const ParsedAttributesView &Attr, AccessSpecifier AS,
3337 SourceLocation ModulePrivateLoc,
3338 MultiTemplateParamsArg TemplateParameterLists,
3339 bool &OwnedDecl, bool &IsDependent,
3340 SourceLocation ScopedEnumKWLoc,
3341 bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
3342 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
3343 OffsetOfKind OOK, SkipBodyInfo *SkipBody = nullptr);
3344
3345 DeclResult ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
3346 unsigned TagSpec, SourceLocation TagLoc,
3347 CXXScopeSpec &SS, IdentifierInfo *Name,
3348 SourceLocation NameLoc,
3349 const ParsedAttributesView &Attr,
3350 MultiTemplateParamsArg TempParamLists);
3351
3352 TypeResult ActOnDependentTag(Scope *S,
3353 unsigned TagSpec,
3354 TagUseKind TUK,
3355 const CXXScopeSpec &SS,
3356 IdentifierInfo *Name,
3357 SourceLocation TagLoc,
3358 SourceLocation NameLoc);
3359
3360 void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3361 IdentifierInfo *ClassName,
3362 SmallVectorImpl<Decl *> &Decls);
3363 Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
3364 Declarator &D, Expr *BitfieldWidth);
3365
3366 FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart,
3367 Declarator &D, Expr *BitfieldWidth,
3368 InClassInitStyle InitStyle,
3369 AccessSpecifier AS);
3370 MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD,
3371 SourceLocation DeclStart, Declarator &D,
3372 Expr *BitfieldWidth,
3373 InClassInitStyle InitStyle,
3374 AccessSpecifier AS,
3375 const ParsedAttr &MSPropertyAttr);
3376
3377 FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T,
3378 TypeSourceInfo *TInfo,
3379 RecordDecl *Record, SourceLocation Loc,
3380 bool Mutable, Expr *BitfieldWidth,
3381 InClassInitStyle InitStyle,
3382 SourceLocation TSSL,
3383 AccessSpecifier AS, NamedDecl *PrevDecl,
3384 Declarator *D = nullptr);
3385
3386 bool CheckNontrivialField(FieldDecl *FD);
3387 void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM);
3388
3389 enum TrivialABIHandling {
3390 /// The triviality of a method unaffected by "trivial_abi".
3391 TAH_IgnoreTrivialABI,
3392
3393 /// The triviality of a method affected by "trivial_abi".
3394 TAH_ConsiderTrivialABI
3395 };
3396
3397 bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
3398 TrivialABIHandling TAH = TAH_IgnoreTrivialABI,
3399 bool Diagnose = false);
3400
3401 /// For a defaulted function, the kind of defaulted function that it is.
3402 class DefaultedFunctionKind {
3403 CXXSpecialMember SpecialMember : 8;
3404 DefaultedComparisonKind Comparison : 8;
3405
3406 public:
3407 DefaultedFunctionKind()
3408 : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) {
3409 }
3410 DefaultedFunctionKind(CXXSpecialMember CSM)
3411 : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {}
3412 DefaultedFunctionKind(DefaultedComparisonKind Comp)
3413 : SpecialMember(CXXInvalid), Comparison(Comp) {}
3414
3415 bool isSpecialMember() const { return SpecialMember != CXXInvalid; }
3416 bool isComparison() const {
3417 return Comparison != DefaultedComparisonKind::None;
3418 }
3419
3420 explicit operator bool() const {
3421 return isSpecialMember() || isComparison();
3422 }
3423
3424 CXXSpecialMember asSpecialMember() const { return SpecialMember; }
3425 DefaultedComparisonKind asComparison() const { return Comparison; }
3426
3427 /// Get the index of this function kind for use in diagnostics.
3428 unsigned getDiagnosticIndex() const {
3429 static_assert(CXXInvalid > CXXDestructor,
3430 "invalid should have highest index");
3431 static_assert((unsigned)DefaultedComparisonKind::None == 0,
3432 "none should be equal to zero");
3433 return SpecialMember + (unsigned)Comparison;
3434 }
3435 };
3436
3437 DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD);
3438
3439 CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) {
3440 return getDefaultedFunctionKind(MD).asSpecialMember();
3441 }
3442 DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) {
3443 return getDefaultedFunctionKind(FD).asComparison();
3444 }
3445
3446 void ActOnLastBitfield(SourceLocation DeclStart,
3447 SmallVectorImpl<Decl *> &AllIvarDecls);
3448 Decl *ActOnIvar(Scope *S, SourceLocation DeclStart,
3449 Declarator &D, Expr *BitfieldWidth,
3450 tok::ObjCKeywordKind visibility);
3451
3452 // This is used for both record definitions and ObjC interface declarations.
3453 void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl,
3454 ArrayRef<Decl *> Fields, SourceLocation LBrac,
3455 SourceLocation RBrac, const ParsedAttributesView &AttrList);
3456
3457 /// ActOnTagStartDefinition - Invoked when we have entered the
3458 /// scope of a tag's definition (e.g., for an enumeration, class,
3459 /// struct, or union).
3460 void ActOnTagStartDefinition(Scope *S, Decl *TagDecl);
3461
3462 /// Perform ODR-like check for C/ObjC when merging tag types from modules.
3463 /// Differently from C++, actually parse the body and reject / error out
3464 /// in case of a structural mismatch.
3465 bool ActOnDuplicateDefinition(Decl *Prev, SkipBodyInfo &SkipBody);
3466
3467 /// Check ODR hashes for C/ObjC when merging types from modules.
3468 /// Differently from C++, actually parse the body and reject in case
3469 /// of a mismatch.
3470 template <typename T,
3471 typename = std::enable_if_t<std::is_base_of<NamedDecl, T>::value>>
3472 bool ActOnDuplicateODRHashDefinition(T *Duplicate, T *Previous) {
3473 if (Duplicate->getODRHash() != Previous->getODRHash())
3474 return false;
3475
3476 // Make the previous decl visible.
3477 makeMergedDefinitionVisible(Previous);
3478 return true;
3479 }
3480
3481 typedef void *SkippedDefinitionContext;
3482
3483 /// Invoked when we enter a tag definition that we're skipping.
3484 SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD);
3485
3486 void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl);
3487
3488 /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a
3489 /// C++ record definition's base-specifiers clause and are starting its
3490 /// member declarations.
3491 void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl,
3492 SourceLocation FinalLoc,
3493 bool IsFinalSpelledSealed,
3494 bool IsAbstract,
3495 SourceLocation LBraceLoc);
3496
3497 /// ActOnTagFinishDefinition - Invoked once we have finished parsing
3498 /// the definition of a tag (enumeration, class, struct, or union).
3499 void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl,
3500 SourceRange BraceRange);
3501
3502 void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context);
3503
3504 void ActOnObjCContainerFinishDefinition();
3505
3506 /// Invoked when we must temporarily exit the objective-c container
3507 /// scope for parsing/looking-up C constructs.
3508 ///
3509 /// Must be followed by a call to \see ActOnObjCReenterContainerContext
3510 void ActOnObjCTemporaryExitContainerContext(ObjCContainerDecl *ObjCCtx);
3511 void ActOnObjCReenterContainerContext(ObjCContainerDecl *ObjCCtx);
3512
3513 /// ActOnTagDefinitionError - Invoked when there was an unrecoverable
3514 /// error parsing the definition of a tag.
3515 void ActOnTagDefinitionError(Scope *S, Decl *TagDecl);
3516
3517 EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum,
3518 EnumConstantDecl *LastEnumConst,
3519 SourceLocation IdLoc,
3520 IdentifierInfo *Id,
3521 Expr *val);
3522 bool CheckEnumUnderlyingType(TypeSourceInfo *TI);
3523 bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
3524 QualType EnumUnderlyingTy, bool IsFixed,
3525 const EnumDecl *Prev);
3526
3527 /// Determine whether the body of an anonymous enumeration should be skipped.
3528 /// \param II The name of the first enumerator.
3529 SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
3530 SourceLocation IILoc);
3531
3532 Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant,
3533 SourceLocation IdLoc, IdentifierInfo *Id,
3534 const ParsedAttributesView &Attrs,
3535 SourceLocation EqualLoc, Expr *Val);
3536 void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
3537 Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S,
3538 const ParsedAttributesView &Attr);
3539
3540 /// Set the current declaration context until it gets popped.
3541 void PushDeclContext(Scope *S, DeclContext *DC);
3542 void PopDeclContext();
3543
3544 /// EnterDeclaratorContext - Used when we must lookup names in the context
3545 /// of a declarator's nested name specifier.
3546 void EnterDeclaratorContext(Scope *S, DeclContext *DC);
3547 void ExitDeclaratorContext(Scope *S);
3548
3549 /// Enter a template parameter scope, after it's been associated with a particular
3550 /// DeclContext. Causes lookup within the scope to chain through enclosing contexts
3551 /// in the correct order.
3552 void EnterTemplatedContext(Scope *S, DeclContext *DC);
3553
3554 /// Push the parameters of D, which must be a function, into scope.
3555 void ActOnReenterFunctionContext(Scope* S, Decl* D);
3556 void ActOnExitFunctionContext();
3557
3558 /// If \p AllowLambda is true, treat lambda as function.
3559 DeclContext *getFunctionLevelDeclContext(bool AllowLambda = false) const;
3560
3561 /// Returns a pointer to the innermost enclosing function, or nullptr if the
3562 /// current context is not inside a function. If \p AllowLambda is true,
3563 /// this can return the call operator of an enclosing lambda, otherwise
3564 /// lambdas are skipped when looking for an enclosing function.
3565 FunctionDecl *getCurFunctionDecl(bool AllowLambda = false) const;
3566
3567 /// getCurMethodDecl - If inside of a method body, this returns a pointer to
3568 /// the method decl for the method being parsed. If we're currently
3569 /// in a 'block', this returns the containing context.
3570 ObjCMethodDecl *getCurMethodDecl();
3571
3572 /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method
3573 /// or C function we're in, otherwise return null. If we're currently
3574 /// in a 'block', this returns the containing context.
3575 NamedDecl *getCurFunctionOrMethodDecl() const;
3576
3577 /// Add this decl to the scope shadowed decl chains.
3578 void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true);
3579
3580 /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
3581 /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
3582 /// true if 'D' belongs to the given declaration context.
3583 ///
3584 /// \param AllowInlineNamespace If \c true, allow the declaration to be in the
3585 /// enclosing namespace set of the context, rather than contained
3586 /// directly within it.
3587 bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr,
3588 bool AllowInlineNamespace = false) const;
3589
3590 /// Finds the scope corresponding to the given decl context, if it
3591 /// happens to be an enclosing scope. Otherwise return NULL.
3592 static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC);
3593
3594 /// Subroutines of ActOnDeclarator().
3595 TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
3596 TypeSourceInfo *TInfo);
3597 bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New);
3598
3599 /// Describes the kind of merge to perform for availability
3600 /// attributes (including "deprecated", "unavailable", and "availability").
3601 enum AvailabilityMergeKind {
3602 /// Don't merge availability attributes at all.
3603 AMK_None,
3604 /// Merge availability attributes for a redeclaration, which requires
3605 /// an exact match.
3606 AMK_Redeclaration,
3607 /// Merge availability attributes for an override, which requires
3608 /// an exact match or a weakening of constraints.
3609 AMK_Override,
3610 /// Merge availability attributes for an implementation of
3611 /// a protocol requirement.
3612 AMK_ProtocolImplementation,
3613 /// Merge availability attributes for an implementation of
3614 /// an optional protocol requirement.
3615 AMK_OptionalProtocolImplementation
3616 };
3617
3618 /// Describes the kind of priority given to an availability attribute.
3619 ///
3620 /// The sum of priorities deteremines the final priority of the attribute.
3621 /// The final priority determines how the attribute will be merged.
3622 /// An attribute with a lower priority will always remove higher priority
3623 /// attributes for the specified platform when it is being applied. An
3624 /// attribute with a higher priority will not be applied if the declaration
3625 /// already has an availability attribute with a lower priority for the
3626 /// specified platform. The final prirority values are not expected to match
3627 /// the values in this enumeration, but instead should be treated as a plain
3628 /// integer value. This enumeration just names the priority weights that are
3629 /// used to calculate that final vaue.
3630 enum AvailabilityPriority : int {
3631 /// The availability attribute was specified explicitly next to the
3632 /// declaration.
3633 AP_Explicit = 0,
3634
3635 /// The availability attribute was applied using '#pragma clang attribute'.
3636 AP_PragmaClangAttribute = 1,
3637
3638 /// The availability attribute for a specific platform was inferred from
3639 /// an availability attribute for another platform.
3640 AP_InferredFromOtherPlatform = 2
3641 };
3642
3643 /// Attribute merging methods. Return true if a new attribute was added.
3644 AvailabilityAttr *
3645 mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI,
3646 IdentifierInfo *Platform, bool Implicit,
3647 VersionTuple Introduced, VersionTuple Deprecated,
3648 VersionTuple Obsoleted, bool IsUnavailable,
3649 StringRef Message, bool IsStrict, StringRef Replacement,
3650 AvailabilityMergeKind AMK, int Priority);
3651 TypeVisibilityAttr *
3652 mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3653 TypeVisibilityAttr::VisibilityType Vis);
3654 VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI,
3655 VisibilityAttr::VisibilityType Vis);
3656 UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
3657 StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
3658 DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI);
3659 DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI);
3660 MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D,
3661 const AttributeCommonInfo &CI,
3662 bool BestCase,
3663 MSInheritanceModel Model);
3664 ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI,
3665 StringRef NewUserDiagnostic);
3666 FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI,
3667 IdentifierInfo *Format, int FormatIdx,
3668 int FirstArg);
3669 SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI,
3670 StringRef Name);
3671 CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI,
3672 StringRef Name);
3673 AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D,
3674 const AttributeCommonInfo &CI,
3675 const IdentifierInfo *Ident);
3676 MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI);
3677 SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
3678 StringRef Name);
3679 OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D,
3680 const AttributeCommonInfo &CI);
3681 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL);
3682 InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D,
3683 const InternalLinkageAttr &AL);
3684 WebAssemblyImportNameAttr *mergeImportNameAttr(
3685 Decl *D, const WebAssemblyImportNameAttr &AL);
3686 WebAssemblyImportModuleAttr *mergeImportModuleAttr(
3687 Decl *D, const WebAssemblyImportModuleAttr &AL);
3688 EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL);
3689 EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D,
3690 const EnforceTCBLeafAttr &AL);
3691 BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL);
3692 HLSLNumThreadsAttr *mergeHLSLNumThreadsAttr(Decl *D,
3693 const AttributeCommonInfo &AL,
3694 int X, int Y, int Z);
3695 HLSLShaderAttr *mergeHLSLShaderAttr(Decl *D, const AttributeCommonInfo &AL,
3696 HLSLShaderAttr::ShaderType ShaderType);
3697
3698 void mergeDeclAttributes(NamedDecl *New, Decl *Old,
3699 AvailabilityMergeKind AMK = AMK_Redeclaration);
3700 void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
3701 LookupResult &OldDecls);
3702 bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S,
3703 bool MergeTypeWithOld, bool NewDeclIsDefn);
3704 bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3705 Scope *S, bool MergeTypeWithOld);
3706 void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old);
3707 void MergeVarDecl(VarDecl *New, LookupResult &Previous);
3708 void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld);
3709 void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old);
3710 bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn);
3711 void notePreviousDefinition(const NamedDecl *Old, SourceLocation New);
3712 bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S);
3713
3714 // AssignmentAction - This is used by all the assignment diagnostic functions
3715 // to represent what is actually causing the operation
3716 enum AssignmentAction {
3717 AA_Assigning,
3718 AA_Passing,
3719 AA_Returning,
3720 AA_Converting,
3721 AA_Initializing,
3722 AA_Sending,
3723 AA_Casting,
3724 AA_Passing_CFAudited
3725 };
3726
3727 /// C++ Overloading.
3728 enum OverloadKind {
3729 /// This is a legitimate overload: the existing declarations are
3730 /// functions or function templates with different signatures.
3731 Ovl_Overload,
3732
3733 /// This is not an overload because the signature exactly matches
3734 /// an existing declaration.
3735 Ovl_Match,
3736
3737 /// This is not an overload because the lookup results contain a
3738 /// non-function.
3739 Ovl_NonFunction
3740 };
3741 OverloadKind CheckOverload(Scope *S,
3742 FunctionDecl *New,
3743 const LookupResult &OldDecls,
3744 NamedDecl *&OldDecl,
3745 bool UseMemberUsingDeclRules);
3746 bool IsOverload(FunctionDecl *New, FunctionDecl *Old,
3747 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs = true,
3748 bool ConsiderRequiresClauses = true);
3749
3750 // Calculates whether the expression Constraint depends on an enclosing
3751 // template, for the purposes of [temp.friend] p9.
3752 // TemplateDepth is the 'depth' of the friend function, which is used to
3753 // compare whether a declaration reference is referring to a containing
3754 // template, or just the current friend function. A 'lower' TemplateDepth in
3755 // the AST refers to a 'containing' template. As the constraint is
3756 // uninstantiated, this is relative to the 'top' of the TU.
3757 bool
3758 ConstraintExpressionDependsOnEnclosingTemplate(const FunctionDecl *Friend,
3759 unsigned TemplateDepth,
3760 const Expr *Constraint);
3761
3762 // Calculates whether the friend function depends on an enclosing template for
3763 // the purposes of [temp.friend] p9.
3764 bool FriendConstraintsDependOnEnclosingTemplate(const FunctionDecl *FD);
3765
3766 // Calculates whether two constraint expressions are equal irrespective of a
3767 // difference in 'depth'. This takes a pair of optional 'NamedDecl's 'Old' and
3768 // 'New', which are the "source" of the constraint, since this is necessary
3769 // for figuring out the relative 'depth' of the constraint. The depth of the
3770 // 'primary template' and the 'instantiated from' templates aren't necessarily
3771 // the same, such as a case when one is a 'friend' defined in a class.
3772 bool AreConstraintExpressionsEqual(const NamedDecl *Old,
3773 const Expr *OldConstr,
3774 const NamedDecl *New,
3775 const Expr *NewConstr);
3776
3777 enum class AllowedExplicit {
3778 /// Allow no explicit functions to be used.
3779 None,
3780 /// Allow explicit conversion functions but not explicit constructors.
3781 Conversions,
3782 /// Allow both explicit conversion functions and explicit constructors.
3783 All
3784 };
3785
3786 ImplicitConversionSequence
3787 TryImplicitConversion(Expr *From, QualType ToType,
3788 bool SuppressUserConversions,
3789 AllowedExplicit AllowExplicit,
3790 bool InOverloadResolution,
3791 bool CStyle,
3792 bool AllowObjCWritebackConversion);
3793
3794 bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType);
3795 bool IsFloatingPointPromotion(QualType FromType, QualType ToType);
3796 bool IsComplexPromotion(QualType FromType, QualType ToType);
3797 bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
3798 bool InOverloadResolution,
3799 QualType& ConvertedType, bool &IncompatibleObjC);
3800 bool isObjCPointerConversion(QualType FromType, QualType ToType,
3801 QualType& ConvertedType, bool &IncompatibleObjC);
3802 bool isObjCWritebackConversion(QualType FromType, QualType ToType,
3803 QualType &ConvertedType);
3804 bool IsBlockPointerConversion(QualType FromType, QualType ToType,
3805 QualType& ConvertedType);
3806 bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
3807 const FunctionProtoType