LLVM IR字符串初始化

时间:2013-05-20 19:25:30

标签: string llvm

我正在研究LLVM IR中的程序,我正在尝试初始化一个写着“Hello World!”的字符串。但我无法弄清楚如何。代码的目标是计算字符串中的字符数。在需要初始化字符串之前,以及在标题之后,我有以下内容:

int main (int argc, const char *argv[]) {
    //Setting up 
    //Build a pointer to the string - LLVMValueRef *strptr=LLVMBuildGlobalStringPtr(builder, const char *string, const char *name);
    LLVMValueRef *strptr;
    LLVMContextRef context = LLVMContextCreate();
    LLVMBuilderRef builder = LLVMCreateBuilderInContext (context);
    LLVMModuleRef module1 = LLVMModuleCreateWithNameInContext("mod", context);
}

1 个答案:

答案 0 :(得分:6)

使用C ++后端查看这些内容的最简单方法 - 它会生成为您构建模块的C ++ API调用。你可以看到这完成online

“编译”此代码:

const char* foo() {
  const char* s = "hello world";
  return s;
}

以下是相关的C ++ API调用:

GlobalVariable* gvar_array__str = new GlobalVariable(/*Module=*/*mod, 
 /*Type=*/ArrayTy_0,
 /*isConstant=*/true,
 /*Linkage=*/GlobalValue::PrivateLinkage,
 /*Initializer=*/0, // has initializer, specified below
 /*Name=*/".str");
 gvar_array__str->setAlignment(1);

 // Constant Definitions
 Constant *const_array_4 = ConstantDataArray::getString(mod->getContext(), "hello world", true);
 std::vector<Constant*> const_ptr_5_indices;
 ConstantInt* const_int64_6 = ConstantInt::get(mod->getContext(), APInt(64, StringRef("0"), 10));
 const_ptr_5_indices.push_back(const_int64_6);
 const_ptr_5_indices.push_back(const_int64_6);
 Constant* const_ptr_5 = ConstantExpr::getGetElementPtr(gvar_array__str, const_ptr_5_indices);

 // Global Variable Definitions
 gvar_array__str->setInitializer(const_array_4);

 // Function Definitions

 // Function: foo (func_foo)
 {

  BasicBlock* label_entry = BasicBlock::Create(mod->getContext(), "entry",func_foo,0);

  // Block entry (label_entry)
  ReturnInst::Create(mod->getContext(), const_ptr_5, label_entry);

 }