forked from TheDan64/inkwell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic_block.rs
470 lines (435 loc) · 17.3 KB
/
basic_block.rs
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! A `BasicBlock` is a container of instructions.
use llvm_sys::core::{LLVMGetBasicBlockParent, LLVMGetBasicBlockTerminator, LLVMGetNextBasicBlock, LLVMInsertBasicBlock, LLVMIsABasicBlock, LLVMIsConstant, LLVMMoveBasicBlockAfter, LLVMMoveBasicBlockBefore, LLVMPrintTypeToString, LLVMPrintValueToString, LLVMTypeOf, LLVMDeleteBasicBlock, LLVMGetPreviousBasicBlock, LLVMRemoveBasicBlockFromParent, LLVMGetFirstInstruction, LLVMGetLastInstruction, LLVMGetTypeContext, LLVMBasicBlockAsValue};
#[llvm_versions(3.9 => latest)]
use llvm_sys::core::LLVMGetBasicBlockName;
use llvm_sys::prelude::{LLVMValueRef, LLVMBasicBlockRef};
use crate::context::{Context, ContextRef};
use crate::values::{FunctionValue, InstructionValue};
use std::fmt;
use std::ffi::{CStr, CString};
use std::rc::Rc;
/// A `BasicBlock` is a container of instructions.
///
/// `BasicBlock`s are values because they can be referenced by instructions (ie branching and switches).
///
/// A well formed `BasicBlock` is a list of non terminating instructions followed by a single terminating
/// instruction. `BasicBlock`s are allowed to be malformed prior to running validation because it may be useful
/// when constructing or modifying a program.
#[derive(PartialEq, Eq, Clone, Copy, Hash)]
pub struct BasicBlock {
pub(crate) basic_block: LLVMBasicBlockRef,
}
impl BasicBlock {
pub(crate) fn new(basic_block: LLVMBasicBlockRef) -> Option<Self> {
if basic_block.is_null() {
return None;
}
unsafe {
// NOTE: There is a LLVMBasicBlockAsValue but it might be the same as casting
assert!(!LLVMIsABasicBlock(basic_block as LLVMValueRef).is_null())
}
Some(BasicBlock { basic_block })
}
/// Obtains the `FunctionValue` that this `BasicBlock` belongs to, if any.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// assert_eq!(basic_block.get_parent().unwrap(), function);
///
/// basic_block.remove_from_function();
///
/// assert!(basic_block.get_parent().is_none());
/// ```
pub fn get_parent(&self) -> Option<FunctionValue> {
let value = unsafe {
LLVMGetBasicBlockParent(self.basic_block)
};
FunctionValue::new(value)
}
/// Gets the `BasicBlock` preceeding the current one, in its own scope, if any.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function1 = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block1 = context.append_basic_block(&function1, "entry");
///
/// assert!(basic_block1.get_previous_basic_block().is_none());
///
/// let function2 = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block2 = context.append_basic_block(&function2, "entry");
/// let basic_block3 = context.append_basic_block(&function2, "next");
///
/// assert!(basic_block2.get_previous_basic_block().is_none());
/// assert_eq!(basic_block3.get_previous_basic_block().unwrap(), basic_block2);
/// ```
pub fn get_previous_basic_block(&self) -> Option<BasicBlock> {
let bb = unsafe {
LLVMGetPreviousBasicBlock(self.basic_block)
};
BasicBlock::new(bb)
}
/// Gets the `BasicBlock` succeeding the current one, in its own scope, if any.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function1 = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block1 = context.append_basic_block(&function1, "entry");
///
/// assert!(basic_block1.get_next_basic_block().is_none());
///
/// let function2 = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block2 = context.append_basic_block(&function2, "entry");
/// let basic_block3 = context.append_basic_block(&function2, "next");
///
/// assert!(basic_block1.get_next_basic_block().is_none());
/// assert_eq!(basic_block2.get_next_basic_block().unwrap(), basic_block3);
/// assert!(basic_block3.get_next_basic_block().is_none());
/// ```
pub fn get_next_basic_block(&self) -> Option<BasicBlock> {
let bb = unsafe {
LLVMGetNextBasicBlock(self.basic_block)
};
BasicBlock::new(bb)
}
/// Prepends one `BasicBlock` before another.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block1 = context.append_basic_block(&function, "entry");
/// let basic_block2 = context.append_basic_block(&function, "next");
///
/// basic_block2.move_before(&basic_block1);
///
/// assert!(basic_block1.get_next_basic_block().is_none());
/// assert_eq!(basic_block2.get_next_basic_block().unwrap(), basic_block1);
/// ```
// REVIEW: What happens if blocks are from different scopes?
pub fn move_before(&self, basic_block: &BasicBlock) {
unsafe {
LLVMMoveBasicBlockBefore(self.basic_block, basic_block.basic_block)
}
}
/// Appends one `BasicBlock` after another.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block1 = context.append_basic_block(&function, "entry");
/// let basic_block2 = context.append_basic_block(&function, "next");
///
/// basic_block1.move_after(&basic_block2);
///
/// assert!(basic_block1.get_next_basic_block().is_none());
/// assert_eq!(basic_block2.get_next_basic_block().unwrap(), basic_block1);
/// ```
// REVIEW: What happens if blocks are from different scopes?
pub fn move_after(&self, basic_block: &BasicBlock) {
unsafe {
LLVMMoveBasicBlockAfter(self.basic_block, basic_block.basic_block)
}
}
/// Prepends a new `BasicBlock` before this one.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
///
/// let basic_block1 = context.append_basic_block(&function, "entry");
/// let basic_block2 = basic_block1.prepend_basic_block("previous");
///
/// assert!(basic_block1.get_next_basic_block().is_none());
/// assert_eq!(basic_block2.get_next_basic_block().unwrap(), basic_block1);
/// ```
pub fn prepend_basic_block(&self, name: &str) -> BasicBlock {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let bb = unsafe {
LLVMInsertBasicBlock(self.basic_block, c_string.as_ptr())
};
BasicBlock::new(bb).expect("Prepending basic block should never fail")
}
/// Obtains the first `InstructionValue` in this `BasicBlock`, if any.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
/// use inkwell::values::InstructionOpcode;
///
/// let context = Context::create();
/// let builder = context.create_builder();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// builder.position_at_end(&basic_block);
/// builder.build_return(None);
///
/// assert_eq!(basic_block.get_first_instruction().unwrap().get_opcode(), InstructionOpcode::Return);
/// ```
pub fn get_first_instruction(&self) -> Option<InstructionValue> {
let value = unsafe {
LLVMGetFirstInstruction(self.basic_block)
};
if value.is_null() {
return None;
}
Some(InstructionValue::new(value))
}
/// Obtains the last `InstructionValue` in this `BasicBlock`, if any. A `BasicBlock` must have a last instruction to be valid.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
/// use inkwell::values::InstructionOpcode;
///
/// let context = Context::create();
/// let builder = context.create_builder();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// builder.position_at_end(&basic_block);
/// builder.build_return(None);
///
/// assert_eq!(basic_block.get_last_instruction().unwrap().get_opcode(), InstructionOpcode::Return);
/// ```
pub fn get_last_instruction(&self) -> Option<InstructionValue> {
let value = unsafe {
LLVMGetLastInstruction(self.basic_block)
};
if value.is_null() {
return None;
}
Some(InstructionValue::new(value))
}
/// Obtains the terminating `InstructionValue` in this `BasicBlock`, if any. A `BasicBlock` must have a terminating instruction to be valid.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
/// use inkwell::values::InstructionOpcode;
///
/// let context = Context::create();
/// let builder = context.create_builder();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// builder.position_at_end(&basic_block);
/// builder.build_return(None);
///
/// assert_eq!(basic_block.get_terminator().unwrap().get_opcode(), InstructionOpcode::Return);
/// ```
// REVIEW: If we wanted the return type could be Option<Either<BasicValueEnum, InstructionValue>>
// if getting a value over an instruction is preferable
// TODOC: Every BB must have a terminating instruction or else it is invalid
// REVIEW: Unclear how this differs from get_last_instruction
pub fn get_terminator(&self) -> Option<InstructionValue> {
let value = unsafe {
LLVMGetBasicBlockTerminator(self.basic_block)
};
if value.is_null() {
return None;
}
Some(InstructionValue::new(value))
}
/// Removes this `BasicBlock` from its parent `FunctionValue`. Does nothing if it has no parent.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// assert_eq!(basic_block.get_parent().unwrap(), function);
///
/// basic_block.remove_from_function();
///
/// assert!(basic_block.get_parent().is_none());
/// ```
// SubTypes: Don't need to call get_parent for a BasicBlock<HasParent> and would return BasicBlock<Orphan>
// by taking ownership of self (though BasicBlock's are not uniquely obtained...)
// might have to make some methods do something like -> Result<..., BasicBlock<Orphan>> for BasicBlock<HasParent>
// and would move_before/after make it no longer orphaned? etc..
pub fn remove_from_function(&self) {
// This method is UB if the parent no longer exists, so we must check for parent (or encode into type system)
if self.get_parent().is_some() {
unsafe {
LLVMRemoveBasicBlockFromParent(self.basic_block)
}
}
}
/// Removes this `BasicBlock` completely from memory. This is unsafe because you could easily have other references to the same `BasicBlock`.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// unsafe {
/// basic_block.delete();
/// }
/// assert!(function.get_basic_blocks().is_empty());
/// ```
// REVIEW: Could potentially be unsafe if there are existing references. Might need a global ref counter
pub unsafe fn delete(self) {
// unsafe {
LLVMDeleteBasicBlock(self.basic_block)
// }
}
/// Obtains the `ContextRef` this `BasicBlock` belongs to.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::builder::Builder;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let function = module.add_function("do_nothing", fn_type, None);
/// let basic_block = context.append_basic_block(&function, "entry");
///
/// assert_eq!(context, *basic_block.get_context());
/// ```
pub fn get_context(&self) -> ContextRef {
let context = unsafe {
LLVMGetTypeContext(LLVMTypeOf(LLVMBasicBlockAsValue(self.basic_block)))
};
// REVIEW: This probably should be somehow using the existing context Rc
ContextRef::new(Context::new(Rc::new(context)))
}
/// Gets the name of a `BasicBlock`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use std::ffi::CString;
///
/// let context = Context::create();
/// let builder = context.create_builder();
/// let module = context.create_module("my_mod");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_val = module.add_function("my_fn", fn_type, None);
/// let bb = context.append_basic_block(&fn_val, "entry");
///
/// assert_eq!(*bb.get_name(), *CString::new("entry").unwrap());
/// ```
#[llvm_versions(3.9 => latest)]
pub fn get_name(&self) -> &CStr {
let ptr = unsafe {
LLVMGetBasicBlockName(self.basic_block)
};
unsafe {
CStr::from_ptr(ptr)
}
}
}
impl fmt::Debug for BasicBlock {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let llvm_value = unsafe {
CStr::from_ptr(LLVMPrintValueToString(self.basic_block as LLVMValueRef))
};
let llvm_type = unsafe {
CStr::from_ptr(LLVMPrintTypeToString(LLVMTypeOf(self.basic_block as LLVMValueRef)))
};
let is_const = unsafe {
LLVMIsConstant(self.basic_block as LLVMValueRef) == 1
};
f.debug_struct("BasicBlock")
.field("address", &self.basic_block)
.field("is_const", &is_const)
.field("llvm_value", &llvm_value)
.field("llvm_type", &llvm_type)
.finish()
}
}