[PATCH] D137488: [clang][Interp] Array initialization via string literal

Timm Bäder via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Nov 9 00:35:31 PST 2022


tbaeder updated this revision to Diff 474177.
tbaeder marked 4 inline comments as done.

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D137488/new/

https://reviews.llvm.org/D137488

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp


Index: clang/test/AST/Interp/literals.cpp
===================================================================
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -350,6 +350,13 @@
 #endif
 
 #pragma clang diagnostic pop
+
+  constexpr char foo[12] = "abc";
+  static_assert(foo[0] == 'a', "");
+  static_assert(foo[1] == 'b', "");
+  static_assert(foo[2] == 'c', "");
+  static_assert(foo[3] == 0, "");
+  static_assert(foo[11] == 0, "");
 };
 
 #if __cplusplus > 201402L
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===================================================================
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -1072,6 +1072,46 @@
         return false;
     }
     return true;
+  } else if (const auto *SL = dyn_cast<StringLiteral>(Initializer)) {
+    const ConstantArrayType *CAT = Ctx.getASTContext().getAsConstantArrayType(SL->getType());
+    assert(CAT && "a string literal that's not a constant array?");
+    size_t NumElems = CAT->getSize().getZExtValue();
+
+    // FIXME: There is a certain code duplication between here
+    //   and Program::createGlobalString().
+    size_t CharWidth = SL->getCharByteWidth();
+    PrimType CharType;
+    switch (CharWidth) {
+    case 1:
+      CharType = PT_Sint8;
+      break;
+    case 2:
+      CharType = PT_Uint16;
+      break;
+    case 4:
+      CharType = PT_Uint32;
+      break;
+    default:
+      llvm_unreachable("unsupported character width");
+    }
+
+    unsigned N = SL->getLength();
+    for (size_t I = 0; I != NumElems; ++I) {
+      uint32_t CodePoint = I < N ? SL->getCodeUnit(I) : 0;
+      // TODO(Perf): 0 is implicit; we can just stop iterating at that point.
+      if (CharWidth == 1)
+        this->emitConstSint8(CodePoint, SL);
+      else if (CharWidth == 2)
+        this->emitConstUint16(CodePoint, SL);
+      else if (CharWidth == 4)
+        this->emitConstUint32(CodePoint, SL);
+      else
+        return false;
+
+      if (!this->emitInitElem(CharType, I, SL))
+        return false;
+    }
+    return true;
   }
 
   assert(false && "Unknown expression for array initialization");


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D137488.474177.patch
Type: text/x-patch
Size: 2181 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20221109/691ec64f/attachment-0001.bin>


More information about the cfe-commits mailing list