[llvm-commits] RFC: initial union syntax support

Frits van Bommel fvbommel at wxs.nl
Thu May 14 07:17:57 PDT 2009


Duncan Sands wrote:
> you can also do away with unions given bitcasts.  For example,
> here is how you can define a union of two types in a platform
> independent way.  It alloca's enough memory for both types
> without using any platform specific information.
> 
> define void @f() {
>         %tmp1 = getelementptr %T1* null, i32 1          ; <%T1*> [#uses=1]
>         %size1 = ptrtoint %T1* %tmp1 to i32             ; <i32> [#uses=2]
> ; the size of type %T1
>         %tmp2 = getelementptr %T2* null, i32 1          ; <%T2*> [#uses=1]
>         %size2 = ptrtoint %T2* %tmp2 to i32             ; <i32> [#uses=2]
> ; the size of type %T2
>         %gt = icmp ugt i32 %size1, %size2               ; <i1> [#uses=1]
>         br i1 %gt, label %use1, label %use2
> 
> use1:           ; preds = %0
>         br label %allocate
> 
> use2:           ; preds = %0
>         br label %allocate
> 
> allocate:               ; preds = %use2, %use1
>         %size = phi i32 [ %size1, %use1 ], [ %size2, %use2 ]            ; <i32> [#uses=1]
> ; the larger of the two sizes
>         %union = alloca i8, i32 %size           ; <i8*> [#uses=2]
> ; a local variable holding the "union"

This alloca will be aligned to 1 byte, not the maximum alignment of the member 
types.
It's also not in the entry block, so SROA won't look at it. (Okay, that can be 
fixed by using select instead of branch + phi, but will SROA look at 
variable-size allocas?)

>         %as_T1 = bitcast i8* %union to %T1*             ; <%T1*> [#uses=0]
> ; the union viewed as a variable of type %T1
>         %as_T2 = bitcast i8* %union to %T2*             ; <%T2*> [#uses=0]
> ; the union viewed as a variable of type %T2
> ; do stuff with it here
>         ret void
> }



More information about the llvm-commits mailing list