Frage

I'm new to llvm and I'm writing a small llvm IR Builder. I use the IRBuilder and all these Create* functions to generate my IR. What I'm trying to do is to create a load instruction which create a new SSA local variable with value of a previously allocated llvm::Value.

What I expected to have :

%2 = load i32* %1

With %2 results of load instruction and %1 my previously allocated Value (CreateAlloca)

Here is what I tried :

// Get Ptr from Val
Value* ptr = ConstantExpr::getIntToPtr((Constant*)loc[n],PointerType::getUnqual(builder->getInt32Ty()));

// Générate load instruction with the new Ptr
builder->CreateLoad(ptr);

And here is what I have :

%2 = load i32* null

loc is an array which contains all my llvm::Value*

Can you please tell me what I'm doing wrong ? Or maybe if I'm on a bad way ? Thanks.

War es hilfreich?

Lösung

ConstantExpr::getIntToPtr() creates a constant expression. So in effect, what you're trying to generate is equivalent to this IR:

%2 = load i32* inttoptr (i32 %1 to i32*)

But this is illegal since a constant expression, as hinted by its name, only supports constants, and %1 isn't a constant. ConstantExpr::getIntToPtr() requires a Constant as a first argument to verify it, but you passed it a non-constant value which was forcefully cast to a constant.

The correct way to convert a non-constant integer to a pointer is with IRBuilder::createIntToPtr. However, since you say the previous value (loc[n]) was created via an alloca then it's already a pointer, and you don't need to perform any conversion: just do builder->CreateLoad(loc[n]).

By the way, the proper way to cast a Value to a Constant in LLVM is not via a c-style cast but via cast<>, like so: cast<Constant>(loc[n]).

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top