Create local string using LLVM

不打扰是莪最后的温柔 提交于 2019-12-05 11:04:36

I figured out by myself after messing more with my previous code.

Below is the code, so people who had the same problem as I had can check

@.string = private constant [4 x i8] c"%s\0A\00"

define void @main() {
entry:
  %a = alloca [6 x i8]
  store [6 x i8] [i8 104,i8 101,i8 108,i8 108, i8 111, i8 0], [6 x i8]* %a
  %0 = bitcast [6 x i8]* %a to i8*
  %1 = call i32 (i8*, ...)* @printf(i8* getelementptr inbounds ([4 x i8]* @.string, i32 0, i32 0), i8* %0)
  ret void
}

declare i32 @printf(i8*, ...)

Basically, I had to store each of the characters individually in the array and then bitcast to i8* so I could use the printf function. I couldn't use the c" ... " method which is the one shown in LLVM webpage http://llvm.org/docs/LangRef.html#id669 . It seems it is a special case in the language specification of the IR and they required to be in the global scope.

UPDATE: I was working on the same code again and I found out that the best way was to store a constant instead of each of the i8 symbols. So the line 6, will be replaced by:

  store [6 x i8] c"hello\00", [6 x i8]* %0

It is easier to generate code using llvm and it's more readable!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!