[LLVMdev] understanding of getelementptr with a const string

Duncan Sands baldrick at free.fr
Sun Oct 28 10:33:43 PDT 2012


Hi edA-qa mort-ora-y,

On 28/10/12 13:03, edA-qa mort-ora-y wrote:
> I'm working through some very basic IR code and got a bit confused by
> the string printing example. In particular, if you have a constant
> string like:
>
> 	@.str = private unnamed_addr constant [4 x i8] c"%d\0A\00"
>
> To pass this as a pointer to a C-function like printf you need to use 2
> indexes in getelementptr:
>
> 	%sp = getelementptr [4 x i8]* @.str, i32 0, i32 0

you could also bitcast the [4xi8]* @.str to an i8*.

> I think I understand now, but would be gracious if somebody could
> correct/clarify for me:
>
> 1. "@.str" represents a pointer to the data when it is used
> 2. the first 0 index to getelementptr is thus of type [4 x i18], if I
> stopped here the type of %sp would b e [4 x i8]*
> 3. the second 0 index is to the first i8 of that array, by doing this
> the resulting type is now i8* (suitable for printf)

This is correct.

> Are the following two forms, to get the one-past-end pointer, also
> equivalent: they result in the same pointer value and type and are correct:
>
> 	%sp = getelementptr [4 x i8]* @.str, i32 1, i32 0
> 	%sp = getelementptr [4 x i8]* @.str, i32 0, i32 4

Yes, they give the same result since the array has length 4.

Ciao, Duncan.



More information about the llvm-dev mailing list