aboutsummaryrefslogtreecommitdiff
path: root/examples/sum.c
blob: cc8f54b1f98addc3957ce5f14b8964108fb67273 (plain) (blame)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
#include <time.h>

#include "../include/ejit/ejit.h"

struct ejit_func *compile(bool try_jit, bool im_scawed)
{
	struct ejit_operand params[2] = {
		EJIT_OPERAND_GPR(0, EJIT_INT32), /* loc 0 contains s */
		EJIT_OPERAND_GPR(1, EJIT_INT32)  /* loc 1 contains n */
	};
	struct ejit_func *f = ejit_create_func(EJIT_INT32, 2, params);

	/* n == 0, return s */
	struct ejit_reloc recurse = ejit_bnei(f, EJIT_GPR(1), 0);
	ejit_retr(f, EJIT_GPR(0));
	ejit_patch(f, recurse, ejit_label(f));

	/* s += n */
	ejit_addr(f, EJIT_GPR(0), EJIT_GPR(0), EJIT_GPR(1));

	/* n -= 1 */
	ejit_subi(f, EJIT_GPR(1), EJIT_GPR(1), 1);

	struct ejit_operand args[2] = {
		EJIT_OPERAND_GPR(0, EJIT_INT32), /* s */
		EJIT_OPERAND_GPR(1, EJIT_INT32) /* n */
	};

	/* recurse */
	ejit_movi(f, EJIT_GPR(2), (uintptr_t)f);
	ejit_tailr(f, EJIT_GPR(2), 2, args);

	ejit_select_compile_func(f, 3, 0, EJIT_USE64(uintptr_t), try_jit, im_scawed);
	return f;
}

int main(int argc, char *argv[])
{
	if(argc != 4){
		fprintf(stderr, "Usage: %s compile_num loop_num jit\n", argv[0]);
		return -1;
	}

	int jit_level = strtoull(argv[3], 0, 0);
	size_t compile_num = strtoull(argv[1], 0, 0);
	struct ejit_func **info = calloc(compile_num, sizeof(struct ejit_func *));

	clock_t t = clock();
	for(size_t i = 0; i < compile_num; ++i){
		info[i] = compile(jit_level > 0, jit_level > 1);
	}
	t = clock() - t;

	double compile_time_total = ((double)t) / CLOCKS_PER_SEC;
	double compile_time_one = compile_time_total / compile_num;
	printf("Compilation for n = %zu took %fs (1/%f).\n",
			compile_num, compile_time_total, compile_time_one);

	size_t run_num = strtoull(argv[2], 0, 0);
	t = clock();
	struct ejit_arg args[2] = {
		(struct ejit_arg){.type = EJIT_INT32, .l = 0}, /* s */
		(struct ejit_arg){.type = EJIT_INT32, .l = run_num} /* n */
	};
	int32_t result = ejit_run_func_i(info[0], 2, args);
	t = clock() - t;

	double run_time_total = ((double)t) / CLOCKS_PER_SEC;
	printf("Running loop for n = %zu took %fs with res %ld\n",
			run_num, run_time_total, (long)result);

	for(size_t i = 0; i < compile_num; ++i)
		ejit_destroy_func(info[i]);

	free(info);
	return 0;
}