允许 llvm 生成代码来访问全局数组

allow llvm generate code to access a global array

我目前有以下代码:

int counter_array[10] = {0};

void increment_address (int*);
void increment_array ();
int main (){
  increment_array();
}

increment_address (int* ptr){
  (*ptr) ++;
}

我正在尝试使用 llvm 进行检测,以便为 "increment_array()" 函数生成代码,以便该函数应该将 "counter_array" 的第二个元素的地址传递给 "increment_address(int*)" 函数。

换句话说,生成的 increment_array 应该执行如下操作:

void increment_array(){
  int* array_pty = &counter_array[1];
  increment_address(array_ptr);
}

通过查看 IR 代码似乎是用 "getelementptr inbount" 指令完成的。但是,我无法将数组分配给它。

我想知道如何在生成的函数中生成如下 IR 代码?

 store i32* getelementptr inbounds ([10 x i32]* @counterarray, i32 0, i64 1), i32** %ptr, align 8

感谢大家的潜在帮助。

首先了解 GEP 的工作原理:http://llvm.org/docs/GetElementPtr.html

然后,要创建实际指令,请使用以下 API:

例如,要在您的示例中复制 GEP(没有商店):

Value *counterarray = ...

Value *indices[] = {
    ConstantInt::get(Type::getInt32Ty(), 0),
    ConstantInt::get(Type::getInt64Ty(), 1)
};

GetElementPtrInst *Inst = GetElementPtrInst::CreateInBounds(counterarray, indices);

(注意:未经测试的代码)