简体   繁体   English

在llvm ir中增加ptr

[英]incrementing a ptr in llvm ir

I am trying to understand the getelementptr instruction in llvm IR, but not fully understanding it. 我正在尝试了解llvm IR中的getelementptr指令,但没有完全理解它。

I have a struct like below - 我有一个像下面的结构-

struct Foo {
    int32_t* p;
}

I want to do this - 我想做这个 -

foo.p++;

What would be the right code for this? 什么是正确的代码呢?

%0 = getelementptr %Foo* %fooPtr, i32 0, i32 0
%1 = getelementptr i32* %0, i8 1
store i32* %1, i32* %0

I am wondering if value in %0 needs to be first loaded using "load" before executing 2nd line. 我想知道在执行第二行之前是否需要先使用“ load”加载%0中的值。

Thanks! 谢谢!

You can see the GEP instruction as an operation that performs arithmetic operations on pointers. 您可以将GEP指令视为对指针执行算术运算的运算。 In LLVM IR the GEP instruction is your instruction of choice to perform operations on pointers easyly. 在LLVM IR中,GEP指令是您选择的易于对指针执行操作的指令。 You don't have to do cumbersome calculate the size of your types and offsets to manually perform such operations. 您不必繁琐地计算类型和偏移量的大小即可手动执行此类操作。

In your case: 在您的情况下:

%0 = getelementptr %Foo* %fooPtr, i32 0, i32 0

selects the member inside the structure. 选择结构内的成员。 It uses the pointer operatand %fooPtr to calculate %0 = ((fooPtr + 0) + 0) . 它使用指针操作数%fooPtr计算%0 = ((fooPtr + 0) + 0) GEP does not know about fooPtr just pointing to one element of Foo, this is why two indices are used to select the member. GEP不知道fooPtr仅指向Foo的一个元素,这就是为什么使用两个索引来选择成员的原因。

%1 = getelementptr i32* %0, i8 1

As mentioned above the GEP performs pointer arithmetic and in your case get %1 = (p + 1); 如上所述,GEP执行指针算术,在您的情况下为%1 = (p + 1);

Since you are operating on pointers using GEP you don't need to load the value of p. 由于您正在使用GEP处理指针,因此不需要加载p的值。 GEP will do this implicitly for you. GEP将为您隐式执行此操作。

Now you can store the new index back to the position of the p member inside the Foo struct pointed to by fooPtr . 现在,您可以将新索引存储回fooPtr指向的Foo结构内p成员的位置。

For further reading: The Often Misunderstood GEP Instruction 进一步阅读: 经常被误解的GEP指令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM