Skip to content

Commit 9247013

Browse files
authored
[SemaCXX] Implement CWG2137 (list-initialization from objects of the same type) (#77768)
Closes #77638, #24186 Rebased from <https://reviews.llvm.org/D156032>, see there for more information. Implements wording change in [CWG2137](https://wg21.link/CWG2137) in the first commit. This also implements an approach to [CWG2311](https://wg21.link/CWG2311) in the second commit, because too much code that relies on `T{ T_prvalue}` being an elision would break. Because that issue is still open and the CWG issue doesn't provide wording to fix the issue, there may be different behaviours on other compilers.
1 parent 2b31a67 commit 9247013

File tree

8 files changed

+215
-33
lines changed

8 files changed

+215
-33
lines changed

clang/docs/ReleaseNotes.rst

+5
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,11 @@ C++2c Feature Support
229229

230230
Resolutions to C++ Defect Reports
231231
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
232+
- Implemented `CWG2137 <https://wg21.link/CWG2137>`_ which allows
233+
list-initialization from objects of the same type.
234+
- Implemented `CWG2311 <https://wg21.link/CWG2311>`_: given a prvalue ``e`` of object type
235+
``T``, ``T{e}`` will try to resolve an initializer list constructor and will use it if successful (CWG2137).
236+
Otherwise, if there is no initializer list constructor, the copy will be elided as if it was ``T(e)``.
232237

233238
- Implemented `CWG2598 <https://wg21.link/CWG2598>`_ and `CWG2096 <https://wg21.link/CWG2096>`_,
234239
making unions (that have either no members or at least one literal member) literal types.

clang/lib/Sema/SemaInit.cpp

+30-10
Original file line numberDiff line numberDiff line change
@@ -4200,7 +4200,7 @@ static OverloadingResult ResolveConstructorOverload(
42004200
/// \param IsListInit Is this list-initialization?
42014201
/// \param IsInitListCopy Is this non-list-initialization resulting from a
42024202
/// list-initialization from {x} where x is the same
4203-
/// type as the entity?
4203+
/// aggregate type as the entity?
42044204
static void TryConstructorInitialization(Sema &S,
42054205
const InitializedEntity &Entity,
42064206
const InitializationKind &Kind,
@@ -4230,6 +4230,14 @@ static void TryConstructorInitialization(Sema &S,
42304230
Entity.getKind() !=
42314231
InitializedEntity::EK_LambdaToBlockConversionBlockElement);
42324232

4233+
bool CopyElisionPossible = false;
4234+
auto ElideConstructor = [&] {
4235+
// Convert qualifications if necessary.
4236+
Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4237+
if (ILE)
4238+
Sequence.RewrapReferenceInitList(DestType, ILE);
4239+
};
4240+
42334241
// C++17 [dcl.init]p17:
42344242
// - If the initializer expression is a prvalue and the cv-unqualified
42354243
// version of the source type is the same class as the class of the
@@ -4242,11 +4250,17 @@ static void TryConstructorInitialization(Sema &S,
42424250
if (S.getLangOpts().CPlusPlus17 && !RequireActualConstructor &&
42434251
UnwrappedArgs.size() == 1 && UnwrappedArgs[0]->isPRValue() &&
42444252
S.Context.hasSameUnqualifiedType(UnwrappedArgs[0]->getType(), DestType)) {
4245-
// Convert qualifications if necessary.
4246-
Sequence.AddQualificationConversionStep(DestType, VK_PRValue);
4247-
if (ILE)
4248-
Sequence.RewrapReferenceInitList(DestType, ILE);
4249-
return;
4253+
if (ILE && !DestType->isAggregateType()) {
4254+
// CWG2311: T{ prvalue_of_type_T } is not eligible for copy elision
4255+
// Make this an elision if this won't call an initializer-list
4256+
// constructor. (Always on an aggregate type or check constructors first.)
4257+
assert(!IsInitListCopy &&
4258+
"IsInitListCopy only possible with aggregate types");
4259+
CopyElisionPossible = true;
4260+
} else {
4261+
ElideConstructor();
4262+
return;
4263+
}
42504264
}
42514265

42524266
const RecordType *DestRecordType = DestType->getAs<RecordType>();
@@ -4291,6 +4305,12 @@ static void TryConstructorInitialization(Sema &S,
42914305
S, Kind.getLocation(), Args, CandidateSet, DestType, Ctors, Best,
42924306
CopyInitialization, AllowExplicit,
42934307
/*OnlyListConstructors=*/true, IsListInit, RequireActualConstructor);
4308+
4309+
if (CopyElisionPossible && Result == OR_No_Viable_Function) {
4310+
// No initializer list candidate
4311+
ElideConstructor();
4312+
return;
4313+
}
42944314
}
42954315

42964316
// C++11 [over.match.list]p1:
@@ -4572,9 +4592,9 @@ static void TryListInitialization(Sema &S,
45724592
return;
45734593
}
45744594

4575-
// C++11 [dcl.init.list]p3, per DR1467:
4576-
// - If T is a class type and the initializer list has a single element of
4577-
// type cv U, where U is T or a class derived from T, the object is
4595+
// C++11 [dcl.init.list]p3, per DR1467 and DR2137:
4596+
// - If T is an aggregate class and the initializer list has a single element
4597+
// of type cv U, where U is T or a class derived from T, the object is
45784598
// initialized from that element (by copy-initialization for
45794599
// copy-list-initialization, or by direct-initialization for
45804600
// direct-list-initialization).
@@ -4585,7 +4605,7 @@ static void TryListInitialization(Sema &S,
45854605
// - Otherwise, if T is an aggregate, [...] (continue below).
45864606
if (S.getLangOpts().CPlusPlus11 && InitList->getNumInits() == 1 &&
45874607
!IsDesignatedInit) {
4588-
if (DestType->isRecordType()) {
4608+
if (DestType->isRecordType() && DestType->isAggregateType()) {
45894609
QualType InitType = InitList->getInit(0)->getType();
45904610
if (S.Context.hasSameUnqualifiedType(InitType, DestType) ||
45914611
S.IsDerivedFrom(InitList->getBeginLoc(), InitType, DestType)) {

clang/lib/Sema/SemaOverload.cpp

+28-10
Original file line numberDiff line numberDiff line change
@@ -1568,19 +1568,37 @@ TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
15681568
// called for those cases.
15691569
if (CXXConstructorDecl *Constructor
15701570
= dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1571-
QualType FromCanon
1572-
= S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1571+
QualType FromType;
1572+
SourceLocation FromLoc;
1573+
// C++11 [over.ics.list]p6, per DR2137:
1574+
// C++17 [over.ics.list]p6:
1575+
// If C is not an initializer-list constructor and the initializer list
1576+
// has a single element of type cv U, where U is X or a class derived
1577+
// from X, the implicit conversion sequence has Exact Match rank if U is
1578+
// X, or Conversion rank if U is derived from X.
1579+
if (const auto *InitList = dyn_cast<InitListExpr>(From);
1580+
InitList && InitList->getNumInits() == 1 &&
1581+
!S.isInitListConstructor(Constructor)) {
1582+
const Expr *SingleInit = InitList->getInit(0);
1583+
FromType = SingleInit->getType();
1584+
FromLoc = SingleInit->getBeginLoc();
1585+
} else {
1586+
FromType = From->getType();
1587+
FromLoc = From->getBeginLoc();
1588+
}
1589+
QualType FromCanon =
1590+
S.Context.getCanonicalType(FromType.getUnqualifiedType());
15731591
QualType ToCanon
15741592
= S.Context.getCanonicalType(ToType).getUnqualifiedType();
15751593
if (Constructor->isCopyConstructor() &&
15761594
(FromCanon == ToCanon ||
1577-
S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1595+
S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
15781596
// Turn this into a "standard" conversion sequence, so that it
15791597
// gets ranked with standard conversion sequences.
15801598
DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
15811599
ICS.setStandard();
15821600
ICS.Standard.setAsIdentityConversion();
1583-
ICS.Standard.setFromType(From->getType());
1601+
ICS.Standard.setFromType(FromType);
15841602
ICS.Standard.setAllToTypes(ToType);
15851603
ICS.Standard.CopyConstructor = Constructor;
15861604
ICS.Standard.FoundCopyConstructor = Found;
@@ -5306,18 +5324,18 @@ TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
53065324
IsDesignatedInit)
53075325
return Result;
53085326

5309-
// Per DR1467:
5310-
// If the parameter type is a class X and the initializer list has a single
5311-
// element of type cv U, where U is X or a class derived from X, the
5312-
// implicit conversion sequence is the one required to convert the element
5313-
// to the parameter type.
5327+
// Per DR1467 and DR2137:
5328+
// If the parameter type is an aggregate class X and the initializer list
5329+
// has a single element of type cv U, where U is X or a class derived from
5330+
// X, the implicit conversion sequence is the one required to convert the
5331+
// element to the parameter type.
53145332
//
53155333
// Otherwise, if the parameter type is a character array [... ]
53165334
// and the initializer list has a single element that is an
53175335
// appropriately-typed string literal (8.5.2 [dcl.init.string]), the
53185336
// implicit conversion sequence is the identity conversion.
53195337
if (From->getNumInits() == 1 && !IsDesignatedInit) {
5320-
if (ToType->isRecordType()) {
5338+
if (ToType->isRecordType() && ToType->isAggregateType()) {
53215339
QualType InitType = From->getInit(0)->getType();
53225340
if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
53235341
S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))

clang/test/CXX/drs/dr14xx.cpp

-10
Original file line numberDiff line numberDiff line change
@@ -488,16 +488,6 @@ namespace dr1467 { // dr1467: 3.7 c++11
488488
}
489489
} // nonaggregate
490490

491-
namespace SelfInitIsNotListInit {
492-
struct S {
493-
S();
494-
explicit S(S &);
495-
S(const S &);
496-
};
497-
S s1;
498-
S s2 = {s1}; // ok, not list-initialization so we pick the non-explicit constructor
499-
}
500-
501491
struct NestedInit { int a, b, c; };
502492
NestedInit ni[1] = {{NestedInit{1, 2, 3}}};
503493

clang/test/CXX/drs/dr21xx.cpp

+45
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,16 @@
1111
// cxx98-error@-1 {{variadic macros are a C99 feature}}
1212
#endif
1313

14+
namespace std {
15+
__extension__ typedef __SIZE_TYPE__ size_t;
16+
17+
template<typename E> struct initializer_list {
18+
const E *p; size_t n;
19+
initializer_list(const E *p, size_t n);
20+
initializer_list();
21+
};
22+
}
23+
1424
namespace dr2100 { // dr2100: 12
1525
template<const int *P, bool = true> struct X {};
1626
template<typename T> struct A {
@@ -132,6 +142,41 @@ namespace dr2126 { // dr2126: 12
132142
#endif
133143
}
134144

145+
namespace dr2137 { // dr2137: 18
146+
#if __cplusplus >= 201103L
147+
struct Q {
148+
Q();
149+
Q(Q&&);
150+
Q(std::initializer_list<Q>) = delete; // #dr2137-Qcons
151+
};
152+
153+
Q x = Q { Q() };
154+
// since-cxx11-error@-1 {{call to deleted constructor of 'Q'}}
155+
// since-cxx11-note@#dr2137-Qcons {{'Q' has been explicitly marked deleted here}}
156+
157+
int f(Q); // #dr2137-f
158+
int y = f({ Q() });
159+
// since-cxx11-error@-1 {{call to deleted constructor of 'Q'}}
160+
// since-cxx11-note@#dr2137-Qcons {{'Q' has been explicitly marked deleted here}}
161+
// since-cxx11-note@#dr2137-f {{passing argument to parameter here}}
162+
163+
struct U {
164+
U();
165+
U(const U&);
166+
};
167+
168+
struct Derived : U {
169+
Derived();
170+
Derived(const Derived&);
171+
} d;
172+
173+
int g(Derived);
174+
int g(U(&&)[1]) = delete;
175+
176+
int z = g({ d });
177+
#endif
178+
}
179+
135180
namespace dr2140 { // dr2140: 9
136181
#if __cplusplus >= 201103L
137182
union U { int a; decltype(nullptr) b; };

clang/test/CXX/drs/dr23xx.cpp

+85
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,16 @@
66
// RUN: %clang_cc1 -std=c++23 %s -verify=expected,since-cxx11,since-cxx14,since-cxx17,since-cxx20 -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
77
// RUN: %clang_cc1 -std=c++2c %s -verify=expected,since-cxx11,since-cxx14,since-cxx17,since-cxx20 -fexceptions -fcxx-exceptions -pedantic-errors 2>&1 | FileCheck %s
88

9+
namespace std {
10+
__extension__ typedef __SIZE_TYPE__ size_t;
11+
12+
template<typename E> struct initializer_list {
13+
const E *p; size_t n;
14+
initializer_list(const E *p, size_t n);
15+
initializer_list();
16+
};
17+
}
18+
919
#if __cplusplus >= 201103L
1020
namespace dr2303 { // dr2303: 12
1121
template <typename... T>
@@ -47,6 +57,81 @@ void g() {
4757
} //namespace dr2303
4858
#endif
4959

60+
namespace dr2311 { // dr2311: 18 open
61+
#if __cplusplus >= 201707L
62+
template<typename T>
63+
void test() {
64+
// Ensure none of these try to call a move constructor.
65+
T a = T{T(0)};
66+
T b{T(0)};
67+
auto c{T(0)};
68+
T d = {T(0)};
69+
auto e = {T(0)};
70+
#if __cplusplus >= 202302L
71+
auto f = auto{T(0)};
72+
#endif
73+
void(*fn)(T);
74+
fn({T(0)});
75+
}
76+
77+
struct NonMovable {
78+
NonMovable(int);
79+
NonMovable(NonMovable&&) = delete;
80+
};
81+
struct NonMovableNonApplicableIList {
82+
NonMovableNonApplicableIList(int);
83+
NonMovableNonApplicableIList(NonMovableNonApplicableIList&&) = delete;
84+
NonMovableNonApplicableIList(std::initializer_list<int>);
85+
};
86+
struct ExplicitMovable {
87+
ExplicitMovable(int);
88+
explicit ExplicitMovable(ExplicitMovable&&);
89+
};
90+
struct ExplicitNonMovable {
91+
ExplicitNonMovable(int);
92+
explicit ExplicitNonMovable(ExplicitNonMovable&&) = delete;
93+
};
94+
struct ExplicitNonMovableNonApplicableIList {
95+
ExplicitNonMovableNonApplicableIList(int);
96+
explicit ExplicitNonMovableNonApplicableIList(ExplicitNonMovableNonApplicableIList&&) = delete;
97+
ExplicitNonMovableNonApplicableIList(std::initializer_list<int>);
98+
};
99+
struct CopyOnly {
100+
CopyOnly(int);
101+
CopyOnly(const CopyOnly&);
102+
CopyOnly(CopyOnly&&) = delete;
103+
};
104+
struct ExplicitCopyOnly {
105+
ExplicitCopyOnly(int);
106+
explicit ExplicitCopyOnly(const ExplicitCopyOnly&);
107+
explicit ExplicitCopyOnly(ExplicitCopyOnly&&) = delete;
108+
};
109+
110+
template void test<NonMovable>();
111+
template void test<NonMovableNonApplicableIList>();
112+
template void test<ExplicitMovable>();
113+
template void test<ExplicitNonMovable>();
114+
template void test<ExplicitNonMovableNonApplicableIList>();
115+
template void test<CopyOnly>();
116+
template void test<ExplicitCopyOnly>();
117+
118+
struct any {
119+
template<typename T>
120+
any(T&&);
121+
};
122+
123+
template<typename T>
124+
struct X {
125+
X();
126+
X(T) = delete; // #dr2311-X
127+
};
128+
129+
X<std::initializer_list<any>> x{ X<std::initializer_list<any>>() };
130+
// since-cxx17-error@-1 {{call to deleted constructor of 'X<std::initializer_list<any>>'}}
131+
// since-cxx17-note@#dr2311-X {{'X' has been explicitly marked deleted here}}
132+
#endif
133+
}
134+
50135
// dr2331: na
51136
// dr2335 is in dr2335.cxx
52137

clang/www/cxx_dr_status.html

+2-2
Original file line numberDiff line numberDiff line change
@@ -12630,7 +12630,7 @@ <h2 id="cxxdr">C++ defect report implementation status</h2>
1263012630
<td><a href="https://cplusplus.github.io/CWG/issues/2137.html">2137</a></td>
1263112631
<td>CD4</td>
1263212632
<td>List-initialization from object of same type</td>
12633-
<td class="unknown" align="center">Unknown</td>
12633+
<td class="unreleased" align="center">Clang 18</td>
1263412634
</tr>
1263512635
<tr id="2138">
1263612636
<td><a href="https://cplusplus.github.io/CWG/issues/2138.html">2138</a></td>
@@ -13674,7 +13674,7 @@ <h2 id="cxxdr">C++ defect report implementation status</h2>
1367413674
<td><a href="https://cplusplus.github.io/CWG/issues/2311.html">2311</a></td>
1367513675
<td>open</td>
1367613676
<td>Missed case for guaranteed copy elision</td>
13677-
<td align="center">Not resolved</td>
13677+
<td class="unreleased" align="center">Clang 18</td>
1367813678
</tr>
1367913679
<tr id="2312">
1368013680
<td><a href="https://cplusplus.github.io/CWG/issues/2312.html">2312</a></td>

libcxx/test/std/utilities/utility/pairs/pairs.pair/ctor.pair_U_V_move.pass.cpp

+20-1
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,26 @@ int main(int, char**)
121121
test_pair_rv<CopyOnly, CopyOnly&>();
122122
test_pair_rv<CopyOnly, CopyOnly&&>();
123123

124-
test_pair_rv<ExplicitTypes::CopyOnly, ExplicitTypes::CopyOnly>();
124+
/* For ExplicitTypes::CopyOnly, two of the viable candidates for initializing from a non-const xvalue are:
125+
* pair(const pair&); // (defaulted copy constructor)
126+
* template<class U1, class U2> explicit pair(const pair<U1, U2>&&); [U1 = ExplicitTypes::CopyOnly, U2 = int]
127+
* This results in diverging behavior for test_convertible which uses copy-list-initialization
128+
* Prior to CWG2137, this would have selected the first (non-explicit) ctor as explicit ctors would not be considered
129+
* Afterwards, it should select the second since it is a better match, and then failed because it is explicit
130+
*
131+
* This may change with future defect reports, and some compilers only have partial support for CWG2137,
132+
* so use std::is_convertible directly to avoid a copy-list-initialization
133+
*/
134+
{
135+
using P1 = std::pair<ExplicitTypes::CopyOnly, int>;
136+
using P2 = std::pair<int, ExplicitTypes::CopyOnly>;
137+
using UP1 = std::pair<ExplicitTypes::CopyOnly, int>&&;
138+
using UP2 = std::pair<int, ExplicitTypes::CopyOnly>&&;
139+
static_assert(std::is_constructible<P1, UP1>::value, "");
140+
static_assert(std::is_convertible<P1, UP1>::value, "");
141+
static_assert(std::is_constructible<P2, UP2>::value, "");
142+
static_assert(std::is_convertible<P2, UP2>::value, "");
143+
}
125144
test_pair_rv<ExplicitTypes::CopyOnly, ExplicitTypes::CopyOnly&, true, false>();
126145
test_pair_rv<ExplicitTypes::CopyOnly, ExplicitTypes::CopyOnly&&, true, false>();
127146

0 commit comments

Comments
 (0)