2013-05-20 110 views
2

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

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); 
} 
+0

你有什么想不通的?我对此不太了解,但我会说第一个char *是内容(这里是'Hello World'),第二个是变量名称 – JDS

+0

我试过了,但没有成功。我甚至不知道我是否应该建立一个指向字符串的指针,或者如果我需要将字符串变成全局变量,然后存储它。 – FCo

回答

5

最简单的方式看东西是如何如通过使用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); 

} 
+1

更新给任何人看到这一点 - 不要打扰尝试C++后端,[它不再存在](https://stackoverflow.com/questions/14751403/generate-llvm-c-api-code-as -backend)。 – tonysdg