llvm::LoadInst* turn to int value in llvm-16

Background: I’m writing an llvm-16 compiler.

In my array element visit function(for example visit A[a]), I want to get the index of the element like:

    llvm::Value* index = this->expr->codegen(__Context);
    // int ind = llvm::dyn_cast<llvm::ConstantInt>(index)->getSExtValue();

    auto pIntType = basetype; 

    llvm::Value *pZero = llvm::ConstantInt::get(pIntType, 0);
    llvm::Value *aIndices[] = {pZero, llvm::ConstantInt::get(pIntType, ind)};
    llvm::Value *pSecondElementPtr = llvm::GetElementPtrInst::CreateInBounds(arrty, arrptr, aIndices, "", Builder.GetInsertBlock());
    return pSecondElementPtr; 

The commented line is what I want to do, but it doesn’t work. it returns no error but meets with segmentation fault in identifier codegeneration which I will talk about later. index is generated by maybe llvm::ConstantInt value like:

//expr->codegen: (integer)
//this runs well when calling llvm::dyn_cast<llvm::ConstantInt>(index)->getSExtValue();
return llvm::ConstantInt::get(llvm::Type::getInt32Ty(Context), val, true);

but maybe also like:

//expr->codegen: (identifier)
//this runs badly when calling the function
llvm::Value* symbolValuePtr = static_cast<llvm::Value*>(symbol->getContent());// symbol->getContent() is a void type
llvm::Type* symboltype = symbol->getLLVMtype();
llvm::LoadInst* loadInst =  new llvm::LoadInst(symboltype,symbolValuePtr, name, false, __Context.getCurrentBlock());
return loadInst; 

which is generated by a identifier like int a, but llvm::LoadInst* loadInst is cast to llvm::Value* implicitly by codegen due to my compiler design. And exactly this is the place where llvm::dyn_cast<llvm::ConstantInt>(index)->getSExtValue() cannot run.

Summed up, I want to get the value of index generated by some expression like A[a], whose a will return an llvm::Value* casted from llvm::LoadInst*.But I still don’t know how to transform it into an int value. Thanks in advance for any useful advice:)

2 Likes

If I understand what you’re asking how to do, you can’t do that because a variable a is not a constant literal. Given you’re just trying to extract a constant literal only to then turn it back into an llvm::Value * (via llvm::ConstantInt::get), just leave it as an llvm::Value * and put index itself in aIndices?

That is a simple but effective solution. I didn’t know that value can be used directly in indice because I see everyone generating it via an constant integer. Thx and wish u good luck:)