How can I implement a string data type in LLVM?

后端 未结 5 1845
眼角桃花
眼角桃花 2021-01-31 10:31

I have been looking at LLVM lately, and I find it to be quite an interesting architecture. However, looking through the tutorial and the reference material, I can\'t see any ex

5条回答
  •  南方客
    南方客 (楼主)
    2021-01-31 11:16

    Using the C API, instead of using LLVMConstString, you could use LLVMBuildGlobalString. Here is my implementation of

    int main() {
        printf("Hello World, %s!\n", "there");
        return;
    }
    

    using C API:

    LLVMTypeRef main_type = LLVMFunctionType(LLVMVoidType(), NULL, 0, false);
    LLVMValueRef main = LLVMAddFunction(mod, "main", main_type);
    
    LLVMTypeRef param_types[] = { LLVMPointerType(LLVMInt8Type(), 0) };
    LLVMTypeRef llvm_printf_type = LLVMFunctionType(LLVMInt32Type(), param_types, 0, true);
    LLVMValueRef llvm_printf = LLVMAddFunction(mod, "printf", llvm_printf_type);
    
    LLVMBasicBlockRef entry = LLVMAppendBasicBlock(main, "entry");
    LLVMPositionBuilderAtEnd(builder, entry);
    
    LLVMValueRef format = LLVMBuildGlobalStringPtr(builder, "Hello World, %s!\n", "format");
    LLVMValueRef value = LLVMBuildGlobalStringPtr(builder, "there", "value");
    
    LLVMValueRef args[] = { format, value };
    LLVMBuildCall(builder, llvm_printf, args, 2, "printf");
    
    LLVMBuildRetVoid(builder);
    

    I created strings like so:

    LLVMValueRef format = LLVMBuildGlobalStringPtr(builder, "Hello World, %s!\n", "format");
    LLVMValueRef value = LLVMBuildGlobalStringPtr(builder, "there", "value");
    

    The generated IR is:

    ; ModuleID = 'printf.bc'
    source_filename = "my_module"
    target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
    
    @format = private unnamed_addr constant [18 x i8] c"Hello World, %s!\0A\00"
    @value = private unnamed_addr constant [6 x i8] c"there\00"
    
    define void @main() {
    entry:
      %printf = call i32 (...) @printf(i8* getelementptr inbounds ([18 x i8], [18 x i8]* @format, i32 0, i32 0), i8* getelementptr inbounds ([6 x i8], [6 x i8]* @value, i32 0, i32 0))
      ret void
    }
    
    declare i32 @printf(...)
    

提交回复
热议问题