LLVM IR字符串初始化

6

我正在使用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);
}

你无法理解什么?我对此了解不多,但我想第一个 char * 是内容(这里是 Hello World),第二个则类似于变量名。 - JDS
我尝试过了,但是没有成功。我甚至不知道是否应该构建一个指向字符串的指针,或者是否需要将字符串作为全局变量然后存储它。 - FCo
1个回答

10
最简单的了解这些内容的方式是使用C++后端 - 它会生成用于构建模块的C++ API调用。您可以在在线演示中查看此操作。
请“编译”此代码:
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);

 }

4
向看到这条消息的任何人更新 -- 不要再尝试使用C++后端,它已经不存在了 - tonysdg
@tonysdg,你知道展示“如何使用C/C++ API生成IR”的其他方法吗?我觉得这些API的文档不够。我不想使用旧版本的LLVM并猜测新版本的LLVM如何工作。 - worldterminator
@worldterminator 抱歉,我已经一年多没有使用LLVM了。祝你好运! - tonysdg
1
@tonysdg 我相当确定C++后端仍然存在 - 只是你不能再使用LLVM API调用生成C++代码了。 - Jeppe
为了让阅读此文的任何人都清楚,@tonysdg在说C++后端不再存在时,并不是指C++ API和LLVM Core。它们仍然是LLVM项目的主要关注点,并持续接收更新和新功能。他所指的是一个名字容易引起混淆的功能,可以将代码编译成LLVM C++后端API调用。因此,在这个答案中,第二个代码块是由一个已经不存在的工具生成的。它被移除了,因为它没有及时跟上LLVM的C++ API的变化,并经常生成误导性/废弃的/错误的代码。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接