ftomassetti / kllvm

Kotlin library to work with LLVM

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Unable to Printf floating point integers.

Redrield opened this issue · comments

I got this library working with printing String literals, but I can't seem to get it to print floating point numbers. Delimiting them with %f leads to 0.000000 no matter the contents of the actual constant, and %d just gives me jibberish nothing close to the actual value.

This is the code that I have

val EXIT_CODE_OK = 0
val STRING_TYPE = Pointer(I8Type)

val module = ModuleBuilder()
val mainFunction = module.createMainFunction()

module.addDeclaration(FunctionDeclaration("printf", I32Type, listOf(STRING_TYPE), varargs = true))

val okBlock = mainFunction.entryBlock()

val num = 2.0
val numConst = FloatConst(num, FloatType)

okBlock.addInstruction(Printf(mainFunction.stringConstForContent("%f\n").reference(), numConst))

okBlock.addInstruction(ReturnInt(EXIT_CODE_OK))
println(module.IRCode())

I tried generating something very similar to what you have and I got:

@stringConst0 = private unnamed_addr constant [8 x i8] c"foo %f\0A\00"



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

define i32 @main(i32, i8**) {
    
    ; unnamed block
    call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([8 x i8], [8 x i8]* @stringConst0, i32 0, i32 0), float 2.0)
    ret i32 0

}

which indeed does not work as expected. It works if I replace float with double in the generated IR code.

The reason why is not working even if you use DoubleType is because of a bug in DoubleType that I have now solved and it will be in the next release.

Why printf does not accept a float is unclear to me. I tried to compile a C program to IR and it seems to pass the value as a double, even if in C it was a float.