-
Notifications
You must be signed in to change notification settings - Fork 52
/
jit2.dasc
43 lines (34 loc) · 1.03 KB
/
jit2.dasc
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
// Most basic DynASM JIT; generates a trivial function that
// returns a given value, and executes it.
// DynASM directives.
|.arch x64
|.actionlist actions
// This define affects "|" DynASM lines. "Dst" must
// resolve to a dasm_State** that points to a dasm_State*.
#define Dst &state
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: jit2 <integer>\n");
return 1;
}
int num = atoi(argv[1]);
dasm_State *state;
initjit(&state, actions);
// Generate the code. Each line appends to a buffer in
// "state", but the code in this buffer is not fully linked
// yet because labels can be referenced before they are
// defined.
//
// The run-time value of C variable "num" is substituted
// into the immediate value of the instruction.
| mov eax, num
| ret
// Link the code and write it to executable memory.
int (*fptr)() = jitcode(&state);
// Call the JIT-ted function.
int ret = fptr();
assert(num == ret);
// Free the machine code.
free_jitcode(fptr);
return ret;
}