Skip to content

Commit 049c29d

Browse files
[Clang] Introduce [[clang::structured_concurrency]]
1 parent d6bbe2e commit 049c29d

File tree

13 files changed

+332
-12
lines changed

13 files changed

+332
-12
lines changed

clang/include/clang/Basic/Attr.td

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1212,6 +1212,14 @@ def CoroDisableLifetimeBound : InheritableAttr {
12121212
let SimpleHandler = 1;
12131213
}
12141214

1215+
def CoroStructuredConcurrencyType : InheritableAttr {
1216+
let Spellings = [Clang<"coro_structured_concurrency">];
1217+
let Subjects = SubjectList<[CXXRecord]>;
1218+
let LangOpts = [CPlusPlus];
1219+
let Documentation = [CoroStructuredConcurrencyDoc];
1220+
let SimpleHandler = 1;
1221+
}
1222+
12151223
// OSObject-based attributes.
12161224
def OSConsumed : InheritableParamAttr {
12171225
let Spellings = [Clang<"os_consumed">];

clang/include/clang/Basic/AttrDocs.td

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8015,6 +8015,26 @@ but do not pass them to the underlying coroutine or pass them by value.
80158015
}];
80168016
}
80178017

8018+
def CoroStructuredConcurrencyDoc : Documentation {
8019+
let Category = DocCatDecl;
8020+
let Content = [{
8021+
The ``[[clang::coro_structured_concurrency]]`` is a class attribute which can be applied
8022+
to a coroutine return type.
8023+
8024+
When a coroutine function that returns such a type calls another coroutine function,
8025+
the compiler performs heap allocation elision when the following conditions are all met:
8026+
- callee coroutine function returns a type that is annotated with
8027+
``[[clang::coro_structured_concurrency]]``.
8028+
- The callee coroutine function is inlined.
8029+
- In caller coroutine, the return value of the callee is a prvalue or an xvalue, and
8030+
- The temporary expression containing the callee coroutine object is immediately co_awaited.
8031+
8032+
The behavior is undefined if any of the following condition was met:
8033+
- the caller coroutine is destroyed earlier than the callee coroutine.
8034+
8035+
}];
8036+
}
8037+
80188038
def CountedByDocs : Documentation {
80198039
let Category = DocCatField;
80208040
let Content = [{

clang/lib/CodeGen/CGCoroutine.cpp

Lines changed: 71 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@
1212

1313
#include "CGCleanup.h"
1414
#include "CodeGenFunction.h"
15-
#include "llvm/ADT/ScopeExit.h"
15+
#include "clang/AST/ExprCXX.h"
1616
#include "clang/AST/StmtCXX.h"
1717
#include "clang/AST/StmtVisitor.h"
18+
#include "llvm/ADT/ArrayRef.h"
19+
#include "llvm/ADT/ScopeExit.h"
20+
#include "llvm/IR/Intrinsics.h"
1821

1922
using namespace clang;
2023
using namespace CodeGen;
@@ -219,17 +222,81 @@ namespace {
219222
RValue RV;
220223
};
221224
}
225+
226+
static MaterializeTemporaryExpr *
227+
getStructuredConcurrencyOperand(ASTContext &Ctx,
228+
CoroutineSuspendExpr const &S) {
229+
auto *E = S.getCommonExpr();
230+
auto *Temporary = dyn_cast_or_null<MaterializeTemporaryExpr>(E);
231+
if (!Temporary)
232+
return nullptr;
233+
234+
auto *Operator =
235+
dyn_cast_or_null<CXXOperatorCallExpr>(Temporary->getSubExpr());
236+
237+
if (!Operator ||
238+
Operator->getOperator() != OverloadedOperatorKind::OO_Coawait ||
239+
Operator->getNumArgs() != 1)
240+
return nullptr;
241+
242+
Expr *Arg = Operator->getArg(0);
243+
assert(Arg && "Arg to operator co_await should not be null");
244+
auto *CalleeRetClass = Arg->getType()->getAsCXXRecordDecl();
245+
246+
if (!CalleeRetClass ||
247+
!CalleeRetClass->hasAttr<CoroStructuredConcurrencyTypeAttr>())
248+
return nullptr;
249+
250+
if (!Arg->isTemporaryObject(Ctx, CalleeRetClass)) {
251+
return nullptr;
252+
}
253+
254+
return dyn_cast<MaterializeTemporaryExpr>(Arg);
255+
}
256+
222257
static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
223258
CoroutineSuspendExpr const &S,
224259
AwaitKind Kind, AggValueSlot aggSlot,
225260
bool ignoreResult, bool forLValue) {
226261
auto *E = S.getCommonExpr();
227262

263+
auto &Builder = CGF.Builder;
264+
bool MarkOperandSafeIntrinsic = false;
265+
266+
auto *TemporaryOperand = [&]() -> MaterializeTemporaryExpr * {
267+
bool CurFnRetTyHasAttr = false;
268+
if (auto *RetTyPtr = CGF.FnRetTy.getTypePtrOrNull()) {
269+
if (auto *CxxRecord = RetTyPtr->getAsCXXRecordDecl()) {
270+
CurFnRetTyHasAttr =
271+
CxxRecord->hasAttr<CoroStructuredConcurrencyTypeAttr>();
272+
}
273+
}
274+
275+
if (CurFnRetTyHasAttr) {
276+
return getStructuredConcurrencyOperand(CGF.getContext(), S);
277+
}
278+
return nullptr;
279+
}();
280+
281+
if (TemporaryOperand) {
282+
CGF.TemporaryValues[TemporaryOperand] = nullptr;
283+
MarkOperandSafeIntrinsic = true;
284+
}
285+
228286
auto CommonBinder =
229287
CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
230288
auto UnbindCommonOnExit =
231289
llvm::make_scope_exit([&] { CommonBinder.unbind(CGF); });
232290

291+
if (MarkOperandSafeIntrinsic) {
292+
auto It = CGF.TemporaryValues.find(TemporaryOperand);
293+
assert(It != CGF.TemporaryValues.end());
294+
if (auto Value = It->second)
295+
Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_safe_elide),
296+
{Value});
297+
CGF.TemporaryValues.erase(TemporaryOperand);
298+
}
299+
233300
auto Prefix = buildSuspendPrefixStr(Coro, Kind);
234301
BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
235302
BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
@@ -241,7 +308,6 @@ static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Co
241308
// Otherwise, emit suspend logic.
242309
CGF.EmitBlock(SuspendBlock);
243310

244-
auto &Builder = CGF.Builder;
245311
llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
246312
auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
247313
auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
@@ -255,9 +321,9 @@ static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Co
255321
"expected to be called in coroutine context");
256322

257323
SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
258-
SuspendIntrinsicCallArgs.push_back(
259-
CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF));
260-
324+
auto *BoundAwaiterValue =
325+
CGF.getOrCreateOpaqueLValueMapping(S.getOpaqueValue()).getPointer(CGF);
326+
SuspendIntrinsicCallArgs.push_back(BoundAwaiterValue);
261327
SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
262328
SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
263329

clang/lib/CodeGen/CGExpr.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -618,7 +618,11 @@ EmitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *M) {
618618
}
619619
}
620620

621-
return MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
621+
auto Ret = MakeAddrLValue(Object, M->getType(), AlignmentSource::Decl);
622+
if (TemporaryValues.contains(M)) {
623+
TemporaryValues[M] = Ret.getPointer(*this);
624+
}
625+
return Ret;
622626
}
623627

624628
RValue

clang/lib/CodeGen/CodeGenFunction.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,6 +369,9 @@ class CodeGenFunction : public CodeGenTypeCache {
369369
};
370370
CGCoroInfo CurCoro;
371371

372+
llvm::SmallDenseMap<const MaterializeTemporaryExpr *, llvm::Value *>
373+
TemporaryValues;
374+
372375
bool isCoroutine() const {
373376
return CurCoro.Data != nullptr;
374377
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
// This is a mock file for <utility>
2+
3+
namespace std {
4+
5+
template <typename T> struct remove_reference { using type = T; };
6+
template <typename T> struct remove_reference<T &> { using type = T; };
7+
template <typename T> struct remove_reference<T &&> { using type = T; };
8+
9+
template <typename T>
10+
constexpr typename std::remove_reference<T>::type&& move(T &&t) noexcept {
11+
return static_cast<typename std::remove_reference<T>::type &&>(t);
12+
}
13+
}
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// This file tests the coro_structured_concurrency attribute semantics.
2+
// RUN: %clang_cc1 -std=c++20 -disable-llvm-passes -emit-llvm %s -o - | FileCheck %s
3+
4+
#include "Inputs/coroutine.h"
5+
#include "Inputs/utility.h"
6+
7+
template <typename T>
8+
struct [[clang::coro_structured_concurrency]] Task {
9+
struct promise_type {
10+
struct FinalAwaiter {
11+
bool await_ready() const noexcept { return false; }
12+
13+
template <typename P>
14+
std::coroutine_handle<> await_suspend(std::coroutine_handle<P> coro) noexcept {
15+
if (!coro)
16+
return std::noop_coroutine();
17+
return coro.promise().continuation;
18+
}
19+
void await_resume() noexcept {}
20+
};
21+
22+
Task get_return_object() noexcept {
23+
return std::coroutine_handle<promise_type>::from_promise(*this);
24+
}
25+
26+
std::suspend_always initial_suspend() noexcept { return {}; }
27+
FinalAwaiter final_suspend() noexcept { return {}; }
28+
void unhandled_exception() noexcept {}
29+
void return_value(T x) noexcept {
30+
value = x;
31+
}
32+
33+
std::coroutine_handle<> continuation;
34+
T value;
35+
};
36+
37+
Task(std::coroutine_handle<promise_type> handle) : handle(handle) {}
38+
~Task() {
39+
if (handle)
40+
handle.destroy();
41+
}
42+
43+
struct Awaiter {
44+
Awaiter(Task *t) : task(t) {}
45+
bool await_ready() const noexcept { return false; }
46+
void await_suspend(std::coroutine_handle<void> continuation) noexcept {}
47+
T await_resume() noexcept {
48+
return task->handle.promise().value;
49+
}
50+
51+
Task *task;
52+
};
53+
54+
auto operator co_await() {
55+
return Awaiter{this};
56+
}
57+
58+
private:
59+
std::coroutine_handle<promise_type> handle;
60+
};
61+
62+
// CHECK-LABEL: define{{.*}} @_Z6calleev
63+
Task<int> callee() {
64+
co_return 1;
65+
}
66+
67+
// CHECK-LABEL: define{{.*}} @_Z8elidablev
68+
Task<int> elidable() {
69+
// CHECK: %[[TARK_OBJ:.+]] = alloca %struct.Task
70+
// CHECK: call void @llvm.coro.safe.elide(ptr %[[TARK_OBJ:.+]])
71+
co_return co_await callee();
72+
}
73+
74+
// CHECK-LABEL: define{{.*}} @_Z11nonelidablev
75+
Task<int> nonelidable() {
76+
// CHECK: %[[TARK_OBJ:.+]] = alloca %struct.Task
77+
auto t = callee();
78+
// Because we aren't co_awaiting a prvalue, we cannot elide here.
79+
// CHECK-NOT: call void @llvm.coro.safe.elide(ptr %[[TARK_OBJ:.+]])
80+
co_await t;
81+
co_await std::move(t);
82+
83+
co_return 1;
84+
}

clang/test/Misc/pragma-attribute-supported-attributes-list.test

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@
6262
// CHECK-NEXT: CoroLifetimeBound (SubjectMatchRule_record)
6363
// CHECK-NEXT: CoroOnlyDestroyWhenComplete (SubjectMatchRule_record)
6464
// CHECK-NEXT: CoroReturnType (SubjectMatchRule_record)
65+
// CHECK-NEXT: CoroStructuredConcurrencyType (SubjectMatchRule_record)
6566
// CHECK-NEXT: CoroWrapper (SubjectMatchRule_function)
6667
// CHECK-NEXT: DLLExport (SubjectMatchRule_function, SubjectMatchRule_variable, SubjectMatchRule_record, SubjectMatchRule_objc_interface)
6768
// CHECK-NEXT: DLLImport (SubjectMatchRule_function, SubjectMatchRule_variable, SubjectMatchRule_record, SubjectMatchRule_objc_interface)

llvm/include/llvm/IR/Intrinsics.td

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1733,6 +1733,9 @@ def int_coro_subfn_addr : DefaultAttrsIntrinsic<
17331733
[IntrReadMem, IntrArgMemOnly, ReadOnly<ArgIndex<0>>,
17341734
NoCapture<ArgIndex<0>>]>;
17351735

1736+
def int_coro_safe_elide : DefaultAttrsIntrinsic<
1737+
[], [llvm_ptr_ty], []>;
1738+
17361739
///===-------------------------- Other Intrinsics --------------------------===//
17371740
//
17381741
// TODO: We should introduce a new memory kind fo traps (and other side effects

llvm/lib/Transforms/Coroutines/CoroCleanup.cpp

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,11 @@
88

99
#include "llvm/Transforms/Coroutines/CoroCleanup.h"
1010
#include "CoroInternal.h"
11+
#include "llvm/IR/Function.h"
1112
#include "llvm/IR/IRBuilder.h"
1213
#include "llvm/IR/InstIterator.h"
14+
#include "llvm/IR/Intrinsics.h"
1315
#include "llvm/IR/PassManager.h"
14-
#include "llvm/IR/Function.h"
1516
#include "llvm/Transforms/Scalar/SimplifyCFG.h"
1617

1718
using namespace llvm;
@@ -80,7 +81,7 @@ bool Lowerer::lower(Function &F) {
8081
} else
8182
continue;
8283
break;
83-
case Intrinsic::coro_async_size_replace:
84+
case Intrinsic::coro_async_size_replace: {
8485
auto *Target = cast<ConstantStruct>(
8586
cast<GlobalVariable>(II->getArgOperand(0)->stripPointerCasts())
8687
->getInitializer());
@@ -98,6 +99,9 @@ bool Lowerer::lower(Function &F) {
9899
Target->replaceAllUsesWith(NewFuncPtrStruct);
99100
break;
100101
}
102+
case Intrinsic::coro_safe_elide:
103+
break;
104+
}
101105
II->eraseFromParent();
102106
Changed = true;
103107
}
@@ -111,7 +115,8 @@ static bool declaresCoroCleanupIntrinsics(const Module &M) {
111115
M, {"llvm.coro.alloc", "llvm.coro.begin", "llvm.coro.subfn.addr",
112116
"llvm.coro.free", "llvm.coro.id", "llvm.coro.id.retcon",
113117
"llvm.coro.id.async", "llvm.coro.id.retcon.once",
114-
"llvm.coro.async.size.replace", "llvm.coro.async.resume"});
118+
"llvm.coro.async.size.replace", "llvm.coro.async.resume",
119+
"llvm.coro.safe.elide"});
115120
}
116121

117122
PreservedAnalyses CoroCleanupPass::run(Module &M,

0 commit comments

Comments
 (0)