DEADSOFTWARE

95696b4d1d6cfac2e62944eedf0076d54fad9ccb
[d2df-sdl.git] / src / lib / libjit / t1.dpr
1 (*
2 Tutorial 1 - mul_add
4 Builds and compiles the following function:
6 int mul_add(int x, int y, int z)
7 {
8 return x * y + z;
9 }
10 *)
11 {$IFDEF WIN32}
12 {$DEFINE MSWINDOWS}
13 {$ENDIF}
15 {$IFDEF FPC}
16 {$MODE OBJFPC}
17 {$PACKRECORDS C}
18 {$ENDIF}
19 program t1;
21 uses
22 SysUtils, Classes,
23 libjit in 'libjit.pas',
24 libjit_types in 'libjit_types.pas';
27 var
28 context: jit_context_t;
29 params: array [0..2] of jit_type_t;
30 signature: jit_type_t;
31 function_: jit_function_t;
32 x, y, z: jit_value_t;
33 temp1, temp2: jit_value_t;
34 arg1, arg2, arg3: jit_int;
35 args: array [0..2] of Pointer;
36 res: jit_int;
37 begin
38 if (jit_type_int = nil) then raise Exception.Create('fuuuuu (0)');
39 //if (PPointer(jit_type_int)^ = nil) then raise Exception.Create('fuuuuu (1)');
41 (* Create a context to hold the JIT's primary state *)
42 writeln('creating context...');
43 context := jit_context_create();
44 if (context = nil) then raise Exception.Create('cannot create jit context');
46 (* Lock the context while we build and compile the function *)
47 writeln('starting builder...');
48 jit_context_build_start(context);
50 (* Build the function signature *)
51 writeln('creating signature...');
52 params[0] := jit_type_int;
53 params[1] := jit_type_int;
54 params[2] := jit_type_int;
55 signature := jit_type_create_signature(jit_abi_cdecl, jit_type_int, @params[0], 3, 1);
57 (* Create the function object *)
58 writeln('creating function object...');
59 function_ := jit_function_create(context, signature);
60 writeln('freeing signature...');
61 jit_type_free(signature);
63 (* Construct the function body *)
64 writeln('creating function body...');
65 x := jit_value_get_param(function_, 0);
66 y := jit_value_get_param(function_, 1);
67 z := jit_value_get_param(function_, 2);
68 temp1 := jit_insn_mul(function_, x, y);
69 temp2 := jit_insn_add(function_, temp1, z);
70 jit_insn_return(function_, temp2);
72 (* Compile the function *)
73 writeln('compiling function...');
74 jit_function_compile(function_);
76 (* Unlock the context *)
77 writeln('finalizing builder...');
78 jit_context_build_end(context);
80 (* Execute the function and print the result *)
81 writeln('executing function...');
82 arg1 := 3;
83 arg2 := 5;
84 arg3 := 2;
85 args[0] := @arg1;
86 args[1] := @arg2;
87 args[2] := @arg3;
88 jit_function_apply(function_, @args[0], @res);
89 writeln('mul_add(3, 5, 2) = ', Integer(res));
91 (* Clean up *)
92 jit_context_destroy(context);
93 end.