我正在尝试使用 LLVM 创建一个局部变量来存储字符串,但我的代码当前抛出语法错误。
lli: test2.ll:8:23: error: constant expression type mismatch
%1 = load [6 x i8]* c"hello\00"
我分配和存储字符串的 IR 代码:
@.string = private constant [4 x i8] c"%s\0A\00"
define void @main() {
entry:
%a = alloca [255 x i8]
%0 = bitcast [255 x i8]* %a to i8*
%1 = load [6 x i8]* c"hello\00"
%2 = bitcast [6 x i8]* %1 to i8*
%3 = tail call i8* @strncpy(i8* %0, i8* %2, i64 255) nounwind
%4 = getelementptr inbounds [6 x i8]* %a, i32 0, i32 0
%5 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([4 x i8]* @.string, i32 0, i32 0), i8* %4)
ret void
}
declare i32 @printf(i8*, ...)
declare i8* @strncpy(i8*, i8* nocapture, i64) nounwind
使用 llc 我可以看到 llvm 实现的方式是分配和分配给全局变量,但我希望它是本地的(在基本块内)。下面的代码可以工作,但我不想创建这个 var“@.str”...
@str = global [1024 x i8] zeroinitializer, align 16
@.str = private unnamed_addr constant [6 x i8] c"hello\00", align 1
@.string = private constant [4 x i8] c"%s\0A\00"
define i32 @main() nounwind uwtable {
%1 = tail call i8* @strncpy(i8* getelementptr inbounds ([1024 x i8]* @str, i64 0, i64 0), i8* getelementptr inbounds ([6 x i8]* @.str, i64 0, i64 0), i64 1024) nounwind
%2 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([4 x i8]* @.string, i32 0, i32 0), i8* %1)
ret i32 0
}
declare i8* @strncpy(i8*, i8* nocapture, i64) nounwind
declare i32 @printf(i8*, ...) #2
Thanks