clang  14.0.0git
SemaCoroutine.cpp
Go to the documentation of this file.
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"
24 #include "clang/Sema/Overload.h"
25 #include "clang/Sema/ScopeInfo.h"
27 #include "llvm/ADT/SmallSet.h"
28 
29 using namespace clang;
30 using namespace sema;
31 
32 static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD,
33  SourceLocation Loc, bool &Res) {
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.
39  Res = S.LookupQualifiedName(LR, RD);
40  return LR;
41 }
42 
43 static 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.
53  SourceLocation KwLoc) {
54  const FunctionProtoType *FnType = FD->getType()->castAs<FunctionProtoType>();
55  const SourceLocation FuncLoc = FD->getLocation();
56  // FIXME: Cache std::coroutine_traits once we've found it.
58  if (!StdExp) {
59  S.Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
60  << "std::experimental::coroutine_traits";
61  return QualType();
62  }
63 
64  ClassTemplateDecl *CoroTraits = S.lookupCoroutineTraits(KwLoc, FuncLoc);
65  if (!CoroTraits) {
66  return QualType();
67  }
68 
69  // Form template argument list for coroutine_traits<R, P1, P2, ...> according
70  // to [dcl.fct.def.coroutine]3
71  TemplateArgumentListInfo Args(KwLoc, KwLoc);
72  auto AddArg = [&](QualType T) {
75  };
76  AddArg(FnType->getReturnType());
77  // If the function is a non-static member function, add the type
78  // of the implicit object parameter before the formal parameters.
79  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
80  if (MD->isInstance()) {
81  // [over.match.funcs]4
82  // For non-static member functions, the type of the implicit object
83  // parameter is
84  // -- "lvalue reference to cv X" for functions declared without a
85  // ref-qualifier or with the & ref-qualifier
86  // -- "rvalue reference to cv X" for functions declared with the &&
87  // ref-qualifier
88  QualType T = MD->getThisType()->castAs<PointerType>()->getPointeeType();
89  T = FnType->getRefQualifier() == RQ_RValue
91  : S.Context.getLValueReferenceType(T, /*SpelledAsLValue*/ true);
92  AddArg(T);
93  }
94  }
95  for (QualType T : FnType->getParamTypes())
96  AddArg(T);
97 
98  // Build the template-id.
99  QualType CoroTrait =
100  S.CheckTemplateIdType(TemplateName(CoroTraits), KwLoc, Args);
101  if (CoroTrait.isNull())
102  return QualType();
103  if (S.RequireCompleteType(KwLoc, CoroTrait,
104  diag::err_coroutine_type_missing_specialization))
105  return QualType();
106 
107  auto *RD = CoroTrait->getAsCXXRecordDecl();
108  assert(RD && "specialization of class template is not a class?");
109 
110  // Look up the ::promise_type member.
111  LookupResult R(S, &S.PP.getIdentifierTable().get("promise_type"), KwLoc,
113  S.LookupQualifiedName(R, RD);
114  auto *Promise = R.getAsSingle<TypeDecl>();
115  if (!Promise) {
116  S.Diag(FuncLoc,
117  diag::err_implied_std_coroutine_traits_promise_type_not_found)
118  << RD;
119  return QualType();
120  }
121  // The promise type is required to be a class type.
122  QualType PromiseType = S.Context.getTypeDeclType(Promise);
123 
124  auto buildElaboratedType = [&]() {
125  auto *NNS = NestedNameSpecifier::Create(S.Context, nullptr, StdExp);
126  NNS = NestedNameSpecifier::Create(S.Context, NNS, false,
127  CoroTrait.getTypePtr());
128  return S.Context.getElaboratedType(ETK_None, NNS, PromiseType);
129  };
130 
131  if (!PromiseType->getAsCXXRecordDecl()) {
132  S.Diag(FuncLoc,
133  diag::err_implied_std_coroutine_traits_promise_type_not_class)
134  << buildElaboratedType();
135  return QualType();
136  }
137  if (S.RequireCompleteType(FuncLoc, buildElaboratedType(),
138  diag::err_coroutine_promise_type_incomplete))
139  return QualType();
140 
141  return PromiseType;
142 }
143 
144 /// Look up the std::experimental::coroutine_handle<PromiseType>.
146  SourceLocation Loc) {
147  if (PromiseType.isNull())
148  return QualType();
149 
151  assert(StdExp && "Should already be diagnosed");
152 
153  LookupResult Result(S, &S.PP.getIdentifierTable().get("coroutine_handle"),
155  if (!S.LookupQualifiedName(Result, StdExp)) {
156  S.Diag(Loc, diag::err_implied_coroutine_type_not_found)
157  << "std::experimental::coroutine_handle";
158  return QualType();
159  }
160 
161  ClassTemplateDecl *CoroHandle = Result.getAsSingle<ClassTemplateDecl>();
162  if (!CoroHandle) {
163  Result.suppressDiagnostics();
164  // We found something weird. Complain about the first thing we found.
165  NamedDecl *Found = *Result.begin();
166  S.Diag(Found->getLocation(), diag::err_malformed_std_coroutine_handle);
167  return QualType();
168  }
169 
170  // Form template argument list for coroutine_handle<Promise>.
171  TemplateArgumentListInfo Args(Loc, Loc);
173  TemplateArgument(PromiseType),
174  S.Context.getTrivialTypeSourceInfo(PromiseType, Loc)));
175 
176  // Build the template-id.
177  QualType CoroHandleType =
178  S.CheckTemplateIdType(TemplateName(CoroHandle), Loc, Args);
179  if (CoroHandleType.isNull())
180  return QualType();
181  if (S.RequireCompleteType(Loc, CoroHandleType,
182  diag::err_coroutine_type_missing_specialization))
183  return QualType();
184 
185  return CoroHandleType;
186 }
187 
189  StringRef Keyword) {
190  // [expr.await]p2 dictates that 'co_await' and 'co_yield' must be used within
191  // a function body.
192  // FIXME: This also covers [expr.await]p2: "An await-expression shall not
193  // appear in a default argument." But the diagnostic QoI here could be
194  // improved to inform the user that default arguments specifically are not
195  // allowed.
196  auto *FD = dyn_cast<FunctionDecl>(S.CurContext);
197  if (!FD) {
198  S.Diag(Loc, isa<ObjCMethodDecl>(S.CurContext)
199  ? diag::err_coroutine_objc_method
200  : diag::err_coroutine_outside_function) << Keyword;
201  return false;
202  }
203 
204  // An enumeration for mapping the diagnostic type to the correct diagnostic
205  // selection index.
206  enum InvalidFuncDiag {
207  DiagCtor = 0,
208  DiagDtor,
209  DiagMain,
210  DiagConstexpr,
211  DiagAutoRet,
212  DiagVarargs,
213  DiagConsteval,
214  };
215  bool Diagnosed = false;
216  auto DiagInvalid = [&](InvalidFuncDiag ID) {
217  S.Diag(Loc, diag::err_coroutine_invalid_func_context) << ID << Keyword;
218  Diagnosed = true;
219  return false;
220  };
221 
222  // Diagnose when a constructor, destructor
223  // or the function 'main' are declared as a coroutine.
224  auto *MD = dyn_cast<CXXMethodDecl>(FD);
225  // [class.ctor]p11: "A constructor shall not be a coroutine."
226  if (MD && isa<CXXConstructorDecl>(MD))
227  return DiagInvalid(DiagCtor);
228  // [class.dtor]p17: "A destructor shall not be a coroutine."
229  else if (MD && isa<CXXDestructorDecl>(MD))
230  return DiagInvalid(DiagDtor);
231  // [basic.start.main]p3: "The function main shall not be a coroutine."
232  else if (FD->isMain())
233  return DiagInvalid(DiagMain);
234 
235  // Emit a diagnostics for each of the following conditions which is not met.
236  // [expr.const]p2: "An expression e is a core constant expression unless the
237  // evaluation of e [...] would evaluate one of the following expressions:
238  // [...] an await-expression [...] a yield-expression."
239  if (FD->isConstexpr())
240  DiagInvalid(FD->isConsteval() ? DiagConsteval : DiagConstexpr);
241  // [dcl.spec.auto]p15: "A function declared with a return type that uses a
242  // placeholder type shall not be a coroutine."
243  if (FD->getReturnType()->isUndeducedType())
244  DiagInvalid(DiagAutoRet);
245  // [dcl.fct.def.coroutine]p1: "The parameter-declaration-clause of the
246  // coroutine shall not terminate with an ellipsis that is not part of a
247  // parameter-declaration."
248  if (FD->isVariadic())
249  DiagInvalid(DiagVarargs);
250 
251  return !Diagnosed;
252 }
253 
255  SourceLocation Loc) {
256  DeclarationName OpName =
257  SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_Coawait);
258  LookupResult Operators(SemaRef, OpName, SourceLocation(),
260  SemaRef.LookupName(Operators, S);
261 
262  assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
263  const auto &Functions = Operators.asUnresolvedSet();
264  bool IsOverloaded =
265  Functions.size() > 1 ||
266  (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
267  Expr *CoawaitOp = UnresolvedLookupExpr::Create(
268  SemaRef.Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
269  DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
270  Functions.begin(), Functions.end());
271  assert(CoawaitOp);
272  return CoawaitOp;
273 }
274 
275 /// Build a call to 'operator co_await' if there is a suitable operator for
276 /// the given expression.
278  Expr *E,
279  UnresolvedLookupExpr *Lookup) {
280  UnresolvedSet<16> Functions;
281  Functions.append(Lookup->decls_begin(), Lookup->decls_end());
282  return SemaRef.CreateOverloadedUnaryOp(Loc, UO_Coawait, Functions, E);
283 }
284 
286  SourceLocation Loc, Expr *E) {
287  ExprResult R = buildOperatorCoawaitLookupExpr(SemaRef, S, Loc);
288  if (R.isInvalid())
289  return ExprError();
290  return buildOperatorCoawaitCall(SemaRef, Loc, E,
291  cast<UnresolvedLookupExpr>(R.get()));
292 }
293 
295  SourceLocation Loc) {
296  QualType CoroHandleType = lookupCoroutineHandleType(S, PromiseType, Loc);
297  if (CoroHandleType.isNull())
298  return ExprError();
299 
300  DeclContext *LookupCtx = S.computeDeclContext(CoroHandleType);
301  LookupResult Found(S, &S.PP.getIdentifierTable().get("from_address"), Loc,
303  if (!S.LookupQualifiedName(Found, LookupCtx)) {
304  S.Diag(Loc, diag::err_coroutine_handle_missing_member)
305  << "from_address";
306  return ExprError();
307  }
308 
309  Expr *FramePtr =
310  S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
311 
312  CXXScopeSpec SS;
313  ExprResult FromAddr =
314  S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
315  if (FromAddr.isInvalid())
316  return ExprError();
317 
318  return S.BuildCallExpr(nullptr, FromAddr.get(), Loc, FramePtr, Loc);
319 }
320 
322  enum AwaitCallType { ACT_Ready, ACT_Suspend, ACT_Resume };
323  Expr *Results[3];
325  bool IsInvalid;
326 };
327 
329  StringRef Name, MultiExprArg Args) {
330  DeclarationNameInfo NameInfo(&S.PP.getIdentifierTable().get(Name), Loc);
331 
332  // FIXME: Fix BuildMemberReferenceExpr to take a const CXXScopeSpec&.
333  CXXScopeSpec SS;
335  Base, Base->getType(), Loc, /*IsPtr=*/false, SS,
336  SourceLocation(), nullptr, NameInfo, /*TemplateArgs=*/nullptr,
337  /*Scope=*/nullptr);
338  if (Result.isInvalid())
339  return ExprError();
340 
341  // We meant exactly what we asked for. No need for typo correction.
342  if (auto *TE = dyn_cast<TypoExpr>(Result.get())) {
343  S.clearDelayedTypo(TE);
344  S.Diag(Loc, diag::err_no_member)
345  << NameInfo.getName() << Base->getType()->getAsCXXRecordDecl()
346  << Base->getSourceRange();
347  return ExprError();
348  }
349 
350  return S.BuildCallExpr(nullptr, Result.get(), Loc, Args, Loc, nullptr);
351 }
352 
353 // See if return type is coroutine-handle and if so, invoke builtin coro-resume
354 // on its address. This is to enable experimental support for coroutine-handle
355 // returning await_suspend that results in a guaranteed tail call to the target
356 // coroutine.
357 static Expr *maybeTailCall(Sema &S, QualType RetType, Expr *E,
358  SourceLocation Loc) {
359  if (RetType->isReferenceType())
360  return nullptr;
361  Type const *T = RetType.getTypePtr();
362  if (!T->isClassType() && !T->isStructureType())
363  return nullptr;
364 
365  // FIXME: Add convertability check to coroutine_handle<>. Possibly via
366  // EvaluateBinaryTypeTrait(BTT_IsConvertible, ...) which is at the moment
367  // a private function in SemaExprCXX.cpp
368 
369  ExprResult AddressExpr = buildMemberCall(S, E, Loc, "address", None);
370  if (AddressExpr.isInvalid())
371  return nullptr;
372 
373  Expr *JustAddress = AddressExpr.get();
374 
375  // Check that the type of AddressExpr is void*
376  if (!JustAddress->getType().getTypePtr()->isVoidPointerType())
377  S.Diag(cast<CallExpr>(JustAddress)->getCalleeDecl()->getLocation(),
378  diag::warn_coroutine_handle_address_invalid_return_type)
379  << JustAddress->getType();
380 
381  // Clean up temporary objects so that they don't live across suspension points
382  // unnecessarily. We choose to clean up before the call to
383  // __builtin_coro_resume so that the cleanup code are not inserted in-between
384  // the resume call and return instruction, which would interfere with the
385  // musttail call contract.
386  JustAddress = S.MaybeCreateExprWithCleanups(JustAddress);
387  return S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_resume,
388  JustAddress);
389 }
390 
391 /// Build calls to await_ready, await_suspend, and await_resume for a co_await
392 /// expression.
393 /// The generated AST tries to clean up temporary objects as early as
394 /// possible so that they don't live across suspension points if possible.
395 /// Having temporary objects living across suspension points unnecessarily can
396 /// lead to large frame size, and also lead to memory corruptions if the
397 /// coroutine frame is destroyed after coming back from suspension. This is done
398 /// by wrapping both the await_ready call and the await_suspend call with
399 /// ExprWithCleanups. In the end of this function, we also need to explicitly
400 /// set cleanup state so that the CoawaitExpr is also wrapped with an
401 /// ExprWithCleanups to clean up the awaiter associated with the co_await
402 /// expression.
404  SourceLocation Loc, Expr *E) {
405  OpaqueValueExpr *Operand = new (S.Context)
406  OpaqueValueExpr(Loc, E->getType(), VK_LValue, E->getObjectKind(), E);
407 
408  // Assume valid until we see otherwise.
409  // Further operations are responsible for setting IsInalid to true.
410  ReadySuspendResumeResult Calls = {{}, Operand, /*IsInvalid=*/false};
411 
413 
414  auto BuildSubExpr = [&](ACT CallType, StringRef Func,
415  MultiExprArg Arg) -> Expr * {
416  ExprResult Result = buildMemberCall(S, Operand, Loc, Func, Arg);
417  if (Result.isInvalid()) {
418  Calls.IsInvalid = true;
419  return nullptr;
420  }
421  Calls.Results[CallType] = Result.get();
422  return Result.get();
423  };
424 
425  CallExpr *AwaitReady =
426  cast_or_null<CallExpr>(BuildSubExpr(ACT::ACT_Ready, "await_ready", None));
427  if (!AwaitReady)
428  return Calls;
429  if (!AwaitReady->getType()->isDependentType()) {
430  // [expr.await]p3 [...]
431  // — await-ready is the expression e.await_ready(), contextually converted
432  // to bool.
433  ExprResult Conv = S.PerformContextuallyConvertToBool(AwaitReady);
434  if (Conv.isInvalid()) {
435  S.Diag(AwaitReady->getDirectCallee()->getBeginLoc(),
436  diag::note_await_ready_no_bool_conversion);
437  S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
438  << AwaitReady->getDirectCallee() << E->getSourceRange();
439  Calls.IsInvalid = true;
440  } else
441  Calls.Results[ACT::ACT_Ready] = S.MaybeCreateExprWithCleanups(Conv.get());
442  }
443 
444  ExprResult CoroHandleRes =
445  buildCoroutineHandle(S, CoroPromise->getType(), Loc);
446  if (CoroHandleRes.isInvalid()) {
447  Calls.IsInvalid = true;
448  return Calls;
449  }
450  Expr *CoroHandle = CoroHandleRes.get();
451  CallExpr *AwaitSuspend = cast_or_null<CallExpr>(
452  BuildSubExpr(ACT::ACT_Suspend, "await_suspend", CoroHandle));
453  if (!AwaitSuspend)
454  return Calls;
455  if (!AwaitSuspend->getType()->isDependentType()) {
456  // [expr.await]p3 [...]
457  // - await-suspend is the expression e.await_suspend(h), which shall be
458  // a prvalue of type void, bool, or std::coroutine_handle<Z> for some
459  // type Z.
460  QualType RetType = AwaitSuspend->getCallReturnType(S.Context);
461 
462  // Experimental support for coroutine_handle returning await_suspend.
463  if (Expr *TailCallSuspend =
464  maybeTailCall(S, RetType, AwaitSuspend, Loc))
465  // Note that we don't wrap the expression with ExprWithCleanups here
466  // because that might interfere with tailcall contract (e.g. inserting
467  // clean up instructions in-between tailcall and return). Instead
468  // ExprWithCleanups is wrapped within maybeTailCall() prior to the resume
469  // call.
470  Calls.Results[ACT::ACT_Suspend] = TailCallSuspend;
471  else {
472  // non-class prvalues always have cv-unqualified types
473  if (RetType->isReferenceType() ||
474  (!RetType->isBooleanType() && !RetType->isVoidType())) {
475  S.Diag(AwaitSuspend->getCalleeDecl()->getLocation(),
476  diag::err_await_suspend_invalid_return_type)
477  << RetType;
478  S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
479  << AwaitSuspend->getDirectCallee();
480  Calls.IsInvalid = true;
481  } else
482  Calls.Results[ACT::ACT_Suspend] =
483  S.MaybeCreateExprWithCleanups(AwaitSuspend);
484  }
485  }
486 
487  BuildSubExpr(ACT::ACT_Resume, "await_resume", None);
488 
489  // Make sure the awaiter object gets a chance to be cleaned up.
491 
492  return Calls;
493 }
494 
496  SourceLocation Loc, StringRef Name,
497  MultiExprArg Args) {
498 
499  // Form a reference to the promise.
500  ExprResult PromiseRef = S.BuildDeclRefExpr(
501  Promise, Promise->getType().getNonReferenceType(), VK_LValue, Loc);
502  if (PromiseRef.isInvalid())
503  return ExprError();
504 
505  return buildMemberCall(S, PromiseRef.get(), Loc, Name, Args);
506 }
507 
509  assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
510  auto *FD = cast<FunctionDecl>(CurContext);
511  bool IsThisDependentType = [&] {
512  if (auto *MD = dyn_cast_or_null<CXXMethodDecl>(FD))
513  return MD->isInstance() && MD->getThisType()->isDependentType();
514  else
515  return false;
516  }();
517 
518  QualType T = FD->getType()->isDependentType() || IsThisDependentType
519  ? Context.DependentTy
520  : lookupPromiseType(*this, FD, Loc);
521  if (T.isNull())
522  return nullptr;
523 
524  auto *VD = VarDecl::Create(Context, FD, FD->getLocation(), FD->getLocation(),
525  &PP.getIdentifierTable().get("__promise"), T,
526  Context.getTrivialTypeSourceInfo(T, Loc), SC_None);
527  VD->setImplicit();
528  CheckVariableDeclarationType(VD);
529  if (VD->isInvalidDecl())
530  return nullptr;
531 
532  auto *ScopeInfo = getCurFunction();
533 
534  // Build a list of arguments, based on the coroutine function's arguments,
535  // that if present will be passed to the promise type's constructor.
536  llvm::SmallVector<Expr *, 4> CtorArgExprs;
537 
538  // Add implicit object parameter.
539  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
540  if (MD->isInstance() && !isLambdaCallOperator(MD)) {
541  ExprResult ThisExpr = ActOnCXXThis(Loc);
542  if (ThisExpr.isInvalid())
543  return nullptr;
544  ThisExpr = CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
545  if (ThisExpr.isInvalid())
546  return nullptr;
547  CtorArgExprs.push_back(ThisExpr.get());
548  }
549  }
550 
551  // Add the coroutine function's parameters.
552  auto &Moves = ScopeInfo->CoroutineParameterMoves;
553  for (auto *PD : FD->parameters()) {
554  if (PD->getType()->isDependentType())
555  continue;
556 
557  auto RefExpr = ExprEmpty();
558  auto Move = Moves.find(PD);
559  assert(Move != Moves.end() &&
560  "Coroutine function parameter not inserted into move map");
561  // If a reference to the function parameter exists in the coroutine
562  // frame, use that reference.
563  auto *MoveDecl =
564  cast<VarDecl>(cast<DeclStmt>(Move->second)->getSingleDecl());
565  RefExpr =
566  BuildDeclRefExpr(MoveDecl, MoveDecl->getType().getNonReferenceType(),
567  ExprValueKind::VK_LValue, FD->getLocation());
568  if (RefExpr.isInvalid())
569  return nullptr;
570  CtorArgExprs.push_back(RefExpr.get());
571  }
572 
573  // If we have a non-zero number of constructor arguments, try to use them.
574  // Otherwise, fall back to the promise type's default constructor.
575  if (!CtorArgExprs.empty()) {
576  // Create an initialization sequence for the promise type using the
577  // constructor arguments, wrapped in a parenthesized list expression.
578  Expr *PLE = ParenListExpr::Create(Context, FD->getLocation(),
579  CtorArgExprs, FD->getLocation());
582  VD->getLocation(), /*DirectInit=*/true, PLE);
583  InitializationSequence InitSeq(*this, Entity, Kind, CtorArgExprs,
584  /*TopLevelOfInitList=*/false,
585  /*TreatUnavailableAsInvalid=*/false);
586 
587  // Attempt to initialize the promise type with the arguments.
588  // If that fails, fall back to the promise type's default constructor.
589  if (InitSeq) {
590  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, CtorArgExprs);
591  if (Result.isInvalid()) {
592  VD->setInvalidDecl();
593  } else if (Result.get()) {
594  VD->setInit(MaybeCreateExprWithCleanups(Result.get()));
595  VD->setInitStyle(VarDecl::CallInit);
596  CheckCompleteVariableDeclaration(VD);
597  }
598  } else
599  ActOnUninitializedDecl(VD);
600  } else
601  ActOnUninitializedDecl(VD);
602 
603  FD->addDecl(VD);
604  return VD;
605 }
606 
607 /// Check that this is a context in which a coroutine suspension can appear.
609  StringRef Keyword,
610  bool IsImplicit = false) {
611  if (!isValidCoroutineContext(S, Loc, Keyword))
612  return nullptr;
613 
614  assert(isa<FunctionDecl>(S.CurContext) && "not in a function scope");
615 
616  auto *ScopeInfo = S.getCurFunction();
617  assert(ScopeInfo && "missing function scope for function");
618 
619  if (ScopeInfo->FirstCoroutineStmtLoc.isInvalid() && !IsImplicit)
620  ScopeInfo->setFirstCoroutineStmt(Loc, Keyword);
621 
622  if (ScopeInfo->CoroutinePromise)
623  return ScopeInfo;
624 
625  if (!S.buildCoroutineParameterMoves(Loc))
626  return nullptr;
627 
628  ScopeInfo->CoroutinePromise = S.buildCoroutinePromise(Loc);
629  if (!ScopeInfo->CoroutinePromise)
630  return nullptr;
631 
632  return ScopeInfo;
633 }
634 
635 /// Recursively check \p E and all its children to see if any call target
636 /// (including constructor call) is declared noexcept. Also any value returned
637 /// from the call has a noexcept destructor.
638 static void checkNoThrow(Sema &S, const Stmt *E,
639  llvm::SmallPtrSetImpl<const Decl *> &ThrowingDecls) {
640  auto checkDeclNoexcept = [&](const Decl *D, bool IsDtor = false) {
641  // In the case of dtor, the call to dtor is implicit and hence we should
642  // pass nullptr to canCalleeThrow.
643  if (Sema::canCalleeThrow(S, IsDtor ? nullptr : cast<Expr>(E), D)) {
644  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
645  // co_await promise.final_suspend() could end up calling
646  // __builtin_coro_resume for symmetric transfer if await_suspend()
647  // returns a handle. In that case, even __builtin_coro_resume is not
648  // declared as noexcept and may throw, it does not throw _into_ the
649  // coroutine that just suspended, but rather throws back out from
650  // whoever called coroutine_handle::resume(), hence we claim that
651  // logically it does not throw.
652  if (FD->getBuiltinID() == Builtin::BI__builtin_coro_resume)
653  return;
654  }
655  if (ThrowingDecls.empty()) {
656  // First time seeing an error, emit the error message.
657  S.Diag(cast<FunctionDecl>(S.CurContext)->getLocation(),
658  diag::err_coroutine_promise_final_suspend_requires_nothrow);
659  }
660  ThrowingDecls.insert(D);
661  }
662  };
663  auto SC = E->getStmtClass();
664  if (SC == Expr::CXXConstructExprClass) {
665  auto const *Ctor = cast<CXXConstructExpr>(E)->getConstructor();
666  checkDeclNoexcept(Ctor);
667  // Check the corresponding destructor of the constructor.
668  checkDeclNoexcept(Ctor->getParent()->getDestructor(), true);
669  } else if (SC == Expr::CallExprClass || SC == Expr::CXXMemberCallExprClass ||
670  SC == Expr::CXXOperatorCallExprClass) {
671  if (!cast<CallExpr>(E)->isTypeDependent()) {
672  checkDeclNoexcept(cast<CallExpr>(E)->getCalleeDecl());
673  auto ReturnType = cast<CallExpr>(E)->getCallReturnType(S.getASTContext());
674  // Check the destructor of the call return type, if any.
675  if (ReturnType.isDestructedType() ==
676  QualType::DestructionKind::DK_cxx_destructor) {
677  const auto *T =
678  cast<RecordType>(ReturnType.getCanonicalType().getTypePtr());
679  checkDeclNoexcept(
680  dyn_cast<CXXRecordDecl>(T->getDecl())->getDestructor(), true);
681  }
682  }
683  }
684  for (const auto *Child : E->children()) {
685  if (!Child)
686  continue;
687  checkNoThrow(S, Child, ThrowingDecls);
688  }
689 }
690 
691 bool Sema::checkFinalSuspendNoThrow(const Stmt *FinalSuspend) {
693  // We first collect all declarations that should not throw but not declared
694  // with noexcept. We then sort them based on the location before printing.
695  // This is to avoid emitting the same note multiple times on the same
696  // declaration, and also provide a deterministic order for the messages.
697  checkNoThrow(*this, FinalSuspend, ThrowingDecls);
698  auto SortedDecls = llvm::SmallVector<const Decl *, 4>{ThrowingDecls.begin(),
699  ThrowingDecls.end()};
700  sort(SortedDecls, [](const Decl *A, const Decl *B) {
701  return A->getEndLoc() < B->getEndLoc();
702  });
703  for (const auto *D : SortedDecls) {
704  Diag(D->getEndLoc(), diag::note_coroutine_function_declare_noexcept);
705  }
706  return ThrowingDecls.empty();
707 }
708 
710  StringRef Keyword) {
711  if (!checkCoroutineContext(*this, KWLoc, Keyword))
712  return false;
713  auto *ScopeInfo = getCurFunction();
714  assert(ScopeInfo->CoroutinePromise);
715 
716  // If we have existing coroutine statements then we have already built
717  // the initial and final suspend points.
718  if (!ScopeInfo->NeedsCoroutineSuspends)
719  return true;
720 
721  ScopeInfo->setNeedsCoroutineSuspends(false);
722 
723  auto *Fn = cast<FunctionDecl>(CurContext);
724  SourceLocation Loc = Fn->getLocation();
725  // Build the initial suspend point
726  auto buildSuspends = [&](StringRef Name) mutable -> StmtResult {
727  ExprResult Suspend =
728  buildPromiseCall(*this, ScopeInfo->CoroutinePromise, Loc, Name, None);
729  if (Suspend.isInvalid())
730  return StmtError();
731  Suspend = buildOperatorCoawaitCall(*this, SC, Loc, Suspend.get());
732  if (Suspend.isInvalid())
733  return StmtError();
734  Suspend = BuildResolvedCoawaitExpr(Loc, Suspend.get(),
735  /*IsImplicit*/ true);
736  Suspend = ActOnFinishFullExpr(Suspend.get(), /*DiscardedValue*/ false);
737  if (Suspend.isInvalid()) {
738  Diag(Loc, diag::note_coroutine_promise_suspend_implicitly_required)
739  << ((Name == "initial_suspend") ? 0 : 1);
740  Diag(KWLoc, diag::note_declared_coroutine_here) << Keyword;
741  return StmtError();
742  }
743  return cast<Stmt>(Suspend.get());
744  };
745 
746  StmtResult InitSuspend = buildSuspends("initial_suspend");
747  if (InitSuspend.isInvalid())
748  return true;
749 
750  StmtResult FinalSuspend = buildSuspends("final_suspend");
751  if (FinalSuspend.isInvalid() || !checkFinalSuspendNoThrow(FinalSuspend.get()))
752  return true;
753 
754  ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
755 
756  return true;
757 }
758 
759 // Recursively walks up the scope hierarchy until either a 'catch' or a function
760 // scope is found, whichever comes first.
761 static bool isWithinCatchScope(Scope *S) {
762  // 'co_await' and 'co_yield' keywords are disallowed within catch blocks, but
763  // lambdas that use 'co_await' are allowed. The loop below ends when a
764  // function scope is found in order to ensure the following behavior:
765  //
766  // void foo() { // <- function scope
767  // try { //
768  // co_await x; // <- 'co_await' is OK within a function scope
769  // } catch { // <- catch scope
770  // co_await x; // <- 'co_await' is not OK within a catch scope
771  // []() { // <- function scope
772  // co_await x; // <- 'co_await' is OK within a function scope
773  // }();
774  // }
775  // }
776  while (S && !(S->getFlags() & Scope::FnScope)) {
777  if (S->getFlags() & Scope::CatchScope)
778  return true;
779  S = S->getParent();
780  }
781  return false;
782 }
783 
784 // [expr.await]p2, emphasis added: "An await-expression shall appear only in
785 // a *potentially evaluated* expression within the compound-statement of a
786 // function-body *outside of a handler* [...] A context within a function
787 // where an await-expression can appear is called a suspension context of the
788 // function."
790  StringRef Keyword) {
791  // First emphasis of [expr.await]p2: must be a potentially evaluated context.
792  // That is, 'co_await' and 'co_yield' cannot appear in subexpressions of
793  // \c sizeof.
794  if (S.isUnevaluatedContext())
795  S.Diag(Loc, diag::err_coroutine_unevaluated_context) << Keyword;
796 
797  // Second emphasis of [expr.await]p2: must be outside of an exception handler.
799  S.Diag(Loc, diag::err_coroutine_within_handler) << Keyword;
800 }
801 
803  if (!ActOnCoroutineBodyStart(S, Loc, "co_await")) {
804  CorrectDelayedTyposInExpr(E);
805  return ExprError();
806  }
807 
808  checkSuspensionContext(*this, Loc, "co_await");
809 
810  if (E->getType()->isPlaceholderType()) {
811  ExprResult R = CheckPlaceholderExpr(E);
812  if (R.isInvalid()) return ExprError();
813  E = R.get();
814  }
815  ExprResult Lookup = buildOperatorCoawaitLookupExpr(*this, S, Loc);
816  if (Lookup.isInvalid())
817  return ExprError();
818  return BuildUnresolvedCoawaitExpr(Loc, E,
819  cast<UnresolvedLookupExpr>(Lookup.get()));
820 }
821 
823  UnresolvedLookupExpr *Lookup) {
824  auto *FSI = checkCoroutineContext(*this, Loc, "co_await");
825  if (!FSI)
826  return ExprError();
827 
828  if (E->getType()->isPlaceholderType()) {
829  ExprResult R = CheckPlaceholderExpr(E);
830  if (R.isInvalid())
831  return ExprError();
832  E = R.get();
833  }
834 
835  auto *Promise = FSI->CoroutinePromise;
836  if (Promise->getType()->isDependentType()) {
837  Expr *Res =
838  new (Context) DependentCoawaitExpr(Loc, Context.DependentTy, E, Lookup);
839  return Res;
840  }
841 
842  auto *RD = Promise->getType()->getAsCXXRecordDecl();
843  if (lookupMember(*this, "await_transform", RD, Loc)) {
844  ExprResult R = buildPromiseCall(*this, Promise, Loc, "await_transform", E);
845  if (R.isInvalid()) {
846  Diag(Loc,
847  diag::note_coroutine_promise_implicit_await_transform_required_here)
848  << E->getSourceRange();
849  return ExprError();
850  }
851  E = R.get();
852  }
853  ExprResult Awaitable = buildOperatorCoawaitCall(*this, Loc, E, Lookup);
854  if (Awaitable.isInvalid())
855  return ExprError();
856 
857  return BuildResolvedCoawaitExpr(Loc, Awaitable.get());
858 }
859 
861  bool IsImplicit) {
862  auto *Coroutine = checkCoroutineContext(*this, Loc, "co_await", IsImplicit);
863  if (!Coroutine)
864  return ExprError();
865 
866  if (E->getType()->isPlaceholderType()) {
867  ExprResult R = CheckPlaceholderExpr(E);
868  if (R.isInvalid()) return ExprError();
869  E = R.get();
870  }
871 
872  if (E->getType()->isDependentType()) {
873  Expr *Res = new (Context)
874  CoawaitExpr(Loc, Context.DependentTy, E, IsImplicit);
875  return Res;
876  }
877 
878  // If the expression is a temporary, materialize it as an lvalue so that we
879  // can use it multiple times.
880  if (E->isPRValue())
881  E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
882 
883  // The location of the `co_await` token cannot be used when constructing
884  // the member call expressions since it's before the location of `Expr`, which
885  // is used as the start of the member call expression.
886  SourceLocation CallLoc = E->getExprLoc();
887 
888  // Build the await_ready, await_suspend, await_resume calls.
890  *this, Coroutine->CoroutinePromise, CallLoc, E);
891  if (RSS.IsInvalid)
892  return ExprError();
893 
894  Expr *Res =
895  new (Context) CoawaitExpr(Loc, E, RSS.Results[0], RSS.Results[1],
896  RSS.Results[2], RSS.OpaqueValue, IsImplicit);
897 
898  return Res;
899 }
900 
902  if (!ActOnCoroutineBodyStart(S, Loc, "co_yield")) {
903  CorrectDelayedTyposInExpr(E);
904  return ExprError();
905  }
906 
907  checkSuspensionContext(*this, Loc, "co_yield");
908 
909  // Build yield_value call.
910  ExprResult Awaitable = buildPromiseCall(
911  *this, getCurFunction()->CoroutinePromise, Loc, "yield_value", E);
912  if (Awaitable.isInvalid())
913  return ExprError();
914 
915  // Build 'operator co_await' call.
916  Awaitable = buildOperatorCoawaitCall(*this, S, Loc, Awaitable.get());
917  if (Awaitable.isInvalid())
918  return ExprError();
919 
920  return BuildCoyieldExpr(Loc, Awaitable.get());
921 }
923  auto *Coroutine = checkCoroutineContext(*this, Loc, "co_yield");
924  if (!Coroutine)
925  return ExprError();
926 
927  if (E->getType()->isPlaceholderType()) {
928  ExprResult R = CheckPlaceholderExpr(E);
929  if (R.isInvalid()) return ExprError();
930  E = R.get();
931  }
932 
933  if (E->getType()->isDependentType()) {
934  Expr *Res = new (Context) CoyieldExpr(Loc, Context.DependentTy, E);
935  return Res;
936  }
937 
938  // If the expression is a temporary, materialize it as an lvalue so that we
939  // can use it multiple times.
940  if (E->isPRValue())
941  E = CreateMaterializeTemporaryExpr(E->getType(), E, true);
942 
943  // Build the await_ready, await_suspend, await_resume calls.
945  *this, Coroutine->CoroutinePromise, Loc, E);
946  if (RSS.IsInvalid)
947  return ExprError();
948 
949  Expr *Res =
950  new (Context) CoyieldExpr(Loc, E, RSS.Results[0], RSS.Results[1],
951  RSS.Results[2], RSS.OpaqueValue);
952 
953  return Res;
954 }
955 
957  if (!ActOnCoroutineBodyStart(S, Loc, "co_return")) {
958  CorrectDelayedTyposInExpr(E);
959  return StmtError();
960  }
961  return BuildCoreturnStmt(Loc, E);
962 }
963 
965  bool IsImplicit) {
966  auto *FSI = checkCoroutineContext(*this, Loc, "co_return", IsImplicit);
967  if (!FSI)
968  return StmtError();
969 
970  if (E && E->getType()->isPlaceholderType() &&
971  !E->getType()->isSpecificPlaceholderType(BuiltinType::Overload)) {
972  ExprResult R = CheckPlaceholderExpr(E);
973  if (R.isInvalid()) return StmtError();
974  E = R.get();
975  }
976 
977  VarDecl *Promise = FSI->CoroutinePromise;
978  ExprResult PC;
979  if (E && (isa<InitListExpr>(E) || !E->getType()->isVoidType())) {
980  getNamedReturnInfo(E, SimplerImplicitMoveMode::ForceOn);
981  PC = buildPromiseCall(*this, Promise, Loc, "return_value", E);
982  } else {
983  E = MakeFullDiscardedValueExpr(E).get();
984  PC = buildPromiseCall(*this, Promise, Loc, "return_void", None);
985  }
986  if (PC.isInvalid())
987  return StmtError();
988 
989  Expr *PCE = ActOnFinishFullExpr(PC.get(), /*DiscardedValue*/ false).get();
990 
991  Stmt *Res = new (Context) CoreturnStmt(Loc, E, PCE, IsImplicit);
992  return Res;
993 }
994 
995 /// Look up the std::nothrow object.
998  assert(Std && "Should already be diagnosed");
999 
1000  LookupResult Result(S, &S.PP.getIdentifierTable().get("nothrow"), Loc,
1002  if (!S.LookupQualifiedName(Result, Std)) {
1003  // FIXME: <experimental/coroutine> should have been included already.
1004  // If we require it to include <new> then this diagnostic is no longer
1005  // needed.
1006  S.Diag(Loc, diag::err_implicit_coroutine_std_nothrow_type_not_found);
1007  return nullptr;
1008  }
1009 
1010  auto *VD = Result.getAsSingle<VarDecl>();
1011  if (!VD) {
1012  Result.suppressDiagnostics();
1013  // We found something weird. Complain about the first thing we found.
1014  NamedDecl *Found = *Result.begin();
1015  S.Diag(Found->getLocation(), diag::err_malformed_std_nothrow);
1016  return nullptr;
1017  }
1018 
1019  ExprResult DR = S.BuildDeclRefExpr(VD, VD->getType(), VK_LValue, Loc);
1020  if (DR.isInvalid())
1021  return nullptr;
1022 
1023  return DR.get();
1024 }
1025 
1026 // Find an appropriate delete for the promise.
1028  QualType PromiseType) {
1029  FunctionDecl *OperatorDelete = nullptr;
1030 
1031  DeclarationName DeleteName =
1033 
1034  auto *PointeeRD = PromiseType->getAsCXXRecordDecl();
1035  assert(PointeeRD && "PromiseType must be a CxxRecordDecl type");
1036 
1037  if (S.FindDeallocationFunction(Loc, PointeeRD, DeleteName, OperatorDelete))
1038  return nullptr;
1039 
1040  if (!OperatorDelete) {
1041  // Look for a global declaration.
1042  const bool CanProvideSize = S.isCompleteType(Loc, PromiseType);
1043  const bool Overaligned = false;
1044  OperatorDelete = S.FindUsualDeallocationFunction(Loc, CanProvideSize,
1045  Overaligned, DeleteName);
1046  }
1047  S.MarkFunctionReferenced(Loc, OperatorDelete);
1048  return OperatorDelete;
1049 }
1050 
1051 
1053  FunctionScopeInfo *Fn = getCurFunction();
1054  assert(Fn && Fn->isCoroutine() && "not a coroutine");
1055  if (!Body) {
1056  assert(FD->isInvalidDecl() &&
1057  "a null body is only allowed for invalid declarations");
1058  return;
1059  }
1060  // We have a function that uses coroutine keywords, but we failed to build
1061  // the promise type.
1062  if (!Fn->CoroutinePromise)
1063  return FD->setInvalidDecl();
1064 
1065  if (isa<CoroutineBodyStmt>(Body)) {
1066  // Nothing todo. the body is already a transformed coroutine body statement.
1067  return;
1068  }
1069 
1070  // Coroutines [stmt.return]p1:
1071  // A return statement shall not appear in a coroutine.
1072  if (Fn->FirstReturnLoc.isValid()) {
1073  assert(Fn->FirstCoroutineStmtLoc.isValid() &&
1074  "first coroutine location not set");
1075  Diag(Fn->FirstReturnLoc, diag::err_return_in_coroutine);
1076  Diag(Fn->FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1078  }
1079  CoroutineStmtBuilder Builder(*this, *FD, *Fn, Body);
1080  if (Builder.isInvalid() || !Builder.buildStatements())
1081  return FD->setInvalidDecl();
1082 
1083  // Build body for the coroutine wrapper statement.
1084  Body = CoroutineBodyStmt::Create(Context, Builder);
1085 }
1086 
1089  Stmt *Body)
1090  : S(S), FD(FD), Fn(Fn), Loc(FD.getLocation()),
1091  IsPromiseDependentType(
1092  !Fn.CoroutinePromise ||
1093  Fn.CoroutinePromise->getType()->isDependentType()) {
1094  this->Body = Body;
1095 
1096  for (auto KV : Fn.CoroutineParameterMoves)
1097  this->ParamMovesVector.push_back(KV.second);
1098  this->ParamMoves = this->ParamMovesVector;
1099 
1100  if (!IsPromiseDependentType) {
1101  PromiseRecordDecl = Fn.CoroutinePromise->getType()->getAsCXXRecordDecl();
1102  assert(PromiseRecordDecl && "Type should have already been checked");
1103  }
1104  this->IsValid = makePromiseStmt() && makeInitialAndFinalSuspend();
1105 }
1106 
1108  assert(this->IsValid && "coroutine already invalid");
1109  this->IsValid = makeReturnObject();
1110  if (this->IsValid && !IsPromiseDependentType)
1112  return this->IsValid;
1113 }
1114 
1116  assert(this->IsValid && "coroutine already invalid");
1117  assert(!this->IsPromiseDependentType &&
1118  "coroutine cannot have a dependent promise type");
1119  this->IsValid = makeOnException() && makeOnFallthrough() &&
1120  makeGroDeclAndReturnStmt() && makeReturnOnAllocFailure() &&
1121  makeNewAndDeleteExpr();
1122  return this->IsValid;
1123 }
1124 
1125 bool CoroutineStmtBuilder::makePromiseStmt() {
1126  // Form a declaration statement for the promise declaration, so that AST
1127  // visitors can more easily find it.
1128  StmtResult PromiseStmt =
1130  if (PromiseStmt.isInvalid())
1131  return false;
1132 
1133  this->Promise = PromiseStmt.get();
1134  return true;
1135 }
1136 
1137 bool CoroutineStmtBuilder::makeInitialAndFinalSuspend() {
1138  if (Fn.hasInvalidCoroutineSuspends())
1139  return false;
1140  this->InitialSuspend = cast<Expr>(Fn.CoroutineSuspends.first);
1141  this->FinalSuspend = cast<Expr>(Fn.CoroutineSuspends.second);
1142  return true;
1143 }
1144 
1146  CXXRecordDecl *PromiseRecordDecl,
1147  FunctionScopeInfo &Fn) {
1148  auto Loc = E->getExprLoc();
1149  if (auto *DeclRef = dyn_cast_or_null<DeclRefExpr>(E)) {
1150  auto *Decl = DeclRef->getDecl();
1151  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(Decl)) {
1152  if (Method->isStatic())
1153  return true;
1154  else
1155  Loc = Decl->getLocation();
1156  }
1157  }
1158 
1159  S.Diag(
1160  Loc,
1161  diag::err_coroutine_promise_get_return_object_on_allocation_failure)
1162  << PromiseRecordDecl;
1163  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1165  return false;
1166 }
1167 
1168 bool CoroutineStmtBuilder::makeReturnOnAllocFailure() {
1169  assert(!IsPromiseDependentType &&
1170  "cannot make statement while the promise type is dependent");
1171 
1172  // [dcl.fct.def.coroutine]/8
1173  // The unqualified-id get_return_object_on_allocation_failure is looked up in
1174  // the scope of class P by class member access lookup (3.4.5). ...
1175  // If an allocation function returns nullptr, ... the coroutine return value
1176  // is obtained by a call to ... get_return_object_on_allocation_failure().
1177 
1178  DeclarationName DN =
1179  S.PP.getIdentifierInfo("get_return_object_on_allocation_failure");
1180  LookupResult Found(S, DN, Loc, Sema::LookupMemberName);
1181  if (!S.LookupQualifiedName(Found, PromiseRecordDecl))
1182  return true;
1183 
1184  CXXScopeSpec SS;
1185  ExprResult DeclNameExpr =
1186  S.BuildDeclarationNameExpr(SS, Found, /*NeedsADL=*/false);
1187  if (DeclNameExpr.isInvalid())
1188  return false;
1189 
1190  if (!diagReturnOnAllocFailure(S, DeclNameExpr.get(), PromiseRecordDecl, Fn))
1191  return false;
1192 
1193  ExprResult ReturnObjectOnAllocationFailure =
1194  S.BuildCallExpr(nullptr, DeclNameExpr.get(), Loc, {}, Loc);
1195  if (ReturnObjectOnAllocationFailure.isInvalid())
1196  return false;
1197 
1199  S.BuildReturnStmt(Loc, ReturnObjectOnAllocationFailure.get());
1200  if (ReturnStmt.isInvalid()) {
1201  S.Diag(Found.getFoundDecl()->getLocation(), diag::note_member_declared_here)
1202  << DN;
1203  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1205  return false;
1206  }
1207 
1208  this->ReturnStmtOnAllocFailure = ReturnStmt.get();
1209  return true;
1210 }
1211 
1212 bool CoroutineStmtBuilder::makeNewAndDeleteExpr() {
1213  // Form and check allocation and deallocation calls.
1214  assert(!IsPromiseDependentType &&
1215  "cannot make statement while the promise type is dependent");
1216  QualType PromiseType = Fn.CoroutinePromise->getType();
1217 
1218  if (S.RequireCompleteType(Loc, PromiseType, diag::err_incomplete_type))
1219  return false;
1220 
1221  const bool RequiresNoThrowAlloc = ReturnStmtOnAllocFailure != nullptr;
1222 
1223  // [dcl.fct.def.coroutine]/7
1224  // Lookup allocation functions using a parameter list composed of the
1225  // requested size of the coroutine state being allocated, followed by
1226  // the coroutine function's arguments. If a matching allocation function
1227  // exists, use it. Otherwise, use an allocation function that just takes
1228  // the requested size.
1229 
1230  FunctionDecl *OperatorNew = nullptr;
1231  FunctionDecl *OperatorDelete = nullptr;
1232  FunctionDecl *UnusedResult = nullptr;
1233  bool PassAlignment = false;
1234  SmallVector<Expr *, 1> PlacementArgs;
1235 
1236  // [dcl.fct.def.coroutine]/7
1237  // "The allocation function’s name is looked up in the scope of P.
1238  // [...] If the lookup finds an allocation function in the scope of P,
1239  // overload resolution is performed on a function call created by assembling
1240  // an argument list. The first argument is the amount of space requested,
1241  // and has type std::size_t. The lvalues p1 ... pn are the succeeding
1242  // arguments."
1243  //
1244  // ...where "p1 ... pn" are defined earlier as:
1245  //
1246  // [dcl.fct.def.coroutine]/3
1247  // "For a coroutine f that is a non-static member function, let P1 denote the
1248  // type of the implicit object parameter (13.3.1) and P2 ... Pn be the types
1249  // of the function parameters; otherwise let P1 ... Pn be the types of the
1250  // function parameters. Let p1 ... pn be lvalues denoting those objects."
1251  if (auto *MD = dyn_cast<CXXMethodDecl>(&FD)) {
1252  if (MD->isInstance() && !isLambdaCallOperator(MD)) {
1253  ExprResult ThisExpr = S.ActOnCXXThis(Loc);
1254  if (ThisExpr.isInvalid())
1255  return false;
1256  ThisExpr = S.CreateBuiltinUnaryOp(Loc, UO_Deref, ThisExpr.get());
1257  if (ThisExpr.isInvalid())
1258  return false;
1259  PlacementArgs.push_back(ThisExpr.get());
1260  }
1261  }
1262  for (auto *PD : FD.parameters()) {
1263  if (PD->getType()->isDependentType())
1264  continue;
1265 
1266  // Build a reference to the parameter.
1267  auto PDLoc = PD->getLocation();
1268  ExprResult PDRefExpr =
1269  S.BuildDeclRefExpr(PD, PD->getOriginalType().getNonReferenceType(),
1270  ExprValueKind::VK_LValue, PDLoc);
1271  if (PDRefExpr.isInvalid())
1272  return false;
1273 
1274  PlacementArgs.push_back(PDRefExpr.get());
1275  }
1276  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1277  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1278  /*isArray*/ false, PassAlignment, PlacementArgs,
1279  OperatorNew, UnusedResult, /*Diagnose*/ false);
1280 
1281  // [dcl.fct.def.coroutine]/7
1282  // "If no matching function is found, overload resolution is performed again
1283  // on a function call created by passing just the amount of space required as
1284  // an argument of type std::size_t."
1285  if (!OperatorNew && !PlacementArgs.empty()) {
1286  PlacementArgs.clear();
1287  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Class,
1288  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1289  /*isArray*/ false, PassAlignment, PlacementArgs,
1290  OperatorNew, UnusedResult, /*Diagnose*/ false);
1291  }
1292 
1293  // [dcl.fct.def.coroutine]/7
1294  // "The allocation function’s name is looked up in the scope of P. If this
1295  // lookup fails, the allocation function’s name is looked up in the global
1296  // scope."
1297  if (!OperatorNew) {
1298  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Global,
1299  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1300  /*isArray*/ false, PassAlignment, PlacementArgs,
1301  OperatorNew, UnusedResult);
1302  }
1303 
1304  bool IsGlobalOverload =
1305  OperatorNew && !isa<CXXRecordDecl>(OperatorNew->getDeclContext());
1306  // If we didn't find a class-local new declaration and non-throwing new
1307  // was is required then we need to lookup the non-throwing global operator
1308  // instead.
1309  if (RequiresNoThrowAlloc && (!OperatorNew || IsGlobalOverload)) {
1310  auto *StdNoThrow = buildStdNoThrowDeclRef(S, Loc);
1311  if (!StdNoThrow)
1312  return false;
1313  PlacementArgs = {StdNoThrow};
1314  OperatorNew = nullptr;
1315  S.FindAllocationFunctions(Loc, SourceRange(), /*NewScope*/ Sema::AFS_Both,
1316  /*DeleteScope*/ Sema::AFS_Both, PromiseType,
1317  /*isArray*/ false, PassAlignment, PlacementArgs,
1318  OperatorNew, UnusedResult);
1319  }
1320 
1321  if (!OperatorNew)
1322  return false;
1323 
1324  if (RequiresNoThrowAlloc) {
1325  const auto *FT = OperatorNew->getType()->castAs<FunctionProtoType>();
1326  if (!FT->isNothrow(/*ResultIfDependent*/ false)) {
1327  S.Diag(OperatorNew->getLocation(),
1328  diag::err_coroutine_promise_new_requires_nothrow)
1329  << OperatorNew;
1330  S.Diag(Loc, diag::note_coroutine_promise_call_implicitly_required)
1331  << OperatorNew;
1332  return false;
1333  }
1334  }
1335 
1336  if ((OperatorDelete = findDeleteForPromise(S, Loc, PromiseType)) == nullptr)
1337  return false;
1338 
1339  Expr *FramePtr =
1340  S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_frame, {});
1341 
1342  Expr *FrameSize =
1343  S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_size, {});
1344 
1345  // Make new call.
1346 
1347  ExprResult NewRef =
1348  S.BuildDeclRefExpr(OperatorNew, OperatorNew->getType(), VK_LValue, Loc);
1349  if (NewRef.isInvalid())
1350  return false;
1351 
1352  SmallVector<Expr *, 2> NewArgs(1, FrameSize);
1353  for (auto Arg : PlacementArgs)
1354  NewArgs.push_back(Arg);
1355 
1356  ExprResult NewExpr =
1357  S.BuildCallExpr(S.getCurScope(), NewRef.get(), Loc, NewArgs, Loc);
1358  NewExpr = S.ActOnFinishFullExpr(NewExpr.get(), /*DiscardedValue*/ false);
1359  if (NewExpr.isInvalid())
1360  return false;
1361 
1362  // Make delete call.
1363 
1364  QualType OpDeleteQualType = OperatorDelete->getType();
1365 
1366  ExprResult DeleteRef =
1367  S.BuildDeclRefExpr(OperatorDelete, OpDeleteQualType, VK_LValue, Loc);
1368  if (DeleteRef.isInvalid())
1369  return false;
1370 
1371  Expr *CoroFree =
1372  S.BuildBuiltinCallExpr(Loc, Builtin::BI__builtin_coro_free, {FramePtr});
1373 
1374  SmallVector<Expr *, 2> DeleteArgs{CoroFree};
1375 
1376  // Check if we need to pass the size.
1377  const auto *OpDeleteType =
1378  OpDeleteQualType.getTypePtr()->castAs<FunctionProtoType>();
1379  if (OpDeleteType->getNumParams() > 1)
1380  DeleteArgs.push_back(FrameSize);
1381 
1382  ExprResult DeleteExpr =
1383  S.BuildCallExpr(S.getCurScope(), DeleteRef.get(), Loc, DeleteArgs, Loc);
1384  DeleteExpr =
1385  S.ActOnFinishFullExpr(DeleteExpr.get(), /*DiscardedValue*/ false);
1386  if (DeleteExpr.isInvalid())
1387  return false;
1388 
1389  this->Allocate = NewExpr.get();
1390  this->Deallocate = DeleteExpr.get();
1391 
1392  return true;
1393 }
1394 
1395 bool CoroutineStmtBuilder::makeOnFallthrough() {
1396  assert(!IsPromiseDependentType &&
1397  "cannot make statement while the promise type is dependent");
1398 
1399  // [dcl.fct.def.coroutine]/4
1400  // The unqualified-ids 'return_void' and 'return_value' are looked up in
1401  // the scope of class P. If both are found, the program is ill-formed.
1402  bool HasRVoid, HasRValue;
1403  LookupResult LRVoid =
1404  lookupMember(S, "return_void", PromiseRecordDecl, Loc, HasRVoid);
1405  LookupResult LRValue =
1406  lookupMember(S, "return_value", PromiseRecordDecl, Loc, HasRValue);
1407 
1408  StmtResult Fallthrough;
1409  if (HasRVoid && HasRValue) {
1410  // FIXME Improve this diagnostic
1411  S.Diag(FD.getLocation(),
1412  diag::err_coroutine_promise_incompatible_return_functions)
1413  << PromiseRecordDecl;
1414  S.Diag(LRVoid.getRepresentativeDecl()->getLocation(),
1415  diag::note_member_first_declared_here)
1416  << LRVoid.getLookupName();
1417  S.Diag(LRValue.getRepresentativeDecl()->getLocation(),
1418  diag::note_member_first_declared_here)
1419  << LRValue.getLookupName();
1420  return false;
1421  } else if (!HasRVoid && !HasRValue) {
1422  // FIXME: The PDTS currently specifies this case as UB, not ill-formed.
1423  // However we still diagnose this as an error since until the PDTS is fixed.
1424  S.Diag(FD.getLocation(),
1425  diag::err_coroutine_promise_requires_return_function)
1426  << PromiseRecordDecl;
1427  S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1428  << PromiseRecordDecl;
1429  return false;
1430  } else if (HasRVoid) {
1431  // If the unqualified-id return_void is found, flowing off the end of a
1432  // coroutine is equivalent to a co_return with no operand. Otherwise,
1433  // flowing off the end of a coroutine results in undefined behavior.
1434  Fallthrough = S.BuildCoreturnStmt(FD.getLocation(), nullptr,
1435  /*IsImplicit*/false);
1436  Fallthrough = S.ActOnFinishFullStmt(Fallthrough.get());
1437  if (Fallthrough.isInvalid())
1438  return false;
1439  }
1440 
1441  this->OnFallthrough = Fallthrough.get();
1442  return true;
1443 }
1444 
1445 bool CoroutineStmtBuilder::makeOnException() {
1446  // Try to form 'p.unhandled_exception();'
1447  assert(!IsPromiseDependentType &&
1448  "cannot make statement while the promise type is dependent");
1449 
1450  const bool RequireUnhandledException = S.getLangOpts().CXXExceptions;
1451 
1452  if (!lookupMember(S, "unhandled_exception", PromiseRecordDecl, Loc)) {
1453  auto DiagID =
1454  RequireUnhandledException
1455  ? diag::err_coroutine_promise_unhandled_exception_required
1456  : diag::
1457  warn_coroutine_promise_unhandled_exception_required_with_exceptions;
1458  S.Diag(Loc, DiagID) << PromiseRecordDecl;
1459  S.Diag(PromiseRecordDecl->getLocation(), diag::note_defined_here)
1460  << PromiseRecordDecl;
1461  return !RequireUnhandledException;
1462  }
1463 
1464  // If exceptions are disabled, don't try to build OnException.
1465  if (!S.getLangOpts().CXXExceptions)
1466  return true;
1467 
1468  ExprResult UnhandledException = buildPromiseCall(S, Fn.CoroutinePromise, Loc,
1469  "unhandled_exception", None);
1470  UnhandledException = S.ActOnFinishFullExpr(UnhandledException.get(), Loc,
1471  /*DiscardedValue*/ false);
1472  if (UnhandledException.isInvalid())
1473  return false;
1474 
1475  // Since the body of the coroutine will be wrapped in try-catch, it will
1476  // be incompatible with SEH __try if present in a function.
1477  if (!S.getLangOpts().Borland && Fn.FirstSEHTryLoc.isValid()) {
1478  S.Diag(Fn.FirstSEHTryLoc, diag::err_seh_in_a_coroutine_with_cxx_exceptions);
1479  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1481  return false;
1482  }
1483 
1484  this->OnException = UnhandledException.get();
1485  return true;
1486 }
1487 
1488 bool CoroutineStmtBuilder::makeReturnObject() {
1489  // Build implicit 'p.get_return_object()' expression and form initialization
1490  // of return type from it.
1491  ExprResult ReturnObject =
1492  buildPromiseCall(S, Fn.CoroutinePromise, Loc, "get_return_object", None);
1493  if (ReturnObject.isInvalid())
1494  return false;
1495 
1496  this->ReturnValue = ReturnObject.get();
1497  return true;
1498 }
1499 
1501  if (auto *MbrRef = dyn_cast<CXXMemberCallExpr>(E)) {
1502  auto *MethodDecl = MbrRef->getMethodDecl();
1503  S.Diag(MethodDecl->getLocation(), diag::note_member_declared_here)
1504  << MethodDecl;
1505  }
1506  S.Diag(Fn.FirstCoroutineStmtLoc, diag::note_declared_coroutine_here)
1508 }
1509 
1510 bool CoroutineStmtBuilder::makeGroDeclAndReturnStmt() {
1511  assert(!IsPromiseDependentType &&
1512  "cannot make statement while the promise type is dependent");
1513  assert(this->ReturnValue && "ReturnValue must be already formed");
1514 
1515  QualType const GroType = this->ReturnValue->getType();
1516  assert(!GroType->isDependentType() &&
1517  "get_return_object type must no longer be dependent");
1518 
1519  QualType const FnRetType = FD.getReturnType();
1520  assert(!FnRetType->isDependentType() &&
1521  "get_return_object type must no longer be dependent");
1522 
1523  if (FnRetType->isVoidType()) {
1524  ExprResult Res =
1525  S.ActOnFinishFullExpr(this->ReturnValue, Loc, /*DiscardedValue*/ false);
1526  if (Res.isInvalid())
1527  return false;
1528 
1529  this->ResultDecl = Res.get();
1530  return true;
1531  }
1532 
1533  if (GroType->isVoidType()) {
1534  // Trigger a nice error message.
1535  InitializedEntity Entity =
1536  InitializedEntity::InitializeResult(Loc, FnRetType);
1539  return false;
1540  }
1541 
1542  auto *GroDecl = VarDecl::Create(
1543  S.Context, &FD, FD.getLocation(), FD.getLocation(),
1544  &S.PP.getIdentifierTable().get("__coro_gro"), GroType,
1545  S.Context.getTrivialTypeSourceInfo(GroType, Loc), SC_None);
1546  GroDecl->setImplicit();
1547 
1548  S.CheckVariableDeclarationType(GroDecl);
1549  if (GroDecl->isInvalidDecl())
1550  return false;
1551 
1553  ExprResult Res =
1555  if (Res.isInvalid())
1556  return false;
1557 
1558  Res = S.ActOnFinishFullExpr(Res.get(), /*DiscardedValue*/ false);
1559  if (Res.isInvalid())
1560  return false;
1561 
1562  S.AddInitializerToDecl(GroDecl, Res.get(),
1563  /*DirectInit=*/false);
1564 
1565  S.FinalizeDeclaration(GroDecl);
1566 
1567  // Form a declaration statement for the return declaration, so that AST
1568  // visitors can more easily find it.
1569  StmtResult GroDeclStmt =
1570  S.ActOnDeclStmt(S.ConvertDeclToDeclGroup(GroDecl), Loc, Loc);
1571  if (GroDeclStmt.isInvalid())
1572  return false;
1573 
1574  this->ResultDecl = GroDeclStmt.get();
1575 
1576  ExprResult declRef = S.BuildDeclRefExpr(GroDecl, GroType, VK_LValue, Loc);
1577  if (declRef.isInvalid())
1578  return false;
1579 
1580  StmtResult ReturnStmt = S.BuildReturnStmt(Loc, declRef.get());
1581  if (ReturnStmt.isInvalid()) {
1583  return false;
1584  }
1585  if (cast<clang::ReturnStmt>(ReturnStmt.get())->getNRVOCandidate() == GroDecl)
1586  GroDecl->setNRVOVariable(true);
1587 
1588  this->ReturnStmt = ReturnStmt.get();
1589  return true;
1590 }
1591 
1592 // Create a static_cast<T&&>(expr).
1593 static Expr *castForMoving(Sema &S, Expr *E, QualType T = QualType()) {
1594  if (T.isNull())
1595  T = E->getType();
1596  QualType TargetType = S.BuildReferenceType(
1597  T, /*SpelledAsLValue*/ false, SourceLocation(), DeclarationName());
1598  SourceLocation ExprLoc = E->getBeginLoc();
1599  TypeSourceInfo *TargetLoc =
1600  S.Context.getTrivialTypeSourceInfo(TargetType, ExprLoc);
1601 
1602  return S
1603  .BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
1604  SourceRange(ExprLoc, ExprLoc), E->getSourceRange())
1605  .get();
1606 }
1607 
1608 /// Build a variable declaration for move parameter.
1610  IdentifierInfo *II) {
1612  VarDecl *Decl = VarDecl::Create(S.Context, S.CurContext, Loc, Loc, II, Type,
1613  TInfo, SC_None);
1614  Decl->setImplicit();
1615  return Decl;
1616 }
1617 
1618 // Build statements that move coroutine function parameters to the coroutine
1619 // frame, and store them on the function scope info.
1621  assert(isa<FunctionDecl>(CurContext) && "not in a function scope");
1622  auto *FD = cast<FunctionDecl>(CurContext);
1623 
1624  auto *ScopeInfo = getCurFunction();
1625  if (!ScopeInfo->CoroutineParameterMoves.empty())
1626  return false;
1627 
1628  for (auto *PD : FD->parameters()) {
1629  if (PD->getType()->isDependentType())
1630  continue;
1631 
1632  ExprResult PDRefExpr =
1633  BuildDeclRefExpr(PD, PD->getType().getNonReferenceType(),
1634  ExprValueKind::VK_LValue, Loc); // FIXME: scope?
1635  if (PDRefExpr.isInvalid())
1636  return false;
1637 
1638  Expr *CExpr = nullptr;
1639  if (PD->getType()->getAsCXXRecordDecl() ||
1640  PD->getType()->isRValueReferenceType())
1641  CExpr = castForMoving(*this, PDRefExpr.get());
1642  else
1643  CExpr = PDRefExpr.get();
1644 
1645  auto D = buildVarDecl(*this, Loc, PD->getType(), PD->getIdentifier());
1646  AddInitializerToDecl(D, CExpr, /*DirectInit=*/true);
1647 
1648  // Convert decl to a statement.
1650  if (Stmt.isInvalid())
1651  return false;
1652 
1653  ScopeInfo->CoroutineParameterMoves.insert(std::make_pair(PD, Stmt.get()));
1654  }
1655  return true;
1656 }
1657 
1660  if (!Res)
1661  return StmtError();
1662  return Res;
1663 }
1664 
1666  SourceLocation FuncLoc) {
1667  if (!StdCoroutineTraitsCache) {
1668  if (auto StdExp = lookupStdExperimentalNamespace()) {
1669  LookupResult Result(*this,
1670  &PP.getIdentifierTable().get("coroutine_traits"),
1671  FuncLoc, LookupOrdinaryName);
1672  if (!LookupQualifiedName(Result, StdExp)) {
1673  Diag(KwLoc, diag::err_implied_coroutine_type_not_found)
1674  << "std::experimental::coroutine_traits";
1675  return nullptr;
1676  }
1677  if (!(StdCoroutineTraitsCache =
1678  Result.getAsSingle<ClassTemplateDecl>())) {
1679  Result.suppressDiagnostics();
1680  NamedDecl *Found = *Result.begin();
1681  Diag(Found->getLocation(), diag::err_malformed_std_coroutine_traits);
1682  return nullptr;
1683  }
1684  }
1685  }
1686  return StdCoroutineTraitsCache;
1687 }
clang::CoroutineBodyStmt::CtorArgs::InitialSuspend
Expr * InitialSuspend
Definition: StmtCXX.h:350
clang::NestedNameSpecifier::Create
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Definition: NestedNameSpecifier.cpp:59
clang::Sema::BuildDeclarationNameExpr
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3151
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:423
Builtins.h
clang::InitializedEntity::InitializeResult
static InitializedEntity InitializeResult(SourceLocation ReturnLoc, QualType Type)
Create the initialization entity for the result of a function.
Definition: Initialization.h:300
clang::Sema::FindAllocationFunctions
bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose=true)
Finds the overloads of operator new and delete that are appropriate for the allocation.
Definition: SemaExprCXX.cpp:2569
clang::CoroutineBodyStmt::CtorArgs::ParamMoves
ArrayRef< Stmt * > ParamMoves
Definition: StmtCXX.h:360
clang::isLambdaCallOperator
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
ReadySuspendResumeResult
Definition: SemaCoroutine.cpp:321
clang::InitializationKind::CreateForInit
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Definition: Initialization.h:698
clang::ASTContext::getTypeDeclType
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1538
clang::CleanupInfo::setExprNeedsCleanups
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
clang::sema::FunctionScopeInfo::getFirstCoroutineStmtKeyword
StringRef getFirstCoroutineStmtKeyword() const
Definition: ScopeInfo.h:492
clang::Scope::FnScope
@ FnScope
This indicates that the scope corresponds to a function, which means that labels are set here.
Definition: Scope.h:47
clang::Sema::BuildDeclRefExpr
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
Definition: SemaExpr.cpp:1932
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2537
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:780
clang::Decl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:426
clang::Sema::BuildCoroutineBodyStmt
StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs)
Definition: SemaCoroutine.cpp:1658
clang::CoroutineBodyStmt::CtorArgs::OnException
Stmt * OnException
Definition: StmtCXX.h:352
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:212
clang::sema::FunctionScopeInfo::CoroutineSuspends
std::pair< Stmt *, Stmt * > CoroutineSuspends
The initial and final coroutine suspend points.
Definition: ScopeInfo.h:211
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1347
clang::Type::isVoidPointerType
bool isVoidPointerType() const
Definition: Type.cpp:589
buildMemberCall
static ExprResult buildMemberCall(Sema &S, Expr *Base, SourceLocation Loc, StringRef Name, MultiExprArg Args)
Definition: SemaCoroutine.cpp:328
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1576
clang::Sema::lookupCoroutineTraits
ClassTemplateDecl * lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc)
Definition: SemaCoroutine.cpp:1665
clang::Sema::getCurFunction
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1899
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:78
clang::Sema::CheckVariableDeclarationType
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:7970
clang::Sema::BuildCoreturnStmt
StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit=false)
Definition: SemaCoroutine.cpp:964
buildCoroutineHandle
static ExprResult buildCoroutineHandle(Sema &S, QualType PromiseType, SourceLocation Loc)
Definition: SemaCoroutine.cpp:294
SemaInternal.h
clang::CoroutineBodyStmt::CtorArgs::FinalSuspend
Expr * FinalSuspend
Definition: StmtCXX.h:351
llvm::SmallVector
Definition: LLVM.h:38
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:592
IsOverloaded
static bool IsOverloaded(const UnresolvedSetImpl &Functions)
Definition: SemaOverload.cpp:13266
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:88
clang::Sema::ActOnFinishFullStmt
StmtResult ActOnFinishFullStmt(Stmt *Stmt)
Definition: SemaExprCXX.cpp:8627
buildVarDecl
static VarDecl * buildVarDecl(Sema &S, SourceLocation Loc, QualType Type, IdentifierInfo *II)
Build a variable declaration for move parameter.
Definition: SemaCoroutine.cpp:1609
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:249
clang::sema::FunctionScopeInfo::CoroutineParameterMoves
llvm::SmallMapVector< ParmVarDecl *, Stmt *, 4 > CoroutineParameterMoves
A mapping between the coroutine function parameters that were moved to the coroutine frame,...
Definition: ScopeInfo.h:208
clang::CoroutineStmtBuilder::buildDependentStatements
bool buildDependentStatements()
Build the coroutine body statements that require a non-dependent promise type in order to construct.
Definition: SemaCoroutine.cpp:1115
clang::Sema::FindUsualDeallocationFunction
FunctionDecl * FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name)
Definition: SemaExprCXX.cpp:3100
clang::QualType::getNonReferenceType
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:6620
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:652
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:673
clang::Expr::getObjectKind
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:437
checkNoThrow
static void checkNoThrow(Sema &S, const Stmt *E, llvm::SmallPtrSetImpl< const Decl * > &ThrowingDecls)
Recursively check E and all its children to see if any call target (including constructor call) is de...
Definition: SemaCoroutine.cpp:638
clang::Sema::LookupOperatorName
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition: Sema.h:3984
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
clang::Sema::BuildMemberReferenceExpr
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
Definition: SemaExprMember.cpp:740
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1834
buildOperatorCoawaitCall
static ExprResult buildOperatorCoawaitCall(Sema &SemaRef, SourceLocation Loc, Expr *E, UnresolvedLookupExpr *Lookup)
Build a call to 'operator co_await' if there is a suitable operator for the given expression.
Definition: SemaCoroutine.cpp:277
clang::Sema::CheckTemplateIdType
QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs)
Definition: SemaTemplate.cpp:3637
clang::Sema::LookupQualifiedName
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Definition: SemaLookup.cpp:2152
clang::Sema::buildCoroutineParameterMoves
bool buildCoroutineParameterMoves(SourceLocation Loc)
Definition: SemaCoroutine.cpp:1620
clang::RQ_RValue
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition: Type.h:1449
llvm::SmallPtrSet< const Decl *, 4 >
clang::Expr::isPRValue
bool isPRValue() const
Definition: Expr.h:271
clang::sema::FunctionScopeInfo::FirstSEHTryLoc
SourceLocation FirstSEHTryLoc
First SEH '__try' statement in the current function.
Definition: ScopeInfo.h:183
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:6955
clang::Sema::BuildCallExpr
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
Definition: SemaExpr.cpp:6395
clang::CoreturnStmt
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition: StmtCXX.h:456
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:64
clang::CallExpr::getCalleeDecl
Decl * getCalleeDecl()
Definition: Expr.h:2959
ASTLambda.h
clang::Sema::getStdNamespace
NamespaceDecl * getStdNamespace() const
Definition: SemaDeclCXX.cpp:11151
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:789
clang::Sema::AFS_Global
@ AFS_Global
Only look for allocation functions in the global scope.
Definition: Sema.h:6350
isValidCoroutineContext
static bool isValidCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword)
Definition: SemaCoroutine.cpp:188
diagReturnOnAllocFailure
static bool diagReturnOnAllocFailure(Sema &S, Expr *E, CXXRecordDecl *PromiseRecordDecl, FunctionScopeInfo &Fn)
Definition: SemaCoroutine.cpp:1145
clang::Sema::FindDeallocationFunction
bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl *&Operator, bool Diagnose=true)
Definition: SemaExprCXX.cpp:3136
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:145
ReadySuspendResumeResult::Results
Expr * Results[3]
Definition: SemaCoroutine.cpp:323
clang::OverloadExpr::decls_end
decls_iterator decls_end() const
Definition: ExprCXX.h:2975
clang::CoroutineBodyStmt::Create
static CoroutineBodyStmt * Create(const ASTContext &C, CtorArgs const &Args)
Definition: StmtCXX.cpp:86
clang::Preprocessor::getIdentifierTable
IdentifierTable & getIdentifierTable()
Definition: Preprocessor.h:967
clang::Sema::isUnevaluatedContext
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition: Sema.h:9129
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1129
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:411
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1490
Preprocessor.h
Overload.h
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
Decl.h
clang::Sema::checkFinalSuspendNoThrow
bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend)
Check that the expression co_await promise.final_suspend() shall not be potentially-throwing.
Definition: SemaCoroutine.cpp:691
clang::ParenListExpr::Create
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4448
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1569
clang::ExprEmpty
ExprResult ExprEmpty()
Definition: Ownership.h:289
clang::Sema::LookupMemberName
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:3980
clang::Sema::RequireCompleteType
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8418
llvm::MutableArrayRef
Definition: LLVM.h:35
clang::CoroutineBodyStmt::CtorArgs::ResultDecl
Stmt * ResultDecl
Definition: StmtCXX.h:357
clang::CoroutineBodyStmt::CtorArgs::Allocate
Expr * Allocate
Definition: StmtCXX.h:354
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6684
clang::CallExpr::getCallReturnType
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition: Expr.cpp:1513
clang::CallExpr::getDirectCallee
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition: Expr.h:2965
buildCoawaitCalls
static ReadySuspendResumeResult buildCoawaitCalls(Sema &S, VarDecl *CoroPromise, SourceLocation Loc, Expr *E)
Build calls to await_ready, await_suspend, and await_resume for a co_await expression.
Definition: SemaCoroutine.cpp:403
clang::Sema::BuildCXXNamedCast
ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens)
Definition: SemaCast.cpp:296
clang::UnresolvedLookupExpr
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3073
clang::OverloadExpr::decls_begin
decls_iterator decls_begin() const
Definition: ExprCXX.h:2972
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:564
clang::DependentCoawaitExpr
Represents a 'co_await' expression while the type of the promise is dependent.
Definition: ExprCXX.h:4800
clang::diff::Move
@ Move
Definition: ASTDiff.h:32
clang::Type::isClassType
bool isClassType() const
Definition: Type.cpp:557
clang::Sema::canCalleeThrow
static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc=SourceLocation())
Determine whether the callee of a particular function call can throw.
Definition: SemaExceptionSpec.cpp:1006
clang::TemplateArgumentListInfo::addArgument
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:604
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1103
checkCoroutineContext
static FunctionScopeInfo * checkCoroutineContext(Sema &S, SourceLocation Loc, StringRef Keyword, bool IsImplicit=false)
Check that this is a context in which a coroutine suspension can appear.
Definition: SemaCoroutine.cpp:608
clang::CoroutineStmtBuilder
Definition: CoroutineStmtBuilder.h:24
clang::Sema::FinalizeDeclaration
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:13367
clang::DeclarationNameTable::getCXXOperatorName
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Definition: DeclarationName.h:639
clang::sema::FunctionScopeInfo::CoroutinePromise
VarDecl * CoroutinePromise
The promise object for this coroutine, if any.
Definition: ScopeInfo.h:204
Std
LangStandard::Kind Std
Definition: InterpolatingCompilationDatabase.cpp:134
clang::Sema::BuildResolvedCoawaitExpr
ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit=false)
Definition: SemaCoroutine.cpp:860
clang::ASTContext::getRValueReferenceType
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
Definition: ASTContext.cpp:3408
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:558
clang::TemplateArgument
Represents a template argument.
Definition: TemplateBase.h:62
clang::Sema::AddInitializerToDecl
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:12160
clang::Sema::PerformContextuallyConvertToBool
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
Definition: SemaOverload.cpp:5596
clang::Stmt::children
child_range children()
Definition: Stmt.cpp:285
clang::Sema::ActOnCoroutineBodyStart
bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword)
Definition: SemaCoroutine.cpp:709
clang::UnresolvedLookupExpr::Create
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:369
clang::TemplateArgumentLoc
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:458
noteMemberDeclaredHere
static void noteMemberDeclaredHere(Sema &S, Expr *E, FunctionScopeInfo &Fn)
Definition: SemaCoroutine.cpp:1500
clang::UnresolvedSet
A set of unresolved declarations.
Definition: UnresolvedSet.h:148
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:876
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4102
clang::Type::isStructureType
bool isStructureType() const
Definition: Type.cpp:563
clang::Sema::ActOnCoyieldExpr
ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E)
Definition: SemaCoroutine.cpp:901
clang::CoroutineBodyStmt::CtorArgs
Definition: StmtCXX.h:347
lookupPromiseType
static QualType lookupPromiseType(Sema &S, const FunctionDecl *FD, SourceLocation KwLoc)
Look up the std::coroutine_traits<...>::promise_type for the given function type.
Definition: SemaCoroutine.cpp:52
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:3138
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1760
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:243
clang::LookupResult::getLookupName
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
ExprCXX.h
Base
clang::Decl::setImplicit
void setImplicit(bool I=true)
Definition: DeclBase.h:564
clang::FunctionProtoType::getRefQualifier
RefQualifierKind getRefQualifier() const
Retrieve the ref-qualifier associated with this function type.
Definition: Type.h:4243
findDeleteForPromise
static FunctionDecl * findDeleteForPromise(Sema &S, SourceLocation Loc, QualType PromiseType)
Definition: SemaCoroutine.cpp:1027
clang::Sema::ActOnCoreturnStmt
StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E)
Definition: SemaCoroutine.cpp:956
clang::Sema::LookupName
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
Definition: SemaLookup.cpp:1914
lookupMember
static LookupResult lookupMember(Sema &S, const char *Name, CXXRecordDecl *RD, SourceLocation Loc, bool &Res)
Definition: SemaCoroutine.cpp:32
clang::CoroutineBodyStmt::CtorArgs::ReturnValue
Expr * ReturnValue
Definition: StmtCXX.h:356
clang::Sema::ActOnDeclStmt
StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc)
Definition: SemaStmt.cpp:73
clang::ETK_None
@ ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5348
clang::Sema::ConvertDeclToDeclGroup
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:56
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:781
clang::CoroutineBodyStmt::CtorArgs::OnFallthrough
Stmt * OnFallthrough
Definition: StmtCXX.h:353
clang::Sema::StdCoroutineTraitsCache
ClassTemplateDecl * StdCoroutineTraitsCache
The C++ "std::coroutine_traits" template, which is defined in <coroutine_traits>
Definition: Sema.h:1126
clang::sema::FunctionScopeInfo
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:98
clang::VK_LValue
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:124
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7226
clang::InitializationSequence::Perform
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7987
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:255
clang::CoroutineStmtBuilder::buildStatements
bool buildStatements()
Build the coroutine body statements, including the "promise dependent" statements when the promise ty...
Definition: SemaCoroutine.cpp:1107
clang::Sema::computeDeclContext
DeclContext * computeDeclContext(QualType T)
Compute the DeclContext that is associated with the given type.
Definition: SemaCXXScopeSpec.cpp:53
clang::sema::FunctionScopeInfo::FirstCoroutineStmtLoc
SourceLocation FirstCoroutineStmtLoc
First coroutine statement in the current function.
Definition: ScopeInfo.h:173
clang::Type::isDependentType
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2174
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
clang::Sema::BuildReturnStmt
StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp)
Definition: SemaStmt.cpp:3913
clang::Sema::CreateBuiltinUnaryOp
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr)
Definition: SemaExpr.cpp:14804
clang::Stmt::getStmtClass
StmtClass getStmtClass() const
Definition: Stmt.h:1163
clang::Sema::ActOnFinishFullExpr
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6473
clang::Sema::ActOnCoawaitExpr
ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E)
Definition: SemaCoroutine.cpp:802
clang::CoroutineBodyStmt::CtorArgs::Deallocate
Expr * Deallocate
Definition: StmtCXX.h:355
clang::Sema::PerformCopyInitialization
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9896
clang::sema::FunctionScopeInfo::FirstReturnLoc
SourceLocation FirstReturnLoc
First 'return' statement in the current function.
Definition: ScopeInfo.h:176
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
clang::Sema::BuildCoyieldExpr
ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E)
Definition: SemaCoroutine.cpp:922
clang::ClassTemplateDecl
Declaration of a class template.
Definition: DeclTemplate.h:2247
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:192
clang::CoyieldExpr
Represents a 'co_yield' expression.
Definition: ExprCXX.h:4849
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3885
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:229
clang::CoroutineBodyStmt::CtorArgs::Promise
Stmt * Promise
Definition: StmtCXX.h:349
clang::Type::isSpecificPlaceholderType
bool isSpecificPlaceholderType(unsigned K) const
Test for a specific placeholder type.
Definition: Type.h:6944
ReadySuspendResumeResult::OpaqueValue
OpaqueValueExpr * OpaqueValue
Definition: SemaCoroutine.cpp:324
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:738
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:89
clang::Sema::CreateOverloadedUnaryOp
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
Definition: SemaOverload.cpp:13298
clang::Sema::AFS_Class
@ AFS_Class
Only look for allocation functions in the scope of the allocated class.
Definition: Sema.h:6353
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:355
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
clang::CoroutineBodyStmt
Represents the body of a coroutine.
Definition: StmtCXX.h:317
clang::CoawaitExpr
Represents a 'co_await' expression.
Definition: ExprCXX.h:4764
clang::sema::FunctionScopeInfo::isCoroutine
bool isCoroutine() const
Definition: ScopeInfo.h:480
clang::Type::isPlaceholderType
bool isPlaceholderType() const
Test for a type which does not represent an actual type-system type but is instead used as a placehol...
Definition: Type.h:6931
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::Sema::lookupStdExperimentalNamespace
NamespaceDecl * lookupStdExperimentalNamespace()
Definition: SemaDeclCXX.cpp:11156
clang::ASTContext::getElaboratedType
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
Definition: ASTContext.cpp:4862
clang::Type::isBooleanType
bool isBooleanType() const
Definition: Type.h:7071
buildStdNoThrowDeclRef
static Expr * buildStdNoThrowDeclRef(Sema &S, SourceLocation Loc)
Look up the std::nothrow object.
Definition: SemaCoroutine.cpp:996
clang::ASTContext::getLValueReferenceType
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Definition: ASTContext.cpp:3369
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
clang::Sema::MaybeCreateExprWithCleanups
Expr * MaybeCreateExprWithCleanups(Expr *SubExpr)
MaybeCreateExprWithCleanups - If the current full-expression requires any cleanups,...
Definition: SemaExprCXX.cpp:7102
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:567
ReadySuspendResumeResult::AwaitCallType
AwaitCallType
Definition: SemaCoroutine.cpp:322
clang::ActionResult< Expr * >
clang::Sema::Cleanup
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:766
buildOperatorCoawaitLookupExpr
static ExprResult buildOperatorCoawaitLookupExpr(Sema &SemaRef, Scope *S, SourceLocation Loc)
Definition: SemaCoroutine.cpp:254
lookupCoroutineHandleType
static QualType lookupCoroutineHandleType(Sema &S, QualType PromiseType, SourceLocation Loc)
Look up the std::experimental::coroutine_handle<PromiseType>.
Definition: SemaCoroutine.cpp:145
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2640
ScopeInfo.h
ReadySuspendResumeResult::IsInvalid
bool IsInvalid
Definition: SemaCoroutine.cpp:325
clang::StmtResult
ActionResult< Stmt * > StmtResult
Definition: Ownership.h:263
clang::Sema::AFS_Both
@ AFS_Both
Look for allocation functions in both the global scope and in the scope of the allocated class.
Definition: Sema.h:6356
clang::Sema::getCurScope
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition: Sema.h:12919
clang::Builtin::ID
ID
Definition: Builtins.h:48
clang
Definition: CalledOnceCheck.h:17
clang::CoroutineStmtBuilder::CoroutineStmtBuilder
CoroutineStmtBuilder(Sema &S, FunctionDecl &FD, sema::FunctionScopeInfo &Fn, Stmt *Body)
Construct a CoroutineStmtBuilder and initialize the promise statement and initial/final suspends from...
Definition: SemaCoroutine.cpp:1087
checkSuspensionContext
static void checkSuspensionContext(Sema &S, SourceLocation Loc, StringRef Keyword)
Definition: SemaCoroutine.cpp:789
clang::Scope::CatchScope
@ CatchScope
This is the scope of a C++ catch statement.
Definition: Scope.h:137
clang::LookupResult::asUnresolvedSet
const UnresolvedSetImpl & asUnresolvedSet() const
Definition: Lookup.h:331
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
isWithinCatchScope
static bool isWithinCatchScope(Scope *S)
Definition: SemaCoroutine.cpp:761
clang::Sema::isCompleteType
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition: Sema.h:2284
clang::Expr::getType
QualType getType() const
Definition: Expr.h:141
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:112
clang::Sema::BuildUnresolvedCoawaitExpr
ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr *Lookup)
Definition: SemaCoroutine.cpp:822
clang::TypeSourceInfo
A container of type source information.
Definition: Type.h:6395
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3809
clang::Sema::ActOnCXXThis
ExprResult ActOnCXXThis(SourceLocation loc)
Definition: SemaExprCXX.cpp:1375
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
clang::CoroutineBodyStmt::CtorArgs::Body
Stmt * Body
Definition: StmtCXX.h:348
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:48
clang::InitializedEntity::InitializeVariable
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
Definition: Initialization.h:249
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:507
clang::ASTContext::getTrivialTypeSourceInfo
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
Definition: ASTContext.cpp:2950
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6424
clang::Sema::buildCoroutinePromise
VarDecl * buildCoroutinePromise(SourceLocation Loc)
Definition: SemaCoroutine.cpp:508
clang::sema::FunctionScopeInfo::hasInvalidCoroutineSuspends
bool hasInvalidCoroutineSuspends() const
Definition: ScopeInfo.h:510
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
buildPromiseCall
static ExprResult buildPromiseCall(Sema &S, VarDecl *Promise, SourceLocation Loc, StringRef Name, MultiExprArg Args)
Definition: SemaCoroutine.cpp:495
clang::Sema::LookupOrdinaryName
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:3972
clang::Sema::CheckCompletedCoroutineBody
void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body)
Definition: SemaCoroutine.cpp:1052
clang::SC_None
@ SC_None
Definition: Specifiers.h:235
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:687
clang::Sema::BuildBuiltinCallExpr
Expr * BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs)
BuildBuiltinCallExpr - Create a call to a builtin function specified by Id.
Definition: SemaExpr.cpp:6602
clang::VarDecl::Create
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2033
clang::Expr
This represents one expression.
Definition: Expr.h:109
maybeTailCall
static Expr * maybeTailCall(Sema &S, QualType RetType, Expr *E, SourceLocation Loc)
Definition: SemaCoroutine.cpp:357
clang::CoroutineBodyStmt::CtorArgs::ReturnStmtOnAllocFailure
Stmt * ReturnStmtOnAllocFailure
Definition: StmtCXX.h:359
clang::Sema::PP
Preprocessor & PP
Definition: Sema.h:410
clang::Sema::BuildReferenceType
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
Definition: SemaType.cpp:2157
clang::Sema::MarkFunctionReferenced
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
Definition: SemaExpr.cpp:17080
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:758
castForMoving
static Expr * castForMoving(Sema &S, Expr *E, QualType T=QualType())
Definition: SemaCoroutine.cpp:1593
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2483
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:430
clang::UnresolvedSetImpl::append
void append(iterator I, iterator E)
Definition: UnresolvedSet.h:129
clang::NamespaceDecl
Represent a C++ namespace.
Definition: Decl.h:542
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1856
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2795
StmtCXX.h
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:524
clang::Preprocessor::getIdentifierInfo
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
Definition: Preprocessor.h:1243
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2760
CoroutineStmtBuilder.h
clang::VarDecl::CallInit
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:884
clang::StmtError
StmtResult StmtError()
Definition: Ownership.h:279
Initialization.h
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1948
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:301
clang::Sema::clearDelayedTypo
void clearDelayedTypo(TypoExpr *TE)
Clears the state of the given TypoExpr.
Definition: SemaLookup.cpp:5508
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:439