Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM IR String Initialization

Tags:

string

llvm

I'm working on a program in LLVM IR, and I am trying to initialize a string that says "Hello World!" but I can't figure out how. The goal of the code is to count the number of characters in the string. Before the string needs to be initialized, and after the headers, I have the following:

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);
}
like image 504
FCo Avatar asked Mar 24 '23 21:03

FCo


1 Answers

The easiest way to see how such things are by using the C++ backend - it generates the C++ API calls that build the module for you. You can see this done online.

"Compile" this code:

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

And here are the relevant C++ API calls:

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);

 }
like image 158
Eli Bendersky Avatar answered Mar 26 '23 12:03

Eli Bendersky