-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdriver.c
78 lines (63 loc) · 1.88 KB
/
driver.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
# include <stdlib.h>
# include "./driver.h"
# include "./math.h"
static LLVMBool driver_init(const char* path) {
LLVMBool failure;
LLVMMemoryBufferRef mem;
char* error;
if (mod != NULL)
return 1;
failure = LLVMCreateMemoryBufferWithContentsOfFile(path, &mem, &error);
if (failure) {
fprintf(stderr, "failed to create memory buffer from bitcode file "
"with error: \n%s\n", error);
LLVMDisposeMessage(error);
return failure;
}
failure = LLVMParseBitcode(mem, &mod, &error);
if (failure) {
fprintf(stderr, "failed to parse bitcode with error: \n%s\n", error);
LLVMDisposeMessage(error);
return failure;
}
failure = LLVMCreateExecutionEngineForModule(&engine, mod, &error);
if (failure) {
fprintf(stderr, "failed to create execution engine with error: \n%s\n", error);
LLVMDisposeMessage(error);
LLVMDisposeExecutionEngine(engine);
}
return failure;
}
static void driver_dispose() {
// dispose engine will dispose module too
// LLVMDisposeModule(mod);
LLVMDisposeExecutionEngine(engine);
engine = NULL;
mod = NULL;
}
static int call_func(const char* name, int n) {
LLVMValueRef func;
func = LLVMGetNamedFunction(mod, name);
LLVMGenericValueRef args[] = { LLVMCreateGenericValueOfInt(LLVMInt32Type(), n, 0) };
LLVMGenericValueRef answer = LLVMRunFunction(engine, func, 1, args);
return (int)LLVMGenericValueToInt(answer, 1);
}
static int run_itoi(const char* name, int argc, const char* argv[]) {
int n;
if (argc < 2) {
fprintf(stderr, "usage: %s n\n", argv[0]);
return 1;
}
if (driver_init("math.bc"))
exit(EXIT_FAILURE);
n = atoi(argv[1]);
printf("%s(%d) = %d\n", name, n, call_func(name, n));
driver_dispose();
return 0;
}
int fib(int argc, const char* argv[]) {
return run_itoi(FIBONACCI, argc, argv);
}
int fac(int argc, const char* argv[]) {
return run_itoi(FACTORIAL, argc, argv);
}