Struct inkwell::module::Module

source ·
pub struct Module<'ctx> { /* private fields */ }
Expand description

Represents a reference to an LLVM Module. The underlying module will be disposed when dropping this object.

Implementations§

source§

impl<'ctx> Module<'ctx>

source

pub unsafe fn new(module: LLVMModuleRef) -> Self

Get a module from an LLVMModuleRef.

Safety

The ref must be valid.

source

pub fn as_mut_ptr(&self) -> LLVMModuleRef

Acquires the underlying raw pointer belonging to this Module type.

source

pub fn add_function( &self, name: &str, ty: FunctionType<'ctx>, linkage: Option<Linkage> ) -> FunctionValue<'ctx>

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};
use inkwell::types::FunctionType;

let context = Context::create();
let module = context.create_module("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);
source

pub fn get_context(&self) -> ContextRef<'ctx>

Gets the Context from which this Module originates.

Example
use inkwell::context::{Context, ContextRef};
use inkwell::module::Module;

let local_context = Context::create();
let local_module = local_context.create_module("my_module");

assert_eq!(local_module.get_context(), local_context);
source

pub fn get_first_function(&self) -> Option<FunctionValue<'ctx>>

Gets the first FunctionValue defined in this Module.

Example
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());
source

pub fn get_last_function(&self) -> Option<FunctionValue<'ctx>>

Gets the last FunctionValue defined in this Module.

Example
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());
source

pub fn get_function(&self, name: &str) -> Option<FunctionValue<'ctx>>

Gets a FunctionValue defined in this Module by its name.

Example
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());
source

pub fn get_functions(&self) -> FunctionIterator<'ctx>

An iterator over the functions in this Module.

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);

let names: Vec<String> = module
    .get_functions()
    .map(|f| f.get_name().to_string_lossy().to_string())
    .collect();

assert_eq!(vec!["my_fn".to_owned()], names);
source

pub fn get_struct_type(&self, name: &str) -> Option<StructType<'ctx>>

Gets a named StructType from this Module’s Context.

Example
use inkwell::context::Context;

let context = Context::create();
let module = context.create_module("my_module");

assert!(module.get_struct_type("foo").is_none());

let opaque = context.opaque_struct_type("foo");

assert_eq!(module.get_struct_type("foo").unwrap(), opaque);
source

pub fn set_triple(&self, triple: &TargetTriple)

Assigns a TargetTriple to this Module.

Example
use inkwell::context::Context;
use inkwell::targets::{Target, TargetTriple};

Target::initialize_x86(&Default::default());
let context = Context::create();
let module = context.create_module("mod");
let triple = TargetTriple::create("x86_64-pc-linux-gnu");

assert_eq!(module.get_triple(), TargetTriple::create(""));

module.set_triple(&triple);

assert_eq!(module.get_triple(), triple);
source

pub fn get_triple(&self) -> TargetTriple

Gets the TargetTriple assigned to this Module. If none has been assigned, the triple will default to “”.

Example
use inkwell::context::Context;
use inkwell::targets::{Target, TargetTriple};

Target::initialize_x86(&Default::default());
let context = Context::create();
let module = context.create_module("mod");
let triple = TargetTriple::create("x86_64-pc-linux-gnu");

assert_eq!(module.get_triple(), TargetTriple::create(""));

module.set_triple(&triple);

assert_eq!(module.get_triple(), triple);
source

pub fn create_execution_engine( &self ) -> Result<ExecutionEngine<'ctx>, LLVMString>

Creates an ExecutionEngine from this Module.

Example
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::create();
let module = context.create_module("my_module");
let execution_engine = module.create_execution_engine().unwrap();

assert_eq!(module.get_context(), context);
source

pub fn create_interpreter_execution_engine( &self ) -> Result<ExecutionEngine<'ctx>, LLVMString>

Creates an interpreter ExecutionEngine from this Module.

Example
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::create();
let module = context.create_module("my_module");
let execution_engine = module.create_interpreter_execution_engine().unwrap();

assert_eq!(module.get_context(), context);
source

pub fn create_jit_execution_engine( &self, opt_level: OptimizationLevel ) -> Result<ExecutionEngine<'ctx>, LLVMString>

Creates a JIT ExecutionEngine from this Module.

Example
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::create();
let module = context.create_module("my_module");
let execution_engine = module.create_jit_execution_engine(OptimizationLevel::None).unwrap();

assert_eq!(module.get_context(), context);
source

pub fn add_global<T: BasicType<'ctx>>( &self, type_: T, address_space: Option<AddressSpace>, name: &str ) -> GlobalValue<'ctx>

Creates a GlobalValue based on a type in an address space.

Example
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::from(1u16)), "my_global");

assert_eq!(module.get_first_global().unwrap(), global);
assert_eq!(module.get_last_global().unwrap(), global);
source

pub fn write_bitcode_to_path(&self, path: &Path) -> bool

Writes a Module to a Path.

Example
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);
source

pub fn write_bitcode_to_file( &self, file: &File, should_close: bool, unbuffered: bool ) -> bool

write_bitcode_to_path should be preferred over this method, as it does not work on all operating systems.

source

pub fn write_bitcode_to_memory(&self) -> MemoryBuffer

Writes this Module to a MemoryBuffer.

Example
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 = context.append_basic_block(f, "entry");
let builder = context.create_builder();

builder.position_at_end(basic_block);
builder.build_return(None);

let buffer = module.write_bitcode_to_memory();
source

pub fn verify(&self) -> Result<(), LLVMString>

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

source

pub fn get_data_layout(&self) -> Ref<'_, DataLayout>

Gets a smart pointer to the DataLayout belonging to a particular Module.

Example
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);
source

pub fn set_data_layout(&self, data_layout: &DataLayout)

Sets the DataLayout for a particular Module.

Example
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);
source

pub fn print_to_stderr(&self)

Prints the content of the Module to stderr.

source

pub fn print_to_string(&self) -> LLVMString

Prints the content of the Module to an LLVMString.

source

pub fn print_to_file<P: AsRef<Path>>(&self, path: P) -> Result<(), LLVMString>

Prints the content of the Module to a file.

source

pub fn to_string(&self) -> String

Prints the content of the Module to a String.

source

pub fn set_inline_assembly(&self, asm: &str)

Sets the inline assembly for the Module.

source

pub fn add_global_metadata( &self, key: &str, metadata: &MetadataValue<'ctx> ) -> Result<(), &'static str>

Appends a MetaDataValue to a global list indexed by a particular key.

Example
use inkwell::context::Context;

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 = context.metadata_string("lots of metadata here");
let md_node = context.metadata_node(&[bool_val.into(), f32_val.into()]);

module.add_global_metadata("my_md", &md_string).unwrap();
module.add_global_metadata("my_md", &md_node).unwrap();

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].into_metadata_value().get_string_value(), md_string.get_string_value());
assert_eq!(md_1[0].into_int_value(), bool_val);
assert_eq!(md_1[1].into_float_value(), f32_val);
source

pub fn get_global_metadata_size(&self, key: &str) -> u32

Obtains the number of MetaDataValues indexed by a particular key.

Example
use inkwell::context::Context;

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 = context.metadata_string("lots of metadata here");
let md_node = context.metadata_node(&[bool_val.into(), f32_val.into()]);

module.add_global_metadata("my_md", &md_string).unwrap();
module.add_global_metadata("my_md", &md_node).unwrap();

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].into_metadata_value().get_string_value(), md_string.get_string_value());
assert_eq!(md_1[0].into_int_value(), bool_val);
assert_eq!(md_1[1].into_float_value(), f32_val);
source

pub fn get_global_metadata(&self, key: &str) -> Vec<MetadataValue<'ctx>>

Obtains the global MetaDataValue node indexed by key, which may contain 1 string or multiple values as its get_node_values()

Example
use inkwell::context::Context;

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 = context.metadata_string("lots of metadata here");
let md_node = context.metadata_node(&[bool_val.into(), f32_val.into()]);

module.add_global_metadata("my_md", &md_string).unwrap();
module.add_global_metadata("my_md", &md_node).unwrap();

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].into_metadata_value().get_string_value(), md_string.get_string_value());
assert_eq!(md_1[0].into_int_value(), bool_val);
assert_eq!(md_1[1].into_float_value(), f32_val);
source

pub fn get_first_global(&self) -> Option<GlobalValue<'ctx>>

Gets the first GlobalValue in a module.

Example
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::from(4u16)), "my_global");

assert_eq!(module.get_first_global().unwrap(), global);
source

pub fn get_last_global(&self) -> Option<GlobalValue<'ctx>>

Gets the last GlobalValue in a module.

Example
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::from(4u16)), "my_global");

assert_eq!(module.get_last_global().unwrap(), global);
source

pub fn get_global(&self, name: &str) -> Option<GlobalValue<'ctx>>

Gets a named GlobalValue in a module.

Example
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::from(4u16)), "my_global");

assert_eq!(module.get_global("my_global").unwrap(), global);
source

pub fn get_globals(&self) -> GlobalIterator<'ctx>

An iterator over the globals in this Module.

source

pub fn parse_bitcode_from_buffer( buffer: &MemoryBuffer, context: impl AsContextRef<'ctx> ) -> Result<Self, LLVMString>

Creates a new Module from a MemoryBuffer with bitcode.

Example
use inkwell::context::Context;
use inkwell::module::Module;
use inkwell::memory_buffer::MemoryBuffer;
use std::path::Path;

let path = Path::new("foo/bar.bc");
let context = Context::create();
let buffer = MemoryBuffer::create_from_file(&path).unwrap();
let module = Module::parse_bitcode_from_buffer(&buffer, &context);

assert_eq!(module.unwrap().get_context(), context);
source

pub fn parse_bitcode_from_path<P: AsRef<Path>>( path: P, context: impl AsContextRef<'ctx> ) -> Result<Self, LLVMString>

A convenience function for creating a Module from a bitcode file for a given context.

Example
use inkwell::context::Context;
use inkwell::module::Module;
use std::path::Path;

let path = Path::new("foo/bar.bc");
let context = Context::create();
let module = Module::parse_bitcode_from_path(&path, &context);

assert_eq!(module.unwrap().get_context(), context);
source

pub fn get_name(&self) -> &CStr

Gets the name of this Module.

Example
use inkwell::context::Context;

let context = Context::create();
let module = context.create_module("my_module");

assert_eq!(module.get_name().to_str(), Ok("my_mdoule"));
source

pub fn set_name(&self, name: &str)

Assigns the name of this Module.

Example
use inkwell::context::Context;

let context = Context::create();
let module = context.create_module("my_module");

module.set_name("my_module2");

assert_eq!(module.get_name().to_str(), Ok("my_module2"));
source

pub fn get_source_file_name(&self) -> &CStr

Gets the source file name. It defaults to the module identifier but is separate from it.

Example
use inkwell::context::Context;

let context = Context::create();
let module = context.create_module("my_mod");

assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod"));

module.set_source_file_name("my_mod.rs");

assert_eq!(module.get_name().to_str(), Ok("my_mod"));
assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod.rs"));
source

pub fn set_source_file_name(&self, file_name: &str)

Sets the source file name. It defaults to the module identifier but is separate from it.

Example
use inkwell::context::Context;

let context = Context::create();
let module = context.create_module("my_mod");

assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod"));

module.set_source_file_name("my_mod.rs");

assert_eq!(module.get_name().to_str(), Ok("my_mod"));
assert_eq!(module.get_source_file_name().to_str(), Ok("my_mod.rs"));

Links one module into another. This will merge two Modules into one.

Example
use inkwell::context::Context;

let context = Context::create();
let module = context.create_module("mod");
let module2 = context.create_module("mod2");

assert!(module.link_in_module(module2).is_ok());
source

pub fn get_or_insert_comdat(&self, name: &str) -> Comdat

Gets the Comdat associated with a particular name. If it does not exist, it will be created. A new Comdat defaults to a kind of ComdatSelectionKind::Any.

source

pub fn get_flag(&self, key: &str) -> Option<MetadataValue<'ctx>>

Gets the MetadataValue flag associated with the key in this module, if any. If a BasicValue was used to create this flag, it will be wrapped in a MetadataValue when returned from this function.

source

pub fn add_metadata_flag( &self, key: &str, behavior: FlagBehavior, flag: MetadataValue<'ctx> )

Append a MetadataValue as a module wide flag. Note that using the same key twice will likely invalidate the module.

source

pub fn add_basic_value_flag<BV: BasicValue<'ctx>>( &self, key: &str, behavior: FlagBehavior, flag: BV )

Append a BasicValue as a module wide flag. Note that using the same key twice will likely invalidate the module.

source

pub fn strip_debug_info(&self) -> bool

Strips and debug info from the module, if it exists.

source

pub fn get_debug_metadata_version(&self) -> c_uint

Gets the version of debug metadata contained in this Module.

source

pub fn create_debug_info_builder( &self, allow_unresolved: bool, language: DWARFSourceLanguage, filename: &str, directory: &str, producer: &str, is_optimized: bool, flags: &str, runtime_ver: c_uint, split_name: &str, kind: DWARFEmissionKind, dwo_id: c_uint, split_debug_inlining: bool, debug_info_for_profiling: bool, sysroot: &str, sdk: &str ) -> (DebugInfoBuilder<'ctx>, DICompileUnit<'ctx>)

Creates a DebugInfoBuilder for this Module.

source

pub fn run_passes( &self, passes: &str, machine: &TargetMachine, options: PassBuilderOptions ) -> Result<(), LLVMString>

Construct and run a set of passes over a module. This function takes a string with the passes that should be used. The format of this string is the same as opt’s -passes argument for the new pass manager. Individual passes may be specified, separated by commas. Full pipelines may also be invoked using default and friends. See opt for full reference of the Passes format.

Trait Implementations§

source§

impl Clone for Module<'_>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'ctx> Debug for Module<'ctx>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Drop for Module<'_>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl<'ctx> PartialEq for Module<'ctx>

source§

fn eq(&self, other: &Module<'ctx>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl PassManagerSubType for Module<'_>

§

type Input = ()

source§

unsafe fn create<I: Borrow<Self::Input>>(_: I) -> LLVMPassManagerRef

source§

unsafe fn run_in_pass_manager(&self, pass_manager: &PassManager<Self>) -> bool

source§

impl<'ctx> Eq for Module<'ctx>

source§

impl<'ctx> StructuralEq for Module<'ctx>

source§

impl<'ctx> StructuralPartialEq for Module<'ctx>

Auto Trait Implementations§

§

impl<'ctx> !RefUnwindSafe for Module<'ctx>

§

impl<'ctx> !Send for Module<'ctx>

§

impl<'ctx> !Sync for Module<'ctx>

§

impl<'ctx> Unpin for Module<'ctx>

§

impl<'ctx> UnwindSafe for Module<'ctx>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.