Skip to content

Commit 06f71b5

Browse files
committedAug 4, 2018
[constexpr] Support for constant evaluation of __builtin_memcpy and
__builtin_memmove (in non-type-punning cases). This is intended to permit libc++ to make std::copy etc constexpr without sacrificing the optimization that uses memcpy on trivially-copyable types. __builtin_strcpy and __builtin_wcscpy are not handled by this change. They'd be straightforward to add, but we haven't encountered a need for them just yet. This reinstates r338455, reverted in r338602, with a fix to avoid trying to constant-evaluate a memcpy call if either pointer operand has an invalid designator. llvm-svn: 338941
1 parent e9798f7 commit 06f71b5

File tree

5 files changed

+387
-54
lines changed

5 files changed

+387
-54
lines changed
 

‎clang/include/clang/Basic/Builtins.def

+4
Original file line numberDiff line numberDiff line change
@@ -471,6 +471,8 @@ BUILTIN(__builtin_wcslen, "zwC*", "nF")
471471
BUILTIN(__builtin_wcsncmp, "iwC*wC*z", "nF")
472472
BUILTIN(__builtin_wmemchr, "w*wC*wz", "nF")
473473
BUILTIN(__builtin_wmemcmp, "iwC*wC*z", "nF")
474+
BUILTIN(__builtin_wmemcpy, "w*w*wC*z", "nF")
475+
BUILTIN(__builtin_wmemmove, "w*w*wC*z", "nF")
474476
BUILTIN(__builtin_return_address, "v*IUi", "n")
475477
BUILTIN(__builtin_extract_return_addr, "v*v*", "n")
476478
BUILTIN(__builtin_frame_address, "v*IUi", "n")
@@ -908,6 +910,8 @@ LIBBUILTIN(wcslen, "zwC*", "f", "wchar.h", ALL_LANGUAGES)
908910
LIBBUILTIN(wcsncmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
909911
LIBBUILTIN(wmemchr, "w*wC*wz", "f", "wchar.h", ALL_LANGUAGES)
910912
LIBBUILTIN(wmemcmp, "iwC*wC*z", "f", "wchar.h", ALL_LANGUAGES)
913+
LIBBUILTIN(wmemcpy, "w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
914+
LIBBUILTIN(wmemmove,"w*w*wC*z", "f", "wchar.h", ALL_LANGUAGES)
911915

912916
// C99
913917
// In some systems setjmp is a macro that expands to _setjmp. We undefine

‎clang/include/clang/Basic/DiagnosticASTKinds.td

+14
Original file line numberDiff line numberDiff line change
@@ -163,6 +163,20 @@ def note_constexpr_unsupported_unsized_array : Note<
163163
def note_constexpr_unsized_array_indexed : Note<
164164
"indexing of array without known bound is not allowed "
165165
"in a constant expression">;
166+
def note_constexpr_memcpy_type_pun : Note<
167+
"cannot constant evaluate '%select{memcpy|memmove}0' from object of "
168+
"type %1 to object of type %2">;
169+
def note_constexpr_memcpy_nontrivial : Note<
170+
"cannot constant evaluate '%select{memcpy|memmove}0' between objects of "
171+
"non-trivially-copyable type %1">;
172+
def note_constexpr_memcpy_overlap : Note<
173+
"'%select{memcpy|wmemcpy}0' between overlapping memory regions">;
174+
def note_constexpr_memcpy_unsupported : Note<
175+
"'%select{%select{memcpy|wmemcpy}1|%select{memmove|wmemmove}1}0' "
176+
"not supported: %select{"
177+
"size to copy (%4) is not a multiple of size of element type %3 (%5)|"
178+
"source is not a contiguous array of at least %4 elements of type %3|"
179+
"destination is not a contiguous array of at least %4 elements of type %3}2">;
166180

167181
def warn_integer_constant_overflow : Warning<
168182
"overflow in expression; result is %0 with type %1">,

‎clang/lib/AST/ExprConstant.cpp

+199-48
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,25 @@ namespace {
319319
return false;
320320
}
321321

322+
/// Get the range of valid index adjustments in the form
323+
/// {maximum value that can be subtracted from this pointer,
324+
/// maximum value that can be added to this pointer}
325+
std::pair<uint64_t, uint64_t> validIndexAdjustments() {
326+
if (Invalid || isMostDerivedAnUnsizedArray())
327+
return {0, 0};
328+
329+
// [expr.add]p4: For the purposes of these operators, a pointer to a
330+
// nonarray object behaves the same as a pointer to the first element of
331+
// an array of length one with the type of the object as its element type.
332+
bool IsArray = MostDerivedPathLength == Entries.size() &&
333+
MostDerivedIsArrayElement;
334+
uint64_t ArrayIndex =
335+
IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
336+
uint64_t ArraySize =
337+
IsArray ? getMostDerivedArraySize() : (uint64_t)1;
338+
return {ArrayIndex, ArraySize - ArrayIndex};
339+
}
340+
322341
/// Check that this refers to a valid subobject.
323342
bool isValidSubobject() const {
324343
if (Invalid)
@@ -329,6 +348,14 @@ namespace {
329348
/// relevant diagnostic and set the designator as invalid.
330349
bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
331350

351+
/// Get the type of the designated object.
352+
QualType getType(ASTContext &Ctx) const {
353+
assert(!Invalid && "invalid designator has no subobject type");
354+
return MostDerivedPathLength == Entries.size()
355+
? MostDerivedType
356+
: Ctx.getRecordType(getAsBaseClass(Entries.back()));
357+
}
358+
332359
/// Update this designator to refer to the first element within this array.
333360
void addArrayUnchecked(const ConstantArrayType *CAT) {
334361
PathEntry Entry;
@@ -1706,6 +1733,54 @@ static bool IsGlobalLValue(APValue::LValueBase B) {
17061733
}
17071734
}
17081735

1736+
static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1737+
return LVal.Base.dyn_cast<const ValueDecl*>();
1738+
}
1739+
1740+
static bool IsLiteralLValue(const LValue &Value) {
1741+
if (Value.getLValueCallIndex())
1742+
return false;
1743+
const Expr *E = Value.Base.dyn_cast<const Expr*>();
1744+
return E && !isa<MaterializeTemporaryExpr>(E);
1745+
}
1746+
1747+
static bool IsWeakLValue(const LValue &Value) {
1748+
const ValueDecl *Decl = GetLValueBaseDecl(Value);
1749+
return Decl && Decl->isWeak();
1750+
}
1751+
1752+
static bool isZeroSized(const LValue &Value) {
1753+
const ValueDecl *Decl = GetLValueBaseDecl(Value);
1754+
if (Decl && isa<VarDecl>(Decl)) {
1755+
QualType Ty = Decl->getType();
1756+
if (Ty->isArrayType())
1757+
return Ty->isIncompleteType() ||
1758+
Decl->getASTContext().getTypeSize(Ty) == 0;
1759+
}
1760+
return false;
1761+
}
1762+
1763+
static bool HasSameBase(const LValue &A, const LValue &B) {
1764+
if (!A.getLValueBase())
1765+
return !B.getLValueBase();
1766+
if (!B.getLValueBase())
1767+
return false;
1768+
1769+
if (A.getLValueBase().getOpaqueValue() !=
1770+
B.getLValueBase().getOpaqueValue()) {
1771+
const Decl *ADecl = GetLValueBaseDecl(A);
1772+
if (!ADecl)
1773+
return false;
1774+
const Decl *BDecl = GetLValueBaseDecl(B);
1775+
if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1776+
return false;
1777+
}
1778+
1779+
return IsGlobalLValue(A.getLValueBase()) ||
1780+
(A.getLValueCallIndex() == B.getLValueCallIndex() &&
1781+
A.getLValueVersion() == B.getLValueVersion());
1782+
}
1783+
17091784
static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
17101785
assert(Base && "no location for a null lvalue");
17111786
const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
@@ -1917,33 +1992,6 @@ CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
19171992
return true;
19181993
}
19191994

1920-
static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1921-
return LVal.Base.dyn_cast<const ValueDecl*>();
1922-
}
1923-
1924-
static bool IsLiteralLValue(const LValue &Value) {
1925-
if (Value.getLValueCallIndex())
1926-
return false;
1927-
const Expr *E = Value.Base.dyn_cast<const Expr*>();
1928-
return E && !isa<MaterializeTemporaryExpr>(E);
1929-
}
1930-
1931-
static bool IsWeakLValue(const LValue &Value) {
1932-
const ValueDecl *Decl = GetLValueBaseDecl(Value);
1933-
return Decl && Decl->isWeak();
1934-
}
1935-
1936-
static bool isZeroSized(const LValue &Value) {
1937-
const ValueDecl *Decl = GetLValueBaseDecl(Value);
1938-
if (Decl && isa<VarDecl>(Decl)) {
1939-
QualType Ty = Decl->getType();
1940-
if (Ty->isArrayType())
1941-
return Ty->isIncompleteType() ||
1942-
Decl->getASTContext().getTypeSize(Ty) == 0;
1943-
}
1944-
return false;
1945-
}
1946-
19471995
static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
19481996
// A null base expression indicates a null pointer. These are always
19491997
// evaluatable, and they are false unless the offset is zero.
@@ -6117,6 +6165,130 @@ bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
61176165
return ZeroInitialization(E);
61186166
}
61196167

6168+
case Builtin::BImemcpy:
6169+
case Builtin::BImemmove:
6170+
case Builtin::BIwmemcpy:
6171+
case Builtin::BIwmemmove:
6172+
if (Info.getLangOpts().CPlusPlus11)
6173+
Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6174+
<< /*isConstexpr*/0 << /*isConstructor*/0
6175+
<< (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6176+
else
6177+
Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6178+
LLVM_FALLTHROUGH;
6179+
case Builtin::BI__builtin_memcpy:
6180+
case Builtin::BI__builtin_memmove:
6181+
case Builtin::BI__builtin_wmemcpy:
6182+
case Builtin::BI__builtin_wmemmove: {
6183+
bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6184+
BuiltinOp == Builtin::BIwmemmove ||
6185+
BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6186+
BuiltinOp == Builtin::BI__builtin_wmemmove;
6187+
bool Move = BuiltinOp == Builtin::BImemmove ||
6188+
BuiltinOp == Builtin::BIwmemmove ||
6189+
BuiltinOp == Builtin::BI__builtin_memmove ||
6190+
BuiltinOp == Builtin::BI__builtin_wmemmove;
6191+
6192+
// The result of mem* is the first argument.
6193+
if (!Visit(E->getArg(0)) || Result.Designator.Invalid)
6194+
return false;
6195+
LValue Dest = Result;
6196+
6197+
LValue Src;
6198+
if (!EvaluatePointer(E->getArg(1), Src, Info) || Src.Designator.Invalid)
6199+
return false;
6200+
6201+
APSInt N;
6202+
if (!EvaluateInteger(E->getArg(2), N, Info))
6203+
return false;
6204+
assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6205+
6206+
// If the size is zero, we treat this as always being a valid no-op.
6207+
// (Even if one of the src and dest pointers is null.)
6208+
if (!N)
6209+
return true;
6210+
6211+
// We require that Src and Dest are both pointers to arrays of
6212+
// trivially-copyable type. (For the wide version, the designator will be
6213+
// invalid if the designated object is not a wchar_t.)
6214+
QualType T = Dest.Designator.getType(Info.Ctx);
6215+
QualType SrcT = Src.Designator.getType(Info.Ctx);
6216+
if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6217+
Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6218+
return false;
6219+
}
6220+
if (!T.isTriviallyCopyableType(Info.Ctx)) {
6221+
Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6222+
return false;
6223+
}
6224+
6225+
// Figure out how many T's we're copying.
6226+
uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6227+
if (!WChar) {
6228+
uint64_t Remainder;
6229+
llvm::APInt OrigN = N;
6230+
llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6231+
if (Remainder) {
6232+
Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6233+
<< Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6234+
<< (unsigned)TSize;
6235+
return false;
6236+
}
6237+
}
6238+
6239+
// Check that the copying will remain within the arrays, just so that we
6240+
// can give a more meaningful diagnostic. This implicitly also checks that
6241+
// N fits into 64 bits.
6242+
uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6243+
uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6244+
if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6245+
Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6246+
<< Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6247+
<< N.toString(10, /*Signed*/false);
6248+
return false;
6249+
}
6250+
uint64_t NElems = N.getZExtValue();
6251+
uint64_t NBytes = NElems * TSize;
6252+
6253+
// Check for overlap.
6254+
int Direction = 1;
6255+
if (HasSameBase(Src, Dest)) {
6256+
uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6257+
uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6258+
if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6259+
// Dest is inside the source region.
6260+
if (!Move) {
6261+
Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6262+
return false;
6263+
}
6264+
// For memmove and friends, copy backwards.
6265+
if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6266+
!HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6267+
return false;
6268+
Direction = -1;
6269+
} else if (!Move && SrcOffset >= DestOffset &&
6270+
SrcOffset - DestOffset < NBytes) {
6271+
// Src is inside the destination region for memcpy: invalid.
6272+
Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6273+
return false;
6274+
}
6275+
}
6276+
6277+
while (true) {
6278+
APValue Val;
6279+
if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6280+
!handleAssignment(Info, E, Dest, T, Val))
6281+
return false;
6282+
// Do not iterate past the last element; if we're copying backwards, that
6283+
// might take us off the start of the array.
6284+
if (--NElems == 0)
6285+
return true;
6286+
if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6287+
!HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6288+
return false;
6289+
}
6290+
}
6291+
61206292
default:
61216293
return visitNonBuiltinCallExpr(E);
61226294
}
@@ -8357,27 +8529,6 @@ bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
83578529
}
83588530
}
83598531

8360-
static bool HasSameBase(const LValue &A, const LValue &B) {
8361-
if (!A.getLValueBase())
8362-
return !B.getLValueBase();
8363-
if (!B.getLValueBase())
8364-
return false;
8365-
8366-
if (A.getLValueBase().getOpaqueValue() !=
8367-
B.getLValueBase().getOpaqueValue()) {
8368-
const Decl *ADecl = GetLValueBaseDecl(A);
8369-
if (!ADecl)
8370-
return false;
8371-
const Decl *BDecl = GetLValueBaseDecl(B);
8372-
if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
8373-
return false;
8374-
}
8375-
8376-
return IsGlobalLValue(A.getLValueBase()) ||
8377-
(A.getLValueCallIndex() == B.getLValueCallIndex() &&
8378-
A.getLValueVersion() == B.getLValueVersion());
8379-
}
8380-
83818532
/// Determine whether this is a pointer past the end of the complete
83828533
/// object referred to by the lvalue.
83838534
static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,

‎clang/test/CodeGen/builtin-memfns.c

+28
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
// RUN: %clang_cc1 -triple i386-pc-linux-gnu -emit-llvm < %s| FileCheck %s
22

3+
typedef __WCHAR_TYPE__ wchar_t;
4+
typedef __SIZE_TYPE__ size_t;
5+
6+
void *memcpy(void *, void const *, size_t);
7+
38
// CHECK: @test1
49
// CHECK: call void @llvm.memset.p0i8.i32
510
// CHECK: call void @llvm.memset.p0i8.i32
@@ -83,3 +88,26 @@ void test9() {
8388
// CHECK: call void @llvm.memcpy{{.*}} align 16 {{.*}} align 16 {{.*}} 16, i1 false)
8489
__builtin_memcpy(x, y, sizeof(y));
8590
}
91+
92+
wchar_t dest;
93+
wchar_t src;
94+
95+
// CHECK-LABEL: @test10
96+
// FIXME: Consider lowering these to llvm.memcpy / llvm.memmove.
97+
void test10() {
98+
// CHECK: call i32* @wmemcpy(i32* @dest, i32* @src, i32 4)
99+
__builtin_wmemcpy(&dest, &src, 4);
100+
101+
// CHECK: call i32* @wmemmove(i32* @dest, i32* @src, i32 4)
102+
__builtin_wmemmove(&dest, &src, 4);
103+
}
104+
105+
// CHECK-LABEL: @test11
106+
void test11() {
107+
typedef struct { int a; } b;
108+
int d;
109+
b e;
110+
// CHECK: call void @llvm.memcpy{{.*}}(
111+
memcpy(&d, (char *)&e.a, sizeof(e));
112+
}
113+

‎clang/test/SemaCXX/constexpr-string.cpp

+142-6
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic
2-
// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -fno-signed-char
3-
// RUN: %clang_cc1 %s -std=c++1z -fsyntax-only -verify -pedantic -fno-wchar -Dwchar_t=__WCHAR_TYPE__
1+
// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic
2+
// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic -fno-signed-char
3+
// RUN: %clang_cc1 %s -triple x86_64-linux-gnu -std=c++1z -fsyntax-only -verify -pedantic -fno-wchar -Dwchar_t=__WCHAR_TYPE__
44

55
# 6 "/usr/include/string.h" 1 3 4
66
extern "C" {
@@ -14,10 +14,13 @@ extern "C" {
1414

1515
extern char *strchr(const char *s, int c);
1616
extern void *memchr(const void *s, int c, size_t n);
17+
18+
extern void *memcpy(void *d, const void *s, size_t n);
19+
extern void *memmove(void *d, const void *s, size_t n);
1720
}
18-
# 19 "SemaCXX/constexpr-string.cpp" 2
21+
# 22 "SemaCXX/constexpr-string.cpp" 2
1922

20-
# 21 "/usr/include/wchar.h" 1 3 4
23+
# 24 "/usr/include/wchar.h" 1 3 4
2124
extern "C" {
2225
extern size_t wcslen(const wchar_t *p);
2326

@@ -27,9 +30,12 @@ extern "C" {
2730

2831
extern wchar_t *wcschr(const wchar_t *s, wchar_t c);
2932
extern wchar_t *wmemchr(const wchar_t *s, wchar_t c, size_t n);
33+
34+
extern wchar_t *wmemcpy(wchar_t *d, const wchar_t *s, size_t n);
35+
extern wchar_t *wmemmove(wchar_t *d, const wchar_t *s, size_t n);
3036
}
3137

32-
# 33 "SemaCXX/constexpr-string.cpp" 2
38+
# 39 "SemaCXX/constexpr-string.cpp" 2
3339
namespace Strlen {
3440
constexpr int n = __builtin_strlen("hello"); // ok
3541
static_assert(n == 5);
@@ -235,3 +241,133 @@ namespace WcschrEtc {
235241
constexpr bool a = !wcschr(L"hello", L'h'); // expected-error {{constant expression}} expected-note {{non-constexpr function 'wcschr' cannot be used in a constant expression}}
236242
constexpr bool b = !wmemchr(L"hello", L'h', 3); // expected-error {{constant expression}} expected-note {{non-constexpr function 'wmemchr' cannot be used in a constant expression}}
237243
}
244+
245+
namespace MemcpyEtc {
246+
template<typename T>
247+
constexpr T result(T (&arr)[4]) {
248+
return arr[0] * 1000 + arr[1] * 100 + arr[2] * 10 + arr[3];
249+
}
250+
251+
constexpr int test_memcpy(int a, int b, int n) {
252+
int arr[4] = {1, 2, 3, 4};
253+
__builtin_memcpy(arr + a, arr + b, n);
254+
// expected-note@-1 2{{overlapping memory regions}}
255+
// expected-note@-2 {{size to copy (1) is not a multiple of size of element type 'int'}}
256+
// expected-note@-3 {{source is not a contiguous array of at least 2 elements of type 'int'}}
257+
// expected-note@-4 {{destination is not a contiguous array of at least 3 elements of type 'int'}}
258+
return result(arr);
259+
}
260+
constexpr int test_memmove(int a, int b, int n) {
261+
int arr[4] = {1, 2, 3, 4};
262+
__builtin_memmove(arr + a, arr + b, n);
263+
// expected-note@-1 {{size to copy (1) is not a multiple of size of element type 'int'}}
264+
// expected-note@-2 {{source is not a contiguous array of at least 2 elements of type 'int'}}
265+
// expected-note@-3 {{destination is not a contiguous array of at least 3 elements of type 'int'}}
266+
return result(arr);
267+
}
268+
constexpr int test_wmemcpy(int a, int b, int n) {
269+
wchar_t arr[4] = {1, 2, 3, 4};
270+
__builtin_wmemcpy(arr + a, arr + b, n);
271+
// expected-note@-1 2{{overlapping memory regions}}
272+
// expected-note-re@-2 {{source is not a contiguous array of at least 2 elements of type '{{wchar_t|int}}'}}
273+
// expected-note-re@-3 {{destination is not a contiguous array of at least 3 elements of type '{{wchar_t|int}}'}}
274+
return result(arr);
275+
}
276+
constexpr int test_wmemmove(int a, int b, int n) {
277+
wchar_t arr[4] = {1, 2, 3, 4};
278+
__builtin_wmemmove(arr + a, arr + b, n);
279+
// expected-note-re@-1 {{source is not a contiguous array of at least 2 elements of type '{{wchar_t|int}}'}}
280+
// expected-note-re@-2 {{destination is not a contiguous array of at least 3 elements of type '{{wchar_t|int}}'}}
281+
return result(arr);
282+
}
283+
284+
static_assert(test_memcpy(1, 2, 4) == 1334);
285+
static_assert(test_memcpy(2, 1, 4) == 1224);
286+
static_assert(test_memcpy(0, 1, 8) == 2334); // expected-error {{constant}} expected-note {{in call}}
287+
static_assert(test_memcpy(1, 0, 8) == 1124); // expected-error {{constant}} expected-note {{in call}}
288+
static_assert(test_memcpy(1, 2, 1) == 1334); // expected-error {{constant}} expected-note {{in call}}
289+
static_assert(test_memcpy(0, 3, 4) == 4234);
290+
static_assert(test_memcpy(0, 3, 8) == 4234); // expected-error {{constant}} expected-note {{in call}}
291+
static_assert(test_memcpy(2, 0, 12) == 4234); // expected-error {{constant}} expected-note {{in call}}
292+
293+
static_assert(test_memmove(1, 2, 4) == 1334);
294+
static_assert(test_memmove(2, 1, 4) == 1224);
295+
static_assert(test_memmove(0, 1, 8) == 2334);
296+
static_assert(test_memmove(1, 0, 8) == 1124);
297+
static_assert(test_memmove(1, 2, 1) == 1334); // expected-error {{constant}} expected-note {{in call}}
298+
static_assert(test_memmove(0, 3, 4) == 4234);
299+
static_assert(test_memmove(0, 3, 8) == 4234); // expected-error {{constant}} expected-note {{in call}}
300+
static_assert(test_memmove(2, 0, 12) == 4234); // expected-error {{constant}} expected-note {{in call}}
301+
302+
static_assert(test_wmemcpy(1, 2, 1) == 1334);
303+
static_assert(test_wmemcpy(2, 1, 1) == 1224);
304+
static_assert(test_wmemcpy(0, 1, 2) == 2334); // expected-error {{constant}} expected-note {{in call}}
305+
static_assert(test_wmemcpy(1, 0, 2) == 1124); // expected-error {{constant}} expected-note {{in call}}
306+
static_assert(test_wmemcpy(1, 2, 1) == 1334);
307+
static_assert(test_wmemcpy(0, 3, 1) == 4234);
308+
static_assert(test_wmemcpy(0, 3, 2) == 4234); // expected-error {{constant}} expected-note {{in call}}
309+
static_assert(test_wmemcpy(2, 0, 3) == 4234); // expected-error {{constant}} expected-note {{in call}}
310+
311+
static_assert(test_wmemmove(1, 2, 1) == 1334);
312+
static_assert(test_wmemmove(2, 1, 1) == 1224);
313+
static_assert(test_wmemmove(0, 1, 2) == 2334);
314+
static_assert(test_wmemmove(1, 0, 2) == 1124);
315+
static_assert(test_wmemmove(1, 2, 1) == 1334);
316+
static_assert(test_wmemmove(0, 3, 1) == 4234);
317+
static_assert(test_wmemmove(0, 3, 2) == 4234); // expected-error {{constant}} expected-note {{in call}}
318+
static_assert(test_wmemmove(2, 0, 3) == 4234); // expected-error {{constant}} expected-note {{in call}}
319+
320+
// Copying is permitted for any trivially-copyable type.
321+
struct Trivial { char k; short s; constexpr bool ok() { return k == 3 && s == 4; } };
322+
constexpr bool test_trivial() {
323+
Trivial arr[3] = {{1, 2}, {3, 4}, {5, 6}};
324+
__builtin_memcpy(arr, arr+1, sizeof(Trivial));
325+
__builtin_memmove(arr+1, arr, 2 * sizeof(Trivial));
326+
return arr[0].ok() && arr[1].ok() && arr[2].ok();
327+
}
328+
static_assert(test_trivial());
329+
330+
// But not for a non-trivially-copyable type.
331+
struct NonTrivial {
332+
constexpr NonTrivial() : n(0) {}
333+
constexpr NonTrivial(const NonTrivial &) : n(1) {}
334+
int n;
335+
};
336+
constexpr bool test_nontrivial_memcpy() { // expected-error {{never produces a constant}}
337+
NonTrivial arr[3] = {};
338+
__builtin_memcpy(arr, arr + 1, sizeof(NonTrivial)); // expected-note 2{{non-trivially-copyable}}
339+
return true;
340+
}
341+
static_assert(test_nontrivial_memcpy()); // expected-error {{constant}} expected-note {{in call}}
342+
constexpr bool test_nontrivial_memmove() { // expected-error {{never produces a constant}}
343+
NonTrivial arr[3] = {};
344+
__builtin_memcpy(arr, arr + 1, sizeof(NonTrivial)); // expected-note 2{{non-trivially-copyable}}
345+
return true;
346+
}
347+
static_assert(test_nontrivial_memmove()); // expected-error {{constant}} expected-note {{in call}}
348+
349+
// Type puns via constant evaluated memcpy are not supported yet.
350+
constexpr float type_pun(const unsigned &n) {
351+
float f = 0.0f;
352+
__builtin_memcpy(&f, &n, 4); // expected-note {{cannot constant evaluate 'memcpy' from object of type 'const unsigned int' to object of type 'float'}}
353+
return f;
354+
}
355+
static_assert(type_pun(0x3f800000) == 1.0f); // expected-error {{constant}} expected-note {{in call}}
356+
357+
// Make sure we're not confused by derived-to-base conversions.
358+
struct Base { int a; };
359+
struct Derived : Base { int b; };
360+
constexpr int test_derived_to_base(int n) {
361+
Derived arr[2] = {1, 2, 3, 4};
362+
Base *p = &arr[0];
363+
Base *q = &arr[1];
364+
__builtin_memcpy(p, q, sizeof(Base) * n); // expected-note {{source is not a contiguous array of at least 2 elements of type 'MemcpyEtc::Base'}}
365+
return arr[0].a * 1000 + arr[0].b * 100 + arr[1].a * 10 + arr[1].b;
366+
}
367+
static_assert(test_derived_to_base(0) == 1234);
368+
static_assert(test_derived_to_base(1) == 3234);
369+
// FIXME: We could consider making this work by stripping elements off both
370+
// designators until we have a long enough matching size, if both designators
371+
// point to the start of their respective final elements.
372+
static_assert(test_derived_to_base(2) == 3434); // expected-error {{constant}} expected-note {{in call}}
373+
}

0 commit comments

Comments
 (0)
Please sign in to comment.