[llvm-dev] Getting a pointer to a i8 from a global variable that holds a constant string

703 views
Skip to first unread message

Lorin Atzberger via llvm-dev

unread,
Apr 8, 2017, 8:18:20 AM4/8/17
to llvm...@lists.llvm.org
Hello,

I'm trying to get the pointer to the first element of a string (so that I can pass it to a function).
The string itself is a constant kept in a global variable.
My end goal is to generate the IR for something like "puts("Hello World")";
I'm stuck on the parameter part of the call instruction.

So far I have something like this:

const std::string& str = strExpr->value();
llvm::ArrayType* type = llvm::ArrayType::get(llvm::IntegerType::get(m_context, 8), str.size()+1);
llvm::GlobalVariable* var = new llvm::GlobalVariable(m_module, type, true, llvm::GlobalValue::PrivateLinkage, nullptr, ".str");
var->setAlignment(1);;

llvm::Constant* c = llvm::ConstantDataArray::getString(m_context, str);
var->setInitializer(c);

The part below is the one I have problems with:

llvm::ConstantInt* const_int32_12 = llvm::ConstantInt::get(m_context, llvm::APInt(32, llvm::StringRef("0"), 10));
std::vector<llvm::Constant*> const_ptr_14_indices;
const_ptr_14_indices.push_back(const_int32_12);
const_ptr_14_indices.push_back(const_int32_12);
return llvm::ConstantExpr::getGetElementPtr(nullptr,c, const_ptr_14_indices);

I realize that the GlobalVariable should not be declared every time I get in that function but that's something I'll fix after I get this working.

Any help here would be appreciated.

Regards,
Lorin

Tim Northover via llvm-dev

unread,
Apr 8, 2017, 8:32:14 PM4/8/17
to Lorin Atzberger, LLVM Developers Mailing List
Hi Lorin,

On 8 April 2017 at 05:18, Lorin Atzberger via llvm-dev


<llvm...@lists.llvm.org> wrote:
> return llvm::ConstantExpr::getGetElementPtr(nullptr,c,
> const_ptr_14_indices);

You need to be using the GlobalVariable as the base of the GEP, not
the ConstantDataArray. Then since it's been initialized to the string
you want, your GEP will pick up the first element of that string. The
ConstantDataArray isn't a pointer (it's an [N x i8], notionally in
registers).

Cheers.

Tim.
_______________________________________________
LLVM Developers mailing list
llvm...@lists.llvm.org
http://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev

Snehasish Kumar via llvm-dev

unread,
Apr 11, 2017, 3:45:40 PM4/11/17
to LLVM Developers Mailing List, Lorin Atzberger
Hi Lorin

You might want to take a look at the CreateGlobalStringPtr method in the IRBuilder class. It should allow you to insert the string and construct the appropriate GEP automatically.

http://llvm.org/docs/doxygen/html/classllvm_1_1IRBuilder.html#ab81bf85457770dc76f2e536f201db219

Regards,
Snehasish
--
Snehasish Kumar
School of Computing Science
Simon Fraser University

Reply all
Reply to author
Forward
0 new messages