-
Notifications
You must be signed in to change notification settings - Fork 215
/
module.rs
1347 lines (1204 loc) · 50.8 KB
/
module.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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A `Module` represets a single code compilation unit.
use llvm_sys::analysis::{LLVMVerifyModule, LLVMVerifierFailureAction};
#[allow(deprecated)]
use llvm_sys::bit_reader::{LLVMParseBitcode, LLVMParseBitcodeInContext};
use llvm_sys::bit_writer::{LLVMWriteBitcodeToFile, LLVMWriteBitcodeToMemoryBuffer};
use llvm_sys::core::{LLVMAddFunction, LLVMAddGlobal, LLVMDumpModule, LLVMGetNamedFunction, LLVMGetTypeByName, LLVMSetDataLayout, LLVMSetTarget, LLVMCloneModule, LLVMDisposeModule, LLVMGetTarget, LLVMModuleCreateWithName, LLVMGetModuleContext, LLVMGetFirstFunction, LLVMGetLastFunction, LLVMAddGlobalInAddressSpace, LLVMPrintModuleToString, LLVMGetNamedMetadataNumOperands, LLVMAddNamedMetadataOperand, LLVMGetNamedMetadataOperands, LLVMGetFirstGlobal, LLVMGetLastGlobal, LLVMGetNamedGlobal, LLVMPrintModuleToFile};
#[llvm_versions(3.9 => latest)]
use llvm_sys::core::{LLVMGetModuleIdentifier, LLVMSetModuleIdentifier};
use llvm_sys::execution_engine::{LLVMCreateInterpreterForModule, LLVMCreateJITCompilerForModule, LLVMCreateExecutionEngineForModule};
use llvm_sys::prelude::{LLVMValueRef, LLVMModuleRef};
use llvm_sys::LLVMLinkage;
use std::cell::{Cell, RefCell, Ref};
#[llvm_versions(3.9 => latest)]
use std::ffi::CStr;
use std::ffi::CString;
use std::fs::File;
use std::mem::{forget, zeroed};
use std::path::Path;
use std::ptr;
use std::rc::Rc;
use std::slice::from_raw_parts;
use {AddressSpace, OptimizationLevel};
#[llvm_versions(7.0 => latest)]
use comdat::Comdat;
use context::{Context, ContextRef};
use data_layout::DataLayout;
use execution_engine::ExecutionEngine;
use memory_buffer::MemoryBuffer;
use support::LLVMString;
use targets::Target;
use types::{AsTypeRef, BasicType, FunctionType, BasicTypeEnum};
use values::{AsValueRef, FunctionValue, GlobalValue, MetadataValue};
enum_rename!{
/// This enum defines how to link a global variable or function in a module. The variant documenation is
/// mostly taken straight from LLVM's own documentation except for some minor clarification.
///
/// It is illegal for a function declaration to have any linkage type other than external or extern_weak.
///
/// All Global Variables, Functions and Aliases can have one of the following DLL storage class: `DLLImport`
/// & `DLLExport`.
// REVIEW: Maybe this should go into it's own module?
Linkage <=> LLVMLinkage {
/// `Appending` linkage may only be applied to global variables of pointer to array type. When two global
/// variables with appending linkage are linked together, the two global arrays are appended together.
/// This is the LLVM, typesafe, equivalent of having the system linker append together "sections" with
/// identical names when .o files are linked. Unfortunately this doesn't correspond to any feature in .o
/// files, so it can only be used for variables like llvm.global_ctors which llvm interprets specially.
Appending <=> LLVMAppendingLinkage,
/// Globals with `AvailableExternally` linkage are never emitted into the object file corresponding to
/// the LLVM module. From the linker's perspective, an `AvailableExternally` global is equivalent to an
/// external declaration. They exist to allow inlining and other optimizations to take place given
/// knowledge of the definition of the global, which is known to be somewhere outside the module. Globals
/// with `AvailableExternally` linkage are allowed to be discarded at will, and allow inlining and other
/// optimizations. This linkage type is only allowed on definitions, not declarations.
AvailableExternally <=> LLVMAvailableExternallyLinkage,
/// `Common` linkage is most similar to "weak" linkage, but they are used for tentative definitions
/// in C, such as "int X;" at global scope. Symbols with Common linkage are merged in the same way as
/// weak symbols, and they may not be deleted if unreferenced. `Common` symbols may not have an explicit
/// section, must have a zero initializer, and may not be marked 'constant'. Functions and aliases may
/// not have `Common` linkage.
Common <=> LLVMCommonLinkage,
/// `DLLExport` causes the compiler to provide a global pointer to a pointer in a DLL, so that it can be
/// referenced with the dllimport attribute. On Microsoft Windows targets, the pointer name is formed by
/// combining __imp_ and the function or variable name. Since this storage class exists for defining a dll
/// interface, the compiler, assembler and linker know it is externally referenced and must refrain from
/// deleting the symbol.
DLLExport <=> LLVMDLLExportLinkage,
/// `DLLImport` causes the compiler to reference a function or variable via a global pointer to a pointer
/// that is set up by the DLL exporting the symbol. On Microsoft Windows targets, the pointer name is
/// formed by combining __imp_ and the function or variable name.
DLLImport <=> LLVMDLLImportLinkage,
/// If none of the other identifiers are used, the global is externally visible, meaning that it
/// participates in linkage and can be used to resolve external symbol references.
External <=> LLVMExternalLinkage,
/// The semantics of this linkage follow the ELF object file model: the symbol is weak until linked,
/// if not linked, the symbol becomes null instead of being an undefined reference.
ExternalWeak <=> LLVMExternalWeakLinkage,
/// FIXME: Unknown linkage type
Ghost <=> LLVMGhostLinkage,
/// Similar to private, but the value shows as a local symbol (STB_LOCAL in the case of ELF) in the object
/// file. This corresponds to the notion of the 'static' keyword in C.
Internal <=> LLVMInternalLinkage,
/// FIXME: Unknown linkage type
LinkerPrivate <=> LLVMLinkerPrivateLinkage,
/// FIXME: Unknown linkage type
LinkerPrivateWeak <=> LLVMLinkerPrivateWeakLinkage,
/// Globals with `LinkOnceAny` linkage are merged with other globals of the same name when linkage occurs.
/// This can be used to implement some forms of inline functions, templates, or other code which must be
/// generated in each translation unit that uses it, but where the body may be overridden with a more
/// definitive definition later. Unreferenced `LinkOnceAny` globals are allowed to be discarded. Note that
/// `LinkOnceAny` linkage does not actually allow the optimizer to inline the body of this function into
/// callers because it doesn’t know if this definition of the function is the definitive definition within
/// the program or whether it will be overridden by a stronger definition. To enable inlining and other
/// optimizations, use `LinkOnceODR` linkage.
LinkOnceAny <=> LLVMLinkOnceAnyLinkage,
/// FIXME: Unknown linkage type
LinkOnceODRAutoHide <=> LLVMLinkOnceODRAutoHideLinkage,
/// Some languages allow differing globals to be merged, such as two functions with different semantics.
/// Other languages, such as C++, ensure that only equivalent globals are ever merged (the "one definition
/// rule" — "ODR"). Such languages can use the `LinkOnceODR` and `WeakODR` linkage types to indicate that
/// the global will only be merged with equivalent globals. These linkage types are otherwise the same
/// as their non-odr versions.
LinkOnceODR <=> LLVMLinkOnceODRLinkage,
/// Global values with `Private` linkage are only directly accessible by objects in the current module.
/// In particular, linking code into a module with a private global value may cause the private to be
/// renamed as necessary to avoid collisions. Because the symbol is private to the module, all references
/// can be updated. This doesn’t show up in any symbol table in the object file.
Private <=> LLVMPrivateLinkage,
/// `WeakAny` linkage has the same merging semantics as linkonce linkage, except that unreferenced globals
/// with weak linkage may not be discarded. This is used for globals that are declared WeakAny in C source code.
WeakAny <=> LLVMWeakAnyLinkage,
/// Some languages allow differing globals to be merged, such as two functions with different semantics.
/// Other languages, such as C++, ensure that only equivalent globals are ever merged (the "one definition
/// rule" — "ODR"). Such languages can use the `LinkOnceODR` and `WeakODR` linkage types to indicate that
/// the global will only be merged with equivalent globals. These linkage types are otherwise the same
/// as their non-odr versions.
WeakODR <=> LLVMWeakODRLinkage,
}
}
/// Represents a reference to an LLVM `Module`.
/// The underlying module will be disposed when dropping this object.
#[derive(Debug, PartialEq, Eq)]
pub struct Module {
pub(crate) non_global_context: Option<Context>, // REVIEW: Could we just set context to the global context?
data_layout: RefCell<Option<DataLayout>>,
pub(crate) module: Cell<LLVMModuleRef>,
pub(crate) owned_by_ee: RefCell<Option<ExecutionEngine>>,
}
impl Module {
pub(crate) fn new(module: LLVMModuleRef, context: Option<&Context>) -> Self {
debug_assert!(!module.is_null());
Module {
module: Cell::new(module),
non_global_context: context.map(|ctx| Context::new(ctx.context.clone())),
owned_by_ee: RefCell::new(None),
data_layout: RefCell::new(Some(Module::get_borrowed_data_layout(module))),
}
}
/// Creates a named `Module`. Will be automatically assigned the global context.
///
/// To use your own `Context`, see [inkwell::context::create_module()](../context/struct.Context.html#method.create_module)
///
/// # Example
/// ```
/// use inkwell::context::Context;
/// use inkwell::module::Module;
///
/// let context = Context::get_global();
/// let module = Module::create("my_module");
///
/// assert_eq!(module.get_context(), context);
/// ```
pub fn create(name: &str) -> Self {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let module = unsafe {
LLVMModuleCreateWithName(c_string.as_ptr())
};
Module::new(module, None)
}
/// Creates a function given its `name` and `ty`, adds it to the `Module`
/// and returns it.
///
/// An optional `linkage` can be specified, without which the default value
/// `Linkage::ExternalLinkage` will be used.
///
/// # Example
/// ```
/// use inkwell::context::Context;
/// use inkwell::module::{Module, Linkage};
///
/// let context = Context::get_global();
/// let module = Module::create("my_module");
///
/// let fn_type = context.f32_type().fn_type(&[], false);
/// let fn_val = module.add_function("my_function", fn_type, None);
///
/// assert_eq!(fn_val.get_name().to_str(), Ok("my_function"));
/// assert_eq!(fn_val.get_linkage(), Linkage::External);
/// ```
pub fn add_function(&self, name: &str, ty: FunctionType, linkage: Option<Linkage>) -> FunctionValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMAddFunction(self.module.get(), c_string.as_ptr(), ty.as_type_ref())
};
let fn_value = FunctionValue::new(value).expect("add_function should always succeed in adding a new function");
if let Some(linkage) = linkage {
fn_value.set_linkage(linkage)
}
fn_value
}
/// Gets the `Context` from which this `Module` originates.
///
/// # Example
/// ```
/// use inkwell::context::{Context, ContextRef};
/// use inkwell::module::Module;
///
/// let global_context = Context::get_global();
/// let global_module = Module::create("my_global_module");
///
/// assert_eq!(global_module.get_context(), global_context);
///
/// let local_context = Context::create();
/// let local_module = local_context.create_module("my_module");
///
/// assert_eq!(*local_module.get_context(), local_context);
/// assert_ne!(local_context, *global_context);
/// ```
pub fn get_context(&self) -> ContextRef {
let context = unsafe {
LLVMGetModuleContext(self.module.get())
};
// REVIEW: This probably should be somehow using the existing context Rc
ContextRef::new(Context::new(Rc::new(context)))
}
/// Gets the first `FunctionValue` defined in this `Module`.
///
/// # Example
/// ```rust,no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
///
/// let context = Context::create();
/// let module = context.create_module("my_mod");
///
/// assert!(module.get_first_function().is_none());
///
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("my_fn", fn_type, None);
///
/// assert_eq!(fn_value, module.get_first_function().unwrap());
/// ```
pub fn get_first_function(&self) -> Option<FunctionValue> {
let function = unsafe {
LLVMGetFirstFunction(self.module.get())
};
FunctionValue::new(function)
}
/// Gets the last `FunctionValue` defined in this `Module`.
///
/// # Example
/// ```rust,no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
///
/// let context = Context::create();
/// let module = context.create_module("my_mod");
///
/// assert!(module.get_last_function().is_none());
///
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("my_fn", fn_type, None);
///
/// assert_eq!(fn_value, module.get_last_function().unwrap());
/// ```
pub fn get_last_function(&self) -> Option<FunctionValue> {
let function = unsafe {
LLVMGetLastFunction(self.module.get())
};
FunctionValue::new(function)
}
/// Gets a `FunctionValue` defined in this `Module` by its name.
///
/// # Example
/// ```rust,no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
///
/// let context = Context::create();
/// let module = context.create_module("my_mod");
///
/// assert!(module.get_function("my_fn").is_none());
///
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let fn_value = module.add_function("my_fn", fn_type, None);
///
/// assert_eq!(fn_value, module.get_function("my_fn").unwrap());
/// ```
pub fn get_function(&self, name: &str) -> Option<FunctionValue> {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
LLVMGetNamedFunction(self.module.get(), c_string.as_ptr())
};
FunctionValue::new(value)
}
/// Gets a `BasicTypeEnum` of a named type in a `Module`.
///
/// # Example
///
/// ```rust,no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
///
/// assert!(module.get_type("foo").is_none());
///
/// let opaque = context.opaque_struct_type("foo");
///
/// assert_eq!(module.get_type("foo").unwrap(), opaque.into());
/// ```
pub fn get_type(&self, name: &str) -> Option<BasicTypeEnum> {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let type_ = unsafe {
LLVMGetTypeByName(self.module.get(), c_string.as_ptr())
};
if type_.is_null() {
return None;
}
Some(BasicTypeEnum::new(type_))
}
/// Sets a `Target` to this `Module`.
///
/// # Example
///
/// ```rust,no_run
/// use inkwell::context::Context;
/// use inkwell::targets::Target;
///
/// Target::initialize_x86(&Default::default());
///
/// let context = Context::create();
/// let module = context.create_module("mod");
/// let target = Target::from_name("x86-64").unwrap();
///
/// assert!(module.get_target().is_none());
///
/// module.set_target(&target);
///
/// assert_eq!(module.get_target().unwrap(), target);
/// ```
pub fn set_target(&self, target: &Target) {
unsafe {
LLVMSetTarget(self.module.get(), target.get_name().as_ptr())
}
}
/// Gets the `Target` assigned to this `Module`, if any.
///
/// # Example
///
/// ```rust,no_run
/// use inkwell::context::Context;
/// use inkwell::targets::Target;
///
/// Target::initialize_x86(&Default::default());
///
/// let context = Context::create();
/// let module = context.create_module("mod");
/// let target = Target::from_name("x86-64").unwrap();
///
/// assert!(module.get_target().is_none());
///
/// module.set_target(&target);
///
/// assert_eq!(module.get_target().unwrap(), target);
/// ```
pub fn get_target(&self) -> Option<Target> {
// REVIEW: This isn't an owned LLVMString, is it? If so, need to deallocate.
let target_str = unsafe {
LLVMGetTarget(self.module.get())
};
Target::from_name_raw(target_str)
}
/// Creates an `ExecutionEngine` from this `Module`.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::targets::{InitializationConfig, Target};
///
/// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
///
/// let context = Context::get_global();
/// let module = Module::create("my_module");
/// let execution_engine = module.create_execution_engine().unwrap();
///
/// assert_eq!(module.get_context(), context);
/// ```
// SubType: ExecutionEngine<?>
pub fn create_execution_engine(&self) -> Result<ExecutionEngine, LLVMString> {
let mut execution_engine = unsafe { zeroed() };
let mut err_string = unsafe { zeroed() };
let code = unsafe {
LLVMCreateExecutionEngineForModule(&mut execution_engine, self.module.get(), &mut err_string) // Takes ownership of module
};
if code == 1 {
return Err(LLVMString::new(err_string));
}
let execution_engine = ExecutionEngine::new(Rc::new(execution_engine), false);
*self.owned_by_ee.borrow_mut() = Some(execution_engine.clone());
Ok(execution_engine)
}
/// Creates an interpreter `ExecutionEngine` from this `Module`.
///
/// # Example
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::targets::{InitializationConfig, Target};
///
/// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
///
/// let context = Context::get_global();
/// let module = Module::create("my_module");
/// let execution_engine = module.create_interpreter_execution_engine().unwrap();
///
/// assert_eq!(module.get_context(), context);
/// ```
// SubType: ExecutionEngine<Interpreter>
pub fn create_interpreter_execution_engine(&self) -> Result<ExecutionEngine, LLVMString> {
let mut execution_engine = unsafe { zeroed() };
let mut err_string = unsafe { zeroed() };
let code = unsafe {
LLVMCreateInterpreterForModule(&mut execution_engine, self.module.get(), &mut err_string) // Takes ownership of module
};
if code == 1 {
return Err(LLVMString::new(err_string));
}
let execution_engine = ExecutionEngine::new(Rc::new(execution_engine), false);
*self.owned_by_ee.borrow_mut() = Some(execution_engine.clone());
Ok(execution_engine)
}
/// Creates a JIT `ExecutionEngine` from this `Module`.
///
/// # Example
/// ```no_run
/// use inkwell::OptimizationLevel;
/// use inkwell::context::Context;
/// use inkwell::module::Module;
/// use inkwell::targets::{InitializationConfig, Target};
///
/// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
///
/// let context = Context::get_global();
/// let module = Module::create("my_module");
/// let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
///
/// assert_eq!(module.get_context(), context);
/// ```
// SubType: ExecutionEngine<Jit>
pub fn create_jit_execution_engine(&self, opt_level: OptimizationLevel) -> Result<ExecutionEngine, LLVMString> {
let mut execution_engine = unsafe { zeroed() };
let mut err_string = unsafe { zeroed() };
let code = unsafe {
LLVMCreateJITCompilerForModule(&mut execution_engine, self.module.get(), opt_level as u32, &mut err_string) // Takes ownership of module
};
if code == 1 {
// The module still seems "owned" in this error case, despite failing to create an EE. This would normally
// end in a segfault on Module drop, however we're avoiding that by cloning the module and replacing the underlying pointer
// REVIEW: Ensure this doesn't lead to unexpected behavior... If it does, the alternate strategy would be to change the fn
// signature to take ownership of self and return it with good EE: (self, opt_level) -> Result<(Module, EE), LLVMString>
let module = self.clone();
self.module.set(module.module.get());
forget(module);
// REVIEW: Module still seems "owned" in the error case and may segfault on module drop. :/
// Need to figure out if there's a way to prevent this.
return Err(LLVMString::new(err_string));
}
let execution_engine = ExecutionEngine::new(Rc::new(execution_engine), true);
*self.owned_by_ee.borrow_mut() = Some(execution_engine.clone());
Ok(execution_engine)
}
/// Creates a `GlobalValue` based on a type in an address space.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("mod");
/// let i8_type = context.i8_type();
/// let global = module.add_global(i8_type, Some(AddressSpace::Const), "my_global");
///
/// assert_eq!(module.get_first_global().unwrap(), global);
/// assert_eq!(module.get_last_global().unwrap(), global);
/// ```
pub fn add_global<T: BasicType>(&self, type_: T, address_space: Option<AddressSpace>, name: &str) -> GlobalValue {
let c_string = CString::new(name).expect("Conversion to CString failed unexpectedly");
let value = unsafe {
match address_space {
Some(address_space) => LLVMAddGlobalInAddressSpace(self.module.get(), type_.as_type_ref(), c_string.as_ptr(), address_space as u32),
None => LLVMAddGlobal(self.module.get(), type_.as_type_ref(), c_string.as_ptr()),
}
};
GlobalValue::new(value)
}
/// Writes a `Module` to a `Path`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// use std::path::Path;
///
/// let mut path = Path::new("module.bc");
///
/// 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);
///
/// module.add_function("my_fn", fn_type, None);
/// module.write_bitcode_to_path(&path);
/// ```
pub fn write_bitcode_to_path(&self, path: &Path) -> bool {
let path_str = path.to_str().expect("Did not find a valid Unicode path string");
let c_string = CString::new(path_str).expect("Conversion to CString failed unexpectedly");
unsafe {
LLVMWriteBitcodeToFile(self.module.get(), c_string.as_ptr()) == 0
}
}
// See GH issue #6
/// `write_bitcode_to_path` should be preferred over this method, as it does not work on all operating systems.
pub fn write_bitcode_to_file(&self, file: &File, should_close: bool, unbuffered: bool) -> bool {
#[cfg(unix)]
{
use std::os::unix::io::AsRawFd;
use llvm_sys::bit_writer::LLVMWriteBitcodeToFD;
// REVIEW: as_raw_fd docs suggest it only works in *nix
// Also, should_close should maybe be hardcoded to true?
unsafe {
LLVMWriteBitcodeToFD(self.module.get(), file.as_raw_fd(), should_close as i32, unbuffered as i32) == 0
}
}
#[cfg(windows)]
return false;
}
/// Writes this `Module` to a `MemoryBuffer`.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("mod");
/// let void_type = context.void_type();
/// let fn_type = void_type.fn_type(&[], false);
/// let f = module.add_function("f", fn_type, None);
/// let basic_block = f.append_basic_block("entry");
/// let builder = context.create_builder();
///
/// builder.position_at_end(&basic_block);
/// builder.build_return(None);
///
/// let buffer = module.write_bitcode_to_memory();
/// ```
pub fn write_bitcode_to_memory(&self) -> MemoryBuffer {
let memory_buffer = unsafe {
LLVMWriteBitcodeToMemoryBuffer(self.module.get())
};
MemoryBuffer::new(memory_buffer)
}
/// Ensures that the current `Module` is valid, and returns a `Result`
/// that describes whether or not it is, returning a LLVM allocated string on error.
///
/// # Remarks
/// See also: http://llvm.org/doxygen/Analysis_2Analysis_8cpp_source.html
pub fn verify(&self) -> Result<(), LLVMString> {
let mut err_str = unsafe { zeroed() };
let action = LLVMVerifierFailureAction::LLVMReturnStatusAction;
let code = unsafe {
LLVMVerifyModule(self.module.get(), action, &mut err_str)
};
if code == 1 && !err_str.is_null() {
return Err(LLVMString::new(err_str));
}
Ok(())
}
fn get_borrowed_data_layout(module: LLVMModuleRef) -> DataLayout {
#[cfg(any(feature = "llvm3-6", feature = "llvm3-7", feature = "llvm3-8"))]
let data_layout = unsafe {
use llvm_sys::core::LLVMGetDataLayout;
LLVMGetDataLayout(module)
};
#[cfg(not(any(feature = "llvm3-6", feature = "llvm3-7", feature = "llvm3-8")))]
let data_layout = unsafe {
use llvm_sys::core::LLVMGetDataLayoutStr;
LLVMGetDataLayoutStr(module)
};
DataLayout::new_borrowed(data_layout)
}
/// Gets a smart pointer to the `DataLayout` belonging to a particular `Module`.
///
/// # Example
///
/// ```no_run
/// use inkwell::OptimizationLevel;
/// use inkwell::context::Context;
/// use inkwell::targets::{InitializationConfig, Target};
///
/// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
/// let target_data = execution_engine.get_target_data();
/// let data_layout = target_data.get_data_layout();
///
/// module.set_data_layout(&data_layout);
///
/// assert_eq!(*module.get_data_layout(), data_layout);
/// ```
pub fn get_data_layout(&self) -> Ref<DataLayout> {
Ref::map(self.data_layout.borrow(), |l| l.as_ref().expect("DataLayout should always exist until Drop"))
}
// REVIEW: Ensure the replaced string ptr still gets cleaned up by the module (I think it does)
// valgrind might come in handy once non jemalloc allocators stabilize
/// Sets the `DataLayout` for a particular `Module`.
///
/// # Example
///
/// ```no_run
/// use inkwell::OptimizationLevel;
/// use inkwell::context::Context;
/// use inkwell::targets::{InitializationConfig, Target};
///
/// Target::initialize_native(&InitializationConfig::default()).expect("Failed to initialize native target");
///
/// let context = Context::create();
/// let module = context.create_module("sum");
/// let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();
/// let target_data = execution_engine.get_target_data();
/// let data_layout = target_data.get_data_layout();
///
/// module.set_data_layout(&data_layout);
///
/// assert_eq!(*module.get_data_layout(), data_layout);
/// ```
pub fn set_data_layout(&self, data_layout: &DataLayout) {
unsafe {
LLVMSetDataLayout(self.module.get(), data_layout.as_ptr());
}
*self.data_layout.borrow_mut() = Some(Module::get_borrowed_data_layout(self.module.get()));
}
/// Prints the content of the `Module` to stderr.
pub fn print_to_stderr(&self) {
unsafe {
LLVMDumpModule(self.module.get());
}
}
/// Prints the content of the `Module` to a string.
pub fn print_to_string(&self) -> LLVMString {
let module_string = unsafe {
LLVMPrintModuleToString(self.module.get())
};
LLVMString::new(module_string)
}
/// Prints the content of the `Module` to a file.
pub fn print_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), LLVMString> {
let path = path.as_ref().to_str().expect("Did not find a valid Unicode path string");
let mut err_string = unsafe { zeroed() };
let return_code = unsafe {
LLVMPrintModuleToFile(self.module.get(), path.as_ptr() as *const i8, &mut err_string)
};
if return_code == 1 {
return Err(LLVMString::new(err_string));
}
Ok(())
}
/// Sets the inline assembly for the `Module`.
pub fn set_inline_assembly(&self, asm: &str) {
#[cfg(any(feature = "llvm3-6", feature = "llvm3-7", feature = "llvm3-8", feature = "llvm3-9",
feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0"))]
{
use llvm_sys::core::LLVMSetModuleInlineAsm;
let c_string = CString::new(asm).expect("Conversion to CString failed unexpectedly");
unsafe {
LLVMSetModuleInlineAsm(self.module.get(), c_string.as_ptr())
}
}
#[cfg(not(any(feature = "llvm3-6", feature = "llvm3-7", feature = "llvm3-8", feature = "llvm3-9",
feature = "llvm4-0", feature = "llvm5-0", feature = "llvm6-0")))]
{
use llvm_sys::core::LLVMSetModuleInlineAsm2;
unsafe {
LLVMSetModuleInlineAsm2(self.module.get(), asm.as_ptr() as *const i8, asm.len())
}
}
}
// REVIEW: Should module take ownership of metadata?
// REVIEW: Should we return a MetadataValue for the global since it's its own value?
// it would be the last item in get_global_metadata I believe
// TODOC: Appends your metadata to a global MetadataValue<Node> indexed by key
/// Appends a `MetaDataValue` to a global list indexed by a particular key.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::values::MetadataValue;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let bool_type = context.bool_type();
/// let f32_type = context.f32_type();
/// let bool_val = bool_type.const_int(0, false);
/// let f32_val = f32_type.const_float(0.0);
///
/// assert_eq!(module.get_global_metadata_size("my_md"), 0);
///
/// let md_string = MetadataValue::create_string("lots of metadata here");
/// let md_node = MetadataValue::create_node(&[&bool_val, &f32_val]);
///
/// module.add_global_metadata("my_md", &md_string);
/// module.add_global_metadata("my_md", &md_node);
///
/// assert_eq!(module.get_global_metadata_size("my_md"), 2);
///
/// let global_md = module.get_global_metadata("my_md");
///
/// assert_eq!(global_md.len(), 2);
///
/// let (md_0, md_1) = (global_md[0].get_node_values(), global_md[1].get_node_values());
///
/// assert_eq!(md_0.len(), 1);
/// assert_eq!(md_1.len(), 2);
/// assert_eq!(md_0[0].as_metadata_value().get_string_value(), md_string.get_string_value());
/// assert_eq!(md_1[0].as_int_value(), &bool_val);
/// assert_eq!(md_1[1].as_float_value(), &f32_val);
/// ```
pub fn add_global_metadata(&self, key: &str, metadata: &MetadataValue) {
let c_string = CString::new(key).expect("Conversion to CString failed unexpectedly");
unsafe {
LLVMAddNamedMetadataOperand(self.module.get(), c_string.as_ptr(), metadata.as_value_ref())
}
}
// REVIEW: Better name? get_global_metadata_len or _count?
/// Obtains the number of `MetaDataValue`s indexed by a particular key.
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::values::MetadataValue;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let bool_type = context.bool_type();
/// let f32_type = context.f32_type();
/// let bool_val = bool_type.const_int(0, false);
/// let f32_val = f32_type.const_float(0.0);
///
/// assert_eq!(module.get_global_metadata_size("my_md"), 0);
///
/// let md_string = MetadataValue::create_string("lots of metadata here");
/// let md_node = MetadataValue::create_node(&[&bool_val, &f32_val]);
///
/// module.add_global_metadata("my_md", &md_string);
/// module.add_global_metadata("my_md", &md_node);
///
/// assert_eq!(module.get_global_metadata_size("my_md"), 2);
///
/// let global_md = module.get_global_metadata("my_md");
///
/// assert_eq!(global_md.len(), 2);
///
/// let (md_0, md_1) = (global_md[0].get_node_values(), global_md[1].get_node_values());
///
/// assert_eq!(md_0.len(), 1);
/// assert_eq!(md_1.len(), 2);
/// assert_eq!(md_0[0].as_metadata_value().get_string_value(), md_string.get_string_value());
/// assert_eq!(md_1[0].as_int_value(), &bool_val);
/// assert_eq!(md_1[1].as_float_value(), &f32_val);
/// ```
pub fn get_global_metadata_size(&self, key: &str) -> u32 {
let c_string = CString::new(key).expect("Conversion to CString failed unexpectedly");
unsafe {
LLVMGetNamedMetadataNumOperands(self.module.get(), c_string.as_ptr())
}
}
// SubTypes: -> Vec<MetadataValue<Node>>
/// Obtains the global `MetaDataValue` node indexed by key, which may contain 1 string or multiple values as its `get_node_values()`
///
/// # Example
///
/// ```no_run
/// use inkwell::context::Context;
/// use inkwell::values::MetadataValue;
///
/// let context = Context::create();
/// let module = context.create_module("my_module");
/// let bool_type = context.bool_type();
/// let f32_type = context.f32_type();
/// let bool_val = bool_type.const_int(0, false);
/// let f32_val = f32_type.const_float(0.0);
///
/// assert_eq!(module.get_global_metadata_size("my_md"), 0);
///
/// let md_string = MetadataValue::create_string("lots of metadata here");
/// let md_node = MetadataValue::create_node(&[&bool_val, &f32_val]);
///
/// module.add_global_metadata("my_md", &md_string);
/// module.add_global_metadata("my_md", &md_node);
///
/// assert_eq!(module.get_global_metadata_size("my_md"), 2);
///
/// let global_md = module.get_global_metadata("my_md");
///
/// assert_eq!(global_md.len(), 2);
///
/// let (md_0, md_1) = (global_md[0].get_node_values(), global_md[1].get_node_values());
///
/// assert_eq!(md_0.len(), 1);
/// assert_eq!(md_1.len(), 2);
/// assert_eq!(md_0[0].as_metadata_value().get_string_value(), md_string.get_string_value());
/// assert_eq!(md_1[0].as_int_value(), &bool_val);
/// assert_eq!(md_1[1].as_float_value(), &f32_val);
/// ```
pub fn get_global_metadata(&self, key: &str) -> Vec<MetadataValue> {
let c_string = CString::new(key).expect("Conversion to CString failed unexpectedly");
let count = self.get_global_metadata_size(key);
let mut raw_vec: Vec<LLVMValueRef> = Vec::with_capacity(count as usize);
let ptr = raw_vec.as_mut_ptr();
forget(raw_vec);
let slice = unsafe {
LLVMGetNamedMetadataOperands(self.module.get(), c_string.as_ptr(), ptr);
from_raw_parts(ptr, count as usize)
};
slice.iter().map(|val| MetadataValue::new(*val)).collect()
}
/// Gets the first `GlobalValue` in a module.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let i8_type = context.i8_type();
/// let module = context.create_module("mod");
///
/// assert!(module.get_first_global().is_none());
///
/// let global = module.add_global(i8_type, Some(AddressSpace::Const), "my_global");
///
/// assert_eq!(module.get_first_global().unwrap(), global);
/// ```
pub fn get_first_global(&self) -> Option<GlobalValue> {
let value = unsafe {
LLVMGetFirstGlobal(self.module.get())
};
if value.is_null() {
return None;
}
Some(GlobalValue::new(value))
}
/// Gets the last `GlobalValue` in a module.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("mod");
/// let i8_type = context.i8_type();
///
/// assert!(module.get_last_global().is_none());
///
/// let global = module.add_global(i8_type, Some(AddressSpace::Const), "my_global");
///
/// assert_eq!(module.get_last_global().unwrap(), global);
/// ```
pub fn get_last_global(&self) -> Option<GlobalValue> {
let value = unsafe {
LLVMGetLastGlobal(self.module.get())
};
if value.is_null() {
return None;
}
Some(GlobalValue::new(value))
}
/// Gets a named `GlobalValue` in a module.
///
/// # Example
///
/// ```no_run
/// use inkwell::AddressSpace;
/// use inkwell::context::Context;
///
/// let context = Context::create();
/// let module = context.create_module("mod");
/// let i8_type = context.i8_type();
///
/// assert!(module.get_global("my_global").is_none());
///
/// let global = module.add_global(i8_type, Some(AddressSpace::Const), "my_global");
///
/// assert_eq!(module.get_global("my_global").unwrap(), global);
/// ```