Bug Summary

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