LLVM IR ê 考查

結構 struct

C:

#include <stdio.h>

/* 定義 struct */
struct a_struct{
int a; // i32
double b;
};

int main(void){
struct a_struct a;
return 0;
}

LLVM IR:


; ModuleID = 'a.c'
%struct.a_struct = type { i32, double } ; 生 struct

; Function Attrs: nounwind uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
%a = alloca %struct.a_struct, align 8
store i32 0, i32* %1, align 4
ret i32 0
}

無條仔聯合 untagged union

C:

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

union a_enum{
int i;
double d;
};

int main(void){
union a_enum a;
a.i = 9;
return 0;
}

LLVM IR:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
%union.a_enum = type { double }

; Function Attrs: nounwind uwtable
define i32 @main() #0 {
%1 = alloca i32, align 4
%a = alloca %union.a_enum, align 8 ; 建立 union.a_enum type
store i32 0, i32* %1, align 4
%2 = bitcast %union.a_enum* %a to i32* ; 轉 union.a_enum type 到 i32
store i32 9, i32* %2, align 8 ; 共 9 (i32) 囥入去
ret i32 0
}



函數多重定義 function overloading

C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

double inc(double x){
return x + 1.0;
};

int inc(int x){
return x + 1;
}

int main(void){
int a = inc(7); // inc with integer
double b = inc(3.0); /// inc with float
return 0;
}

LLVM IR:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
; inc double
; Function Attrs: nounwind uwtable
define double @_Z3incd(double %x) #3 {
%1 = alloca double, align 8
store double %x, double* %1, align 8
%2 = load double, double* %1, align 8
%3 = fadd double %2, 1.000000e+00
ret double %3
}

; inc integer
; Function Attrs: nounwind uwtable
define i32 @_Z3inci(i32 %x) #3 {
%1 = alloca i32, align 4
store i32 %x, i32* %1, align 4
%2 = load i32, i32* %1, align 4
%3 = add nsw i32 %2, 1
ret i32 %3
}

; Function Attrs: norecurse nounwind uwtable
define i32 @main() #4 {
%1 = alloca i32, align 4
%a = alloca i32, align 4
%b = alloca double, align 8
store i32 0, i32* %1, align 4
%2 = call i32 @_Z3inci(i32 7) ; call inc integer
store i32 %2, i32* %a, align 4
%3 = call double @_Z3incd(double 3.000000e+00) ; call inc double
store double %3, double* %b, align 8
ret i32 0
}