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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
use super::LLVMRef;
use super::context::Context;
use libc::c_char;
use llvm::analysis::{
LLVMVerifierFailureAction,
LLVMVerifyModule
};
use llvm::core::{
LLVMDisposeMessage,
LLVMDisposeModule,
LLVMModuleCreateWithNameInContext,
LLVMPrintModuleToString
};
use llvm::prelude::LLVMModuleRef;
use std::ffi::{CStr, CString};
use std::fmt;
pub struct Module {
module: LLVMModuleRef,
owned : bool
}
impl Module {
pub fn new(module_id: &str, context: &Context) -> Module {
let module_id = CString::new(module_id).unwrap();
Module {
module: unsafe {
LLVMModuleCreateWithNameInContext(
module_id.as_ptr() as *const c_char,
context.to_ref()
)
},
owned: true
}
}
pub unsafe fn unown(&mut self) {
self.owned = false;
}
pub fn verify(&self) -> Result<(), String> {
let mut verify_error = 0 as *mut c_char;
let status;
unsafe {
status = LLVMVerifyModule(
self.to_ref(),
LLVMVerifierFailureAction::LLVMReturnStatusAction,
&mut verify_error
)
}
if 1 == status {
let error;
unsafe {
let error_buffer = CStr::from_ptr(verify_error);
error = String::from_utf8_lossy(error_buffer.to_bytes()).into_owned();
LLVMDisposeMessage(verify_error);
}
Err(error)
} else {
Ok(())
}
}
}
impl Drop for Module {
fn drop(&mut self) {
if self.owned {
unsafe {
LLVMDisposeModule(self.module);
}
}
}
}
impl LLVMRef<LLVMModuleRef> for Module {
fn to_ref(&self) -> LLVMModuleRef {
self.module
}
}
impl fmt::Display for Module {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"{}",
unsafe {
let ir_as_c_string = LLVMPrintModuleToString(self.to_ref());
let ir = CStr::from_ptr(ir_as_c_string).to_string_lossy().into_owned();
LLVMDisposeMessage(ir_as_c_string);
ir
}
)
}
}
#[cfg(test)]
mod tests {
use super::Module;
use super::super::context::Context;
#[test]
fn case_ownership() {
let context = Context::new();
let module = Module::new("foobar", &context);
assert!(module.owned);
}
#[test]
fn case_id() {
let context = Context::new();
let module = Module::new("foobar", &context);
assert_eq!(
"; ModuleID = 'foobar'\n".to_string() +
"source_filename = \"foobar\"\n",
format!("{}", module)
);
}
#[test]
fn case_verify() {
let context = Context::new();
let module = Module::new("foobar", &context);
match module.verify() {
Ok(_) =>
assert!(true),
Err(_) =>
assert!(false)
}
}
}