Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LLVM How to get return value of an instruction

Tags:

c++

llvm

I have a program which allocates memory from stack like this:

%x = alloca i32, align 4

In my pass I want to get the actual memory pointer that points to this allocated memory at runtime. This should be %x. How do I get the pointer in my pass?

Instruction* I;
if (AllocaInst* AI = dyn_cast<AllocaInst>(I)) {
    //How to get %x?
} 
like image 230
Fee Avatar asked Oct 27 '25 07:10

Fee


1 Answers

You can work with an Instruction* as a Value* (and Instruction inherits from Value), then you are working with the result / return value of that instruction. I have adapted some code from my LLVM Pass to demonstrate allocating space using alloca and then storing into that location. Notice that the results of the instructions can be directly passed to other instructions, as they are values.

    // M is the module
    // ci is the current instruction
    LLVMContext &ctx = M.getContext();
    Type* int32Ty = Type::getInt32Ty(ctx);
    Type* int8Ty = Type::getInt8Ty(ctx);
    Type* voidPtrTy = int8Ty->getPointerTo();

    // Get an identifier for rand()
    Constant* = M.getOrInsertFunction("rand", FunctionType::get(cct.int32Ty, false));

    // Construct the struct and allocate space
    Type* strTy[] = {int32Ty, voidPtrTy};
    Type* t = StructType::create(strTy);
    Instruction* nArg = new AllocaInst(t, "Wrapper Struct", ci);

    // Add Store insts here
    Value* gepArgs[2] = {ConstantInt::get(int32Ty, 0), ConstantInt::get(int32Ty, 0)};
    Instruction* prand = GetElementPtrInst::Create(NULL, nArg, ArrayRef<Value*>(gepArgs, 2), "RandPtr", ci);

    // Get a random number 
    Instruction* tRand = CallInst::Create(getRand, "", ci);

    // Store the random number into the struct
    Instruction* stPRand = new StoreInst(tRand, prand, ci);
like image 174
Brian Avatar answered Oct 29 '25 20:10

Brian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!