在 LLVM IR 中使用小字符串初始化大型 i8 数组

Initialize large i8 array using a small string in LLVM IR

我想在 LLVM IR 中用一个小字符串初始化一个 i8 的大数组。我想做这样的事情:

@str = [1024 x i8] c"Hello World![=10=]A[=10=]"

请注意,字符串长度仅为 14(如果不计算空字节,则为 13)。我现在不在乎剩余字节中放入了什么。上面的代码由于 constant expression type mismatch 而不起作用,因为初始化数组大小与目标数组大小不匹配。一种解决方案是在字符串后发出正确数量的 [=13=],但我不想这样做,因为它会导致大量无用的垃圾。有没有我可以采取的捷径,或者我必须执行两步过程来为字符串分配 space 然后将字符串常量复制到它?如果我确实需要执行这样的复制,我应该使用什么?

在 LLVM IR 中,全局变量定义 has to be initialized. For array initialization, the array constant 必须匹配数组的大小。因此,我认为没有尾随零就无法一步初始化数组。

但是,您可以使用 zeroinitializer 用零初始化 I8 数组,然后使用 strncpymemcpy 将小字符串复制到它。你可以用 C 编写这样的代码片段,看看 clang 是如何编译它的:

#include <string.h>

extern char str[1024] = "";

int main() {
    char* hello = "Hello World!";
    strncpy(str, hello, sizeof(str));
    return 0;
}

使用 clang -O3 -S -emit-llvm test2.c -o test.ll 时,位码文件应类似于以下内容:

@str = global [1024 x i8] zeroinitializer, align 16
@.str = private unnamed_addr constant [13 x i8] c"Hello World![=11=]", align 1

define i32 @main() nounwind uwtable {
  %1 = tail call i8* @strncpy(i8* getelementptr inbounds ([1024 x i8]* @str, i64 0, i64 0), i8* getelementptr inbounds ([13 x i8]* @.str, i64 0, i64 0), i64 1024) nounwind
  ret i32 0
}

declare i8* @strncpy(i8*, i8* nocapture, i64) nounwind