Skip to content

Commit 4909e7c

Browse files
authored
[clang][Interp] Zero-init remaining string literal elements (#66862)
1 parent 11fbbcb commit 4909e7c

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

clang/lib/AST/Interp/ByteCodeExprGen.cpp

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -881,8 +881,8 @@ bool ByteCodeExprGen<Emitter>::VisitStringLiteral(const StringLiteral *E) {
881881

882882
// If the initializer string is too long, a diagnostic has already been
883883
// emitted. Read only the array length from the string literal.
884-
unsigned N =
885-
std::min(unsigned(CAT->getSize().getZExtValue()), E->getLength());
884+
unsigned ArraySize = CAT->getSize().getZExtValue();
885+
unsigned N = std::min(ArraySize, E->getLength());
886886
size_t CharWidth = E->getCharByteWidth();
887887

888888
for (unsigned I = 0; I != N; ++I) {
@@ -901,6 +901,23 @@ bool ByteCodeExprGen<Emitter>::VisitStringLiteral(const StringLiteral *E) {
901901
llvm_unreachable("unsupported character width");
902902
}
903903
}
904+
905+
// Fill up the rest of the char array with NUL bytes.
906+
for (unsigned I = N; I != ArraySize; ++I) {
907+
if (CharWidth == 1) {
908+
this->emitConstSint8(0, E);
909+
this->emitInitElemSint8(I, E);
910+
} else if (CharWidth == 2) {
911+
this->emitConstUint16(0, E);
912+
this->emitInitElemUint16(I, E);
913+
} else if (CharWidth == 4) {
914+
this->emitConstUint32(0, E);
915+
this->emitInitElemUint32(I, E);
916+
} else {
917+
llvm_unreachable("unsupported character width");
918+
}
919+
}
920+
904921
return true;
905922
}
906923

clang/test/AST/Interp/arrays.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -369,3 +369,24 @@ namespace ArrayInitLoop {
369369
static_assert(g() == 6); // expected-error {{failed}} \
370370
// expected-note {{15 == 6}}
371371
}
372+
373+
namespace StringZeroFill {
374+
struct A {
375+
char c[6];
376+
};
377+
constexpr A a = { "abc" };
378+
static_assert(a.c[0] == 'a', "");
379+
static_assert(a.c[1] == 'b', "");
380+
static_assert(a.c[2] == 'c', "");
381+
static_assert(a.c[3] == '\0', "");
382+
static_assert(a.c[4] == '\0', "");
383+
static_assert(a.c[5] == '\0', "");
384+
385+
constexpr char b[6] = "foo";
386+
static_assert(b[0] == 'f', "");
387+
static_assert(b[1] == 'o', "");
388+
static_assert(b[2] == 'o', "");
389+
static_assert(b[3] == '\0', "");
390+
static_assert(b[4] == '\0', "");
391+
static_assert(b[5] == '\0', "");
392+
}

0 commit comments

Comments
 (0)