Extract/Insert 值索引处的元素 - LLVM
Extract/Insert element at index from value - LLVM
有没有办法从值而不是 int 的索引处提取或插入元素?我希望能够使用 ExtractElementInst
之类的东西,但用于数组而不是向量。
现在我正在做
mBuilder.CreateExtractValue(refArray, index)
但是,我需要能够将它传递给 Value *
,因为我希望能够访问变量值索引处的数组元素。例如:
array[i]
通过上面的代码,我限制为:
array[0]
要使用任意非常量索引执行地址运算,您需要使用 getelementptr
指令,该指令是使用 CreateGEP
函数创建的。
请注意,getelementptr
需要它的参数是一个指针,因此您需要直接使用保存数组的全局变量或 alloca
,而不是先读取它。这也意味着您需要一个零作为指针后面的第一个索引。所以总而言之,读取 array[i]
的生成代码应该如下所示:
@array = global [3 x i32] [1,2,3]
define void f() {
%i = ; calculuate the index here
%array_i_ptr = getelementptr [3 x i32], [3 x i32]* @array, i32 0, i32 %i
%array_i_value = load i32, i32* array_i_ptr
; do something with %array_i_value
ret
}
这里我假设 array
是一个全局变量。对于局部变量,您将使用 alloca
代替。对于动态分配的数组,您将调用 malloc
,没有数组类型和只有一个索引的 getelementptr
指令(因为我们将使用指向 int 的指针,而不是指针数组到 int,因此零索引不是必需的)。
有没有办法从值而不是 int 的索引处提取或插入元素?我希望能够使用 ExtractElementInst
之类的东西,但用于数组而不是向量。
现在我正在做
mBuilder.CreateExtractValue(refArray, index)
但是,我需要能够将它传递给 Value *
,因为我希望能够访问变量值索引处的数组元素。例如:
array[i]
通过上面的代码,我限制为:
array[0]
要使用任意非常量索引执行地址运算,您需要使用 getelementptr
指令,该指令是使用 CreateGEP
函数创建的。
请注意,getelementptr
需要它的参数是一个指针,因此您需要直接使用保存数组的全局变量或 alloca
,而不是先读取它。这也意味着您需要一个零作为指针后面的第一个索引。所以总而言之,读取 array[i]
的生成代码应该如下所示:
@array = global [3 x i32] [1,2,3]
define void f() {
%i = ; calculuate the index here
%array_i_ptr = getelementptr [3 x i32], [3 x i32]* @array, i32 0, i32 %i
%array_i_value = load i32, i32* array_i_ptr
; do something with %array_i_value
ret
}
这里我假设 array
是一个全局变量。对于局部变量,您将使用 alloca
代替。对于动态分配的数组,您将调用 malloc
,没有数组类型和只有一个索引的 getelementptr
指令(因为我们将使用指向 int 的指针,而不是指针数组到 int,因此零索引不是必需的)。