Using Value to Represent Interger or String Type

How to represent integer such as 1?
How to represent String Hello World?

In Value.h, constructor of Value class is Value(Type *Ty, unsigned scid);. But it seems not work.

// Value *valInt = new Value(Type::getInt32Ty, 1);  // WRONG
Value *valInt = ??? 

// Value *valStr = new Value(Type::getInt8PtrTy, "Hello World");  // WRONG
Value *valStr = ???

Ints are reasonably easy, you want ConstantInt::get(Int32Ty, 1).

Strings are a bit more complicated, what you usually want is a pointer to the string rather than a constant array of characters. But then the actual string has to exist somewhere to have a pointer to it. To get that you normally put an unnamed global into the module and refer to that instead.

The easiest way to do that is probably IRBuilder::CreateGlobalString, which will create the right kind of global and insert it into the module.

1 Like

Thank you! I followed your reply, and the string works:

IRBuilder<> builder(op);
builder.SetInsertPoint(&B, ++builder.GetInsertPoint());
Value *valStr = builder.CreateGlobalString("Hello World");

But I still failed in int:

The ConstantInt::get function is static so you don’t need an instance variable to call it, you can literaly write ConstantInt::get(Type::getInt32Ty(Ctx), 1).

As for the error you’re getting, it’s related to something called the most vexing parse. In the first line you didn’t actually declare and construct a variable with type ConstantInt, you declared a function called cii that took no parameters and returned a ConstantInt. That function decays to a pointer to that function on the second line (hence type ConstantInt (*)()), which can’t be used with . notation for C++ method calls.


It works!
I really learnt a lot from your patient and knowledgeable reply.
THANK YOU :rose: :rose: :rose: