How to load an address that was allocated in a separate function using IRBuilder - LLVM 6.0

时间:2018-11-16 21:39:41

标签: llvm llvm-ir

Working on a research project that requires to add load instructions to an analyzed LLVM IR code to load in a function func_A addresses that were allocated in a separate function func_B using IRBuilder. An example is shown as follows.

define void @func_B() {
  %1 = alloca [1 x i32], align 4
}

define void @func_A() {
  // load the address allocated above here using IRBuilder in an analysis pass 
  // to the IR code, something like the following:
  // IRBuilder<> builder(); 
  // builder.CreateLoad(val);
}

I've been able to find the to-be-loaded llvm:value*, i.e., val in the above example, but the problem is val is a local identifier declared in func_B and may conflict with func_A's identifiers (say func_A declares a local identifier named %1 too) when loaded in func_A.

How can I load func_B's %1 without conflicts in func_A? Note that I can't pass %1 to func_A as a function parameter since I don't want to change anything of the IR code but adding some load instructions.

Any help would be greatly appreciated!

1 个答案:

答案 0 :(得分:0)

您显然无法做到这一点。在以下示例中,就好像您要从int a访问bar()

int foo()
{
  int a = 5;
}

int bar()
{
  ...
}

由于%1是在堆栈上分配的,因此在函数func_B完成时将释放其内存,因此在func_A执行期间它甚至可能不存在。

您唯一可以做的就是将%1的值存储到func_B中的全局变量中并将其加载到func_A中:

@var = [1 x i32] zeroinitializer

define void @func_B() {
  %1 = alloca [1 x i32], align 4
  store %1, @var
}

define void @func_A() {
  // load the address allocated above here using IRBuilder in an analysis pass 
  // to the IR code, something like the following:
  // IRBuilder<> builder(); 
  // builder.CreateLoad(val);
  %1 = load @var
}