Llvm pass: How to insert a variable using the existing variable value

I have identified int a = 5; in the source code, and I will convert the source to LLVM IR:

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

I want to insert int b = a;by writing a pass. I compile int a=5; int b=ain LLVM IR, first load "a" and then save it. I also checked doxygen in which LoadInst LoadInst (Value *Ptr, const Twine &NameStr, Instruction *InsertBefore)However, I do not know how to get Valuefrom "a".

How to get the value of a variable?

+2
source share
1 answer

The LLVM IR sequence

int a = 5;
int b = a;

without any optimization, translates as

%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

This corresponds to two AllocaInsts, two StoreInstand a LoadInstas follows

: /

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 .

+2

Source: https://habr.com/ru/post/1621498/


All Articles