-
-
Notifications
You must be signed in to change notification settings - Fork 77
/
jit.c
90 lines (71 loc) · 2.41 KB
/
jit.c
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
79
80
81
82
83
84
85
86
87
88
89
90
//
// Copyright (C) 2011 Nick Gasson
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
#include "rt.h"
#include "util.h"
#include "lib.h"
#include <assert.h>
#include <limits.h>
#include <llvm-c/Core.h>
#include <llvm-c/BitReader.h>
#include <llvm-c/ExecutionEngine.h>
static LLVMModuleRef module = NULL;
static LLVMExecutionEngineRef exec_engine = NULL;
void *jit_fun_ptr(const char *name)
{
LLVMValueRef fn;
if (LLVMFindFunction(exec_engine, name, &fn))
fatal("cannot find function %s", name);
return LLVMGetPointerToGlobal(exec_engine, fn);
}
void *jit_var_ptr(const char *name)
{
LLVMValueRef var = LLVMGetNamedGlobal(module, name);
if (var == NULL)
fatal("cannot find global %s", name);
return LLVMGetPointerToGlobal(exec_engine, var);
}
void jit_bind_fn(const char *name, void *ptr)
{
LLVMValueRef fn;
if (LLVMFindFunction(exec_engine, name, &fn))
return;
LLVMAddGlobalMapping(exec_engine, fn, ptr);
}
void jit_init(ident_t top)
{
ident_t orig = ident_strip(top, ident_new(".elab"));
ident_t final = ident_prefix(orig, ident_new("final"), '.');
char fname[128];
snprintf(fname, sizeof(fname), "_%s.bc", istr(final));
char path[PATH_MAX];
lib_realpath(lib_work(), fname, path, sizeof(path));
char *error;
LLVMMemoryBufferRef buf;
if (LLVMCreateMemoryBufferWithContentsOfFile(path, &buf, &error))
fatal("error reading bitcode from %s: %s", path, error);
if (LLVMParseBitcode(buf, &module, &error))
fatal("error parsing bitcode: %s", error);
LLVMDisposeMemoryBuffer(buf);
LLVMInitializeNativeTarget();
LLVMLinkInJIT();
if (LLVMCreateExecutionEngineForModule(&exec_engine, module, &error))
fatal("error creating execution engine: %s", error);
}
void jit_shutdown(void)
{
LLVMDisposeExecutionEngine(exec_engine);
}