LLVM 如何获取指令的返回值

use*_*312 3 c++ llvm

我有一个从堆栈中分配内存的程序,如下所示:

%x = alloca i32, align 4
Run Code Online (Sandbox Code Playgroud)

在我的过程中,我想在运行时获得指向这个分配内存的实际内存指针。这应该是 %x。我如何在我的传球中获得指针?

Instruction* I;
if (AllocaInst* AI = dyn_cast<AllocaInst>(I)) {
    //How to get %x?
} 
Run Code Online (Sandbox Code Playgroud)

Bri*_*ian 8

您可以将指令*用作值*(并且指令从值继承),然后您正在使用该指令的结果/返回值。我已经改编了我的 LLVM Pass 中的一些代码来演示使用 alloca 分配空间然后存储到该位置。请注意,指令的结果可以直接传递给其他指令,因为它们是值。

    // 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);
Run Code Online (Sandbox Code Playgroud)