llvm pass:如何使用现有变量值插入变量

时间:2014-10-12 13:36:56

标签: llvm llvm-c++-api

我定义了int a = 5;在源代码中,我将源转换为LLVM IR:

%a = alloca i32, align 4
store i32 5, i32* %a, align 4

我想通过写一个传递来插入int b = a;。我将int a=5; int b=a编译成LLVM IR,首先加载“a”,然后存储它。我还检查了doxygen,其中LoadInst是LoadInst (Value *Ptr, const Twine &NameStr, Instruction *InsertBefore)但是,我不知道如何得到“{1}}的”a“。

如何获取变量值?

1 个答案:

答案 0 :(得分:3)

在LLVM IR中序列

int a = 5;
int b = a;

没有任何优化,被翻译为

%a = alloca i32, align 4
%b = alloca i32, align 4
store i32 5, i32* %a, align 4
%0 = load i32* %a, align 4
store i32 %0, i32* %b, align 4

这相当于两个AllocaInst,两个StoreInst和一个LoadInst,如下所示

警告:未经测试/未编译的伪代码

ConstantInt* const_int_5 = ConstantInt::get(llvmContext, APInt(32, StringRef("5"), 10));

AllocaInst* a_alloc = new AllocaInst(IntegerType::get(llvmContext, 32), "a");
AllocaInst* b_alloc = new AllocaInst(IntegerType::get(llvmContext, 32), "b");
StoreInst* store_5 = new StoreInst(const_int_5, a_alloc, false);
LoadInst* load_from_a = new LoadInst(a_alloc, "", false);
StoreInst* store_b = new StoreInst(load_from_a, b_alloc, false);

由于设计良好的继承层次结构,因为指令是LLVM API中的值,您可能会感到困惑。