Path: blob/main/cranelift/module/src/module.rs
3069 views
//! Defines `Module` and related types.12// TODO: Should `ir::Function` really have a `name`?34// TODO: Factor out `ir::Function`'s `ext_funcs` and `global_values` into a struct5// shared with `DataDescription`?67use super::HashMap;8use crate::data_context::DataDescription;9use core::fmt::Display;10use cranelift_codegen::binemit::{CodeOffset, Reloc};11use cranelift_codegen::entity::{PrimaryMap, entity_impl};12use cranelift_codegen::ir::ExternalName;13use cranelift_codegen::ir::function::{Function, VersionMarker};14use cranelift_codegen::settings::SetError;15use cranelift_codegen::{16CodegenError, CompileError, Context, FinalizedMachReloc, FinalizedRelocTarget, ir, isa,17};18use cranelift_control::ControlPlane;19use std::borrow::{Cow, ToOwned};20use std::boxed::Box;21use std::string::String;2223/// A module relocation.24#[derive(Clone)]25pub struct ModuleReloc {26/// The offset at which the relocation applies, *relative to the27/// containing section*.28pub offset: CodeOffset,29/// The kind of relocation.30pub kind: Reloc,31/// The external symbol / name to which this relocation refers.32pub name: ModuleRelocTarget,33/// The addend to add to the symbol value.34pub addend: i64,35}3637impl ModuleReloc {38/// Converts a `FinalizedMachReloc` produced from a `Function` into a `ModuleReloc`.39pub fn from_mach_reloc(40mach_reloc: &FinalizedMachReloc,41func: &Function,42func_id: FuncId,43) -> Self {44let name = match mach_reloc.target {45FinalizedRelocTarget::ExternalName(ExternalName::User(reff)) => {46let name = &func.params.user_named_funcs()[reff];47ModuleRelocTarget::user(name.namespace, name.index)48}49FinalizedRelocTarget::ExternalName(ExternalName::TestCase(_)) => unimplemented!(),50FinalizedRelocTarget::ExternalName(ExternalName::LibCall(libcall)) => {51ModuleRelocTarget::LibCall(libcall)52}53FinalizedRelocTarget::ExternalName(ExternalName::KnownSymbol(ks)) => {54ModuleRelocTarget::KnownSymbol(ks)55}56FinalizedRelocTarget::Func(offset) => {57ModuleRelocTarget::FunctionOffset(func_id, offset)58}59};60Self {61offset: mach_reloc.offset,62kind: mach_reloc.kind,63name,64addend: mach_reloc.addend,65}66}67}6869/// A function identifier for use in the `Module` interface.70#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]71#[cfg_attr(72feature = "enable-serde",73derive(serde_derive::Serialize, serde_derive::Deserialize)74)]75pub struct FuncId(u32);76entity_impl!(FuncId, "funcid");7778/// Function identifiers are namespace 0 in `ir::ExternalName`79impl From<FuncId> for ModuleRelocTarget {80fn from(id: FuncId) -> Self {81Self::User {82namespace: 0,83index: id.0,84}85}86}8788impl FuncId {89/// Get the `FuncId` for the function named by `name`.90pub fn from_name(name: &ModuleRelocTarget) -> FuncId {91if let ModuleRelocTarget::User { namespace, index } = name {92debug_assert_eq!(*namespace, 0);93FuncId::from_u32(*index)94} else {95panic!("unexpected name in DataId::from_name")96}97}98}99100/// A data object identifier for use in the `Module` interface.101#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]102#[cfg_attr(103feature = "enable-serde",104derive(serde_derive::Serialize, serde_derive::Deserialize)105)]106pub struct DataId(u32);107entity_impl!(DataId, "dataid");108109/// Data identifiers are namespace 1 in `ir::ExternalName`110impl From<DataId> for ModuleRelocTarget {111fn from(id: DataId) -> Self {112Self::User {113namespace: 1,114index: id.0,115}116}117}118119impl DataId {120/// Get the `DataId` for the data object named by `name`.121pub fn from_name(name: &ModuleRelocTarget) -> DataId {122if let ModuleRelocTarget::User { namespace, index } = name {123debug_assert_eq!(*namespace, 1);124DataId::from_u32(*index)125} else {126panic!("unexpected name in DataId::from_name")127}128}129}130131/// Linkage refers to where an entity is defined and who can see it.132#[derive(Copy, Clone, Debug, PartialEq, Eq)]133#[cfg_attr(134feature = "enable-serde",135derive(serde_derive::Serialize, serde_derive::Deserialize)136)]137pub enum Linkage {138/// Defined outside of a module.139Import,140/// Defined inside the module, but not visible outside it.141Local,142/// Defined inside the module, visible outside it, and may be preempted.143Preemptible,144/// Defined inside the module, visible inside the current static linkage unit, but not outside.145///146/// A static linkage unit is the combination of all object files passed to a linker to create147/// an executable or dynamic library.148Hidden,149/// Defined inside the module, and visible outside it.150Export,151}152153impl Linkage {154fn merge(a: Self, b: Self) -> Self {155match a {156Self::Export => Self::Export,157Self::Hidden => match b {158Self::Export => Self::Export,159Self::Preemptible => Self::Preemptible,160_ => Self::Hidden,161},162Self::Preemptible => match b {163Self::Export => Self::Export,164_ => Self::Preemptible,165},166Self::Local => match b {167Self::Export => Self::Export,168Self::Hidden => Self::Hidden,169Self::Preemptible => Self::Preemptible,170Self::Local | Self::Import => Self::Local,171},172Self::Import => b,173}174}175176/// Test whether this linkage can have a definition.177pub fn is_definable(self) -> bool {178match self {179Self::Import => false,180Self::Local | Self::Preemptible | Self::Hidden | Self::Export => true,181}182}183184/// Test whether this linkage must have a definition.185pub fn requires_definition(self) -> bool {186match self {187Self::Import | Self::Preemptible => false,188Self::Local | Self::Hidden | Self::Export => true,189}190}191192/// Test whether this linkage will have a definition that cannot be preempted.193pub fn is_final(self) -> bool {194match self {195Self::Import | Self::Preemptible => false,196Self::Local | Self::Hidden | Self::Export => true,197}198}199}200201/// A declared name may refer to either a function or data declaration202#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]203#[cfg_attr(204feature = "enable-serde",205derive(serde_derive::Serialize, serde_derive::Deserialize)206)]207pub enum FuncOrDataId {208/// When it's a FuncId209Func(FuncId),210/// When it's a DataId211Data(DataId),212}213214/// Mapping to `ModuleExtName` is trivial based on the `FuncId` and `DataId` mapping.215impl From<FuncOrDataId> for ModuleRelocTarget {216fn from(id: FuncOrDataId) -> Self {217match id {218FuncOrDataId::Func(funcid) => Self::from(funcid),219FuncOrDataId::Data(dataid) => Self::from(dataid),220}221}222}223224/// Information about a function which can be called.225#[derive(Debug)]226#[cfg_attr(227feature = "enable-serde",228derive(serde_derive::Serialize, serde_derive::Deserialize)229)]230#[expect(missing_docs, reason = "self-describing fields")]231pub struct FunctionDeclaration {232pub name: Option<String>,233pub linkage: Linkage,234pub signature: ir::Signature,235}236237impl FunctionDeclaration {238/// The linkage name of the function.239///240/// Synthesized from the given function id if it is an anonymous function.241pub fn linkage_name(&self, id: FuncId) -> Cow<'_, str> {242match &self.name {243Some(name) => Cow::Borrowed(name),244// Symbols starting with .L are completely omitted from the symbol table after linking.245// Using hexadecimal instead of decimal for slightly smaller symbol names and often246// slightly faster linking.247None => Cow::Owned(format!(".Lfn{:x}", id.as_u32())),248}249}250251fn merge(252&mut self,253id: FuncId,254linkage: Linkage,255sig: &ir::Signature,256) -> Result<(), ModuleError> {257self.linkage = Linkage::merge(self.linkage, linkage);258if &self.signature != sig {259return Err(ModuleError::IncompatibleSignature(260self.linkage_name(id).into_owned(),261self.signature.clone(),262sig.clone(),263));264}265Ok(())266}267}268269/// Error messages for all `Module` methods270#[derive(Debug)]271pub enum ModuleError {272/// Indicates an identifier was used before it was declared273Undeclared(String),274275/// Indicates an identifier was used as data/function first, but then used as the other276IncompatibleDeclaration(String),277278/// Indicates a function identifier was declared with a279/// different signature than declared previously280IncompatibleSignature(String, ir::Signature, ir::Signature),281282/// Indicates an identifier was defined more than once283DuplicateDefinition(String),284285/// Indicates an identifier was defined, but was declared as an import286InvalidImportDefinition(String),287288/// Wraps a `cranelift-codegen` error289Compilation(CodegenError),290291/// Memory allocation failure from a backend292Allocation {293/// Io error the allocation failed with294err: std::io::Error,295},296297/// Wraps a generic error from a backend298Backend(anyhow::Error),299300/// Wraps an error from a flag definition.301Flag(SetError),302}303304impl<'a> From<CompileError<'a>> for ModuleError {305fn from(err: CompileError<'a>) -> Self {306Self::Compilation(err.inner)307}308}309310// This is manually implementing Error and Display instead of using thiserror to reduce the amount311// of dependencies used by Cranelift.312impl std::error::Error for ModuleError {313fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {314match self {315Self::Undeclared { .. }316| Self::IncompatibleDeclaration { .. }317| Self::IncompatibleSignature { .. }318| Self::DuplicateDefinition { .. }319| Self::InvalidImportDefinition { .. } => None,320Self::Compilation(source) => Some(source),321Self::Allocation { err: source } => Some(source),322Self::Backend(source) => Some(&**source),323Self::Flag(source) => Some(source),324}325}326}327328impl std::fmt::Display for ModuleError {329fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {330match self {331Self::Undeclared(name) => {332write!(f, "Undeclared identifier: {name}")333}334Self::IncompatibleDeclaration(name) => {335write!(f, "Incompatible declaration of identifier: {name}",)336}337Self::IncompatibleSignature(name, prev_sig, new_sig) => {338write!(339f,340"Function {name} signature {new_sig:?} is incompatible with previous declaration {prev_sig:?}",341)342}343Self::DuplicateDefinition(name) => {344write!(f, "Duplicate definition of identifier: {name}")345}346Self::InvalidImportDefinition(name) => {347write!(348f,349"Invalid to define identifier declared as an import: {name}",350)351}352Self::Compilation(err) => {353write!(f, "Compilation error: {err}")354}355Self::Allocation { err } => {356write!(f, "Allocation error: {err}")357}358Self::Backend(err) => write!(f, "Backend error: {err}"),359Self::Flag(err) => write!(f, "Flag error: {err}"),360}361}362}363364impl std::convert::From<CodegenError> for ModuleError {365fn from(source: CodegenError) -> Self {366Self::Compilation { 0: source }367}368}369370impl std::convert::From<SetError> for ModuleError {371fn from(source: SetError) -> Self {372Self::Flag { 0: source }373}374}375376/// A convenient alias for a `Result` that uses `ModuleError` as the error type.377pub type ModuleResult<T> = Result<T, ModuleError>;378379/// Information about a data object which can be accessed.380#[derive(Debug)]381#[cfg_attr(382feature = "enable-serde",383derive(serde_derive::Serialize, serde_derive::Deserialize)384)]385#[expect(missing_docs, reason = "self-describing fields")]386pub struct DataDeclaration {387pub name: Option<String>,388pub linkage: Linkage,389pub writable: bool,390pub tls: bool,391}392393impl DataDeclaration {394/// The linkage name of the data object.395///396/// Synthesized from the given data id if it is an anonymous function.397pub fn linkage_name(&self, id: DataId) -> Cow<'_, str> {398match &self.name {399Some(name) => Cow::Borrowed(name),400// Symbols starting with .L are completely omitted from the symbol table after linking.401// Using hexadecimal instead of decimal for slightly smaller symbol names and often402// slightly faster linking.403None => Cow::Owned(format!(".Ldata{:x}", id.as_u32())),404}405}406407fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {408self.linkage = Linkage::merge(self.linkage, linkage);409self.writable = self.writable || writable;410assert_eq!(411self.tls, tls,412"Can't change TLS data object to normal or in the opposite way",413);414}415}416417/// A translated `ExternalName` into something global we can handle.418#[derive(Clone, Debug)]419#[cfg_attr(420feature = "enable-serde",421derive(serde_derive::Serialize, serde_derive::Deserialize)422)]423pub enum ModuleRelocTarget {424/// User defined function, converted from `ExternalName::User`.425User {426/// Arbitrary.427namespace: u32,428/// Arbitrary.429index: u32,430},431/// Call into a library function.432LibCall(ir::LibCall),433/// Symbols known to the linker.434KnownSymbol(ir::KnownSymbol),435/// A offset inside a function436FunctionOffset(FuncId, CodeOffset),437}438439impl ModuleRelocTarget {440/// Creates a user-defined external name.441pub fn user(namespace: u32, index: u32) -> Self {442Self::User { namespace, index }443}444}445446impl Display for ModuleRelocTarget {447fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {448match self {449Self::User { namespace, index } => write!(f, "u{namespace}:{index}"),450Self::LibCall(lc) => write!(f, "%{lc}"),451Self::KnownSymbol(ks) => write!(f, "{ks}"),452Self::FunctionOffset(fname, offset) => write!(f, "{fname}+{offset}"),453}454}455}456457/// This provides a view to the state of a module which allows `ir::ExternalName`s to be translated458/// into `FunctionDeclaration`s and `DataDeclaration`s.459#[derive(Debug, Default)]460pub struct ModuleDeclarations {461/// A version marker used to ensure that serialized clif ir is never deserialized with a462/// different version of Cranelift.463// Note: This must be the first field to ensure that Serde will deserialize it before464// attempting to deserialize other fields that are potentially changed between versions.465_version_marker: VersionMarker,466467names: HashMap<String, FuncOrDataId>,468functions: PrimaryMap<FuncId, FunctionDeclaration>,469data_objects: PrimaryMap<DataId, DataDeclaration>,470}471472#[cfg(feature = "enable-serde")]473mod serialize {474// This is manually implementing Serialize and Deserialize to avoid serializing the names field,475// which can be entirely reconstructed from the functions and data_objects fields, saving space.476477use super::*;478479use serde::de::{Deserialize, Deserializer, Error, MapAccess, SeqAccess, Unexpected, Visitor};480use serde::ser::{Serialize, SerializeStruct, Serializer};481use std::fmt;482483fn get_names<E: Error>(484functions: &PrimaryMap<FuncId, FunctionDeclaration>,485data_objects: &PrimaryMap<DataId, DataDeclaration>,486) -> Result<HashMap<String, FuncOrDataId>, E> {487let mut names = HashMap::new();488for (func_id, decl) in functions.iter() {489if let Some(name) = &decl.name {490let old = names.insert(name.clone(), FuncOrDataId::Func(func_id));491if old.is_some() {492return Err(E::invalid_value(493Unexpected::Other("duplicate name"),494&"FunctionDeclaration's with no duplicate names",495));496}497}498}499for (data_id, decl) in data_objects.iter() {500if let Some(name) = &decl.name {501let old = names.insert(name.clone(), FuncOrDataId::Data(data_id));502if old.is_some() {503return Err(E::invalid_value(504Unexpected::Other("duplicate name"),505&"DataDeclaration's with no duplicate names",506));507}508}509}510Ok(names)511}512513impl Serialize for ModuleDeclarations {514fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {515let ModuleDeclarations {516_version_marker,517functions,518data_objects,519names: _,520} = self;521522let mut state = s.serialize_struct("ModuleDeclarations", 4)?;523state.serialize_field("_version_marker", _version_marker)?;524state.serialize_field("functions", functions)?;525state.serialize_field("data_objects", data_objects)?;526state.end()527}528}529530enum ModuleDeclarationsField {531VersionMarker,532Functions,533DataObjects,534Ignore,535}536537struct ModuleDeclarationsFieldVisitor;538539impl<'de> serde::de::Visitor<'de> for ModuleDeclarationsFieldVisitor {540type Value = ModuleDeclarationsField;541542fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {543f.write_str("field identifier")544}545546fn visit_u64<E: Error>(self, val: u64) -> Result<Self::Value, E> {547match val {5480u64 => Ok(ModuleDeclarationsField::VersionMarker),5491u64 => Ok(ModuleDeclarationsField::Functions),5502u64 => Ok(ModuleDeclarationsField::DataObjects),551_ => Ok(ModuleDeclarationsField::Ignore),552}553}554555fn visit_str<E: Error>(self, val: &str) -> Result<Self::Value, E> {556match val {557"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),558"functions" => Ok(ModuleDeclarationsField::Functions),559"data_objects" => Ok(ModuleDeclarationsField::DataObjects),560_ => Ok(ModuleDeclarationsField::Ignore),561}562}563564fn visit_bytes<E: Error>(self, val: &[u8]) -> Result<Self::Value, E> {565match val {566b"_version_marker" => Ok(ModuleDeclarationsField::VersionMarker),567b"functions" => Ok(ModuleDeclarationsField::Functions),568b"data_objects" => Ok(ModuleDeclarationsField::DataObjects),569_ => Ok(ModuleDeclarationsField::Ignore),570}571}572}573574impl<'de> Deserialize<'de> for ModuleDeclarationsField {575#[inline]576fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {577d.deserialize_identifier(ModuleDeclarationsFieldVisitor)578}579}580581struct ModuleDeclarationsVisitor;582583impl<'de> Visitor<'de> for ModuleDeclarationsVisitor {584type Value = ModuleDeclarations;585586fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {587f.write_str("struct ModuleDeclarations")588}589590#[inline]591fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {592let _version_marker = match seq.next_element()? {593Some(val) => val,594None => {595return Err(Error::invalid_length(5960usize,597&"struct ModuleDeclarations with 4 elements",598));599}600};601let functions = match seq.next_element()? {602Some(val) => val,603None => {604return Err(Error::invalid_length(6052usize,606&"struct ModuleDeclarations with 4 elements",607));608}609};610let data_objects = match seq.next_element()? {611Some(val) => val,612None => {613return Err(Error::invalid_length(6143usize,615&"struct ModuleDeclarations with 4 elements",616));617}618};619let names = get_names(&functions, &data_objects)?;620Ok(ModuleDeclarations {621_version_marker,622names,623functions,624data_objects,625})626}627628#[inline]629fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {630let mut _version_marker: Option<VersionMarker> = None;631let mut functions: Option<PrimaryMap<FuncId, FunctionDeclaration>> = None;632let mut data_objects: Option<PrimaryMap<DataId, DataDeclaration>> = None;633while let Some(key) = map.next_key::<ModuleDeclarationsField>()? {634match key {635ModuleDeclarationsField::VersionMarker => {636if _version_marker.is_some() {637return Err(Error::duplicate_field("_version_marker"));638}639_version_marker = Some(map.next_value()?);640}641ModuleDeclarationsField::Functions => {642if functions.is_some() {643return Err(Error::duplicate_field("functions"));644}645functions = Some(map.next_value()?);646}647ModuleDeclarationsField::DataObjects => {648if data_objects.is_some() {649return Err(Error::duplicate_field("data_objects"));650}651data_objects = Some(map.next_value()?);652}653_ => {654map.next_value::<serde::de::IgnoredAny>()?;655}656}657}658let _version_marker = match _version_marker {659Some(_version_marker) => _version_marker,660None => return Err(Error::missing_field("_version_marker")),661};662let functions = match functions {663Some(functions) => functions,664None => return Err(Error::missing_field("functions")),665};666let data_objects = match data_objects {667Some(data_objects) => data_objects,668None => return Err(Error::missing_field("data_objects")),669};670let names = get_names(&functions, &data_objects)?;671Ok(ModuleDeclarations {672_version_marker,673names,674functions,675data_objects,676})677}678}679680impl<'de> Deserialize<'de> for ModuleDeclarations {681fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {682d.deserialize_struct(683"ModuleDeclarations",684&["_version_marker", "functions", "data_objects"],685ModuleDeclarationsVisitor,686)687}688}689}690691impl ModuleDeclarations {692/// Get the module identifier for a given name, if that name693/// has been declared.694pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {695self.names.get(name).copied()696}697698/// Get an iterator of all function declarations699pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {700self.functions.iter()701}702703/// Return whether `name` names a function, rather than a data object.704pub fn is_function(name: &ModuleRelocTarget) -> bool {705match name {706ModuleRelocTarget::User { namespace, .. } => *namespace == 0,707ModuleRelocTarget::LibCall(_)708| ModuleRelocTarget::KnownSymbol(_)709| ModuleRelocTarget::FunctionOffset(..) => {710panic!("unexpected module ext name")711}712}713}714715/// Get the `FunctionDeclaration` for the function named by `name`.716pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {717&self.functions[func_id]718}719720/// Get an iterator of all data declarations721pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {722self.data_objects.iter()723}724725/// Get the `DataDeclaration` for the data object named by `name`.726pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {727&self.data_objects[data_id]728}729730/// Declare a function in this module.731pub fn declare_function(732&mut self,733name: &str,734linkage: Linkage,735signature: &ir::Signature,736) -> ModuleResult<(FuncId, Linkage)> {737// TODO: Can we avoid allocating names so often?738use super::hash_map::Entry::*;739match self.names.entry(name.to_owned()) {740Occupied(entry) => match *entry.get() {741FuncOrDataId::Func(id) => {742let existing = &mut self.functions[id];743existing.merge(id, linkage, signature)?;744Ok((id, existing.linkage))745}746FuncOrDataId::Data(..) => {747Err(ModuleError::IncompatibleDeclaration(name.to_owned()))748}749},750Vacant(entry) => {751let id = self.functions.push(FunctionDeclaration {752name: Some(name.to_owned()),753linkage,754signature: signature.clone(),755});756entry.insert(FuncOrDataId::Func(id));757Ok((id, self.functions[id].linkage))758}759}760}761762/// Declare an anonymous function in this module.763pub fn declare_anonymous_function(764&mut self,765signature: &ir::Signature,766) -> ModuleResult<FuncId> {767let id = self.functions.push(FunctionDeclaration {768name: None,769linkage: Linkage::Local,770signature: signature.clone(),771});772Ok(id)773}774775/// Declare a data object in this module.776pub fn declare_data(777&mut self,778name: &str,779linkage: Linkage,780writable: bool,781tls: bool,782) -> ModuleResult<(DataId, Linkage)> {783// TODO: Can we avoid allocating names so often?784use super::hash_map::Entry::*;785match self.names.entry(name.to_owned()) {786Occupied(entry) => match *entry.get() {787FuncOrDataId::Data(id) => {788let existing = &mut self.data_objects[id];789existing.merge(linkage, writable, tls);790Ok((id, existing.linkage))791}792793FuncOrDataId::Func(..) => {794Err(ModuleError::IncompatibleDeclaration(name.to_owned()))795}796},797Vacant(entry) => {798let id = self.data_objects.push(DataDeclaration {799name: Some(name.to_owned()),800linkage,801writable,802tls,803});804entry.insert(FuncOrDataId::Data(id));805Ok((id, self.data_objects[id].linkage))806}807}808}809810/// Declare an anonymous data object in this module.811pub fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {812let id = self.data_objects.push(DataDeclaration {813name: None,814linkage: Linkage::Local,815writable,816tls,817});818Ok(id)819}820}821822/// A `Module` is a utility for collecting functions and data objects, and linking them together.823pub trait Module {824/// Return the `TargetIsa` to compile for.825fn isa(&self) -> &dyn isa::TargetIsa;826827/// Get all declarations in this module.828fn declarations(&self) -> &ModuleDeclarations;829830/// Get the module identifier for a given name, if that name831/// has been declared.832fn get_name(&self, name: &str) -> Option<FuncOrDataId> {833self.declarations().get_name(name)834}835836/// Return the target information needed by frontends to produce Cranelift IR837/// for the current target.838fn target_config(&self) -> isa::TargetFrontendConfig {839self.isa().frontend_config()840}841842/// Create a new `Context` initialized for use with this `Module`.843///844/// This ensures that the `Context` is initialized with the default calling845/// convention for the `TargetIsa`.846fn make_context(&self) -> Context {847let mut ctx = Context::new();848ctx.func.signature.call_conv = self.isa().default_call_conv();849ctx850}851852/// Clear the given `Context` and reset it for use with a new function.853///854/// This ensures that the `Context` is initialized with the default calling855/// convention for the `TargetIsa`.856fn clear_context(&self, ctx: &mut Context) {857ctx.clear();858ctx.func.signature.call_conv = self.isa().default_call_conv();859}860861/// Create a new empty `Signature` with the default calling convention for862/// the `TargetIsa`, to which parameter and return types can be added for863/// declaring a function to be called by this `Module`.864fn make_signature(&self) -> ir::Signature {865ir::Signature::new(self.isa().default_call_conv())866}867868/// Clear the given `Signature` and reset for use with a new function.869///870/// This ensures that the `Signature` is initialized with the default871/// calling convention for the `TargetIsa`.872fn clear_signature(&self, sig: &mut ir::Signature) {873sig.clear(self.isa().default_call_conv());874}875876/// Declare a function in this module.877fn declare_function(878&mut self,879name: &str,880linkage: Linkage,881signature: &ir::Signature,882) -> ModuleResult<FuncId>;883884/// Declare an anonymous function in this module.885fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId>;886887/// Declare a data object in this module.888fn declare_data(889&mut self,890name: &str,891linkage: Linkage,892writable: bool,893tls: bool,894) -> ModuleResult<DataId>;895896/// Declare an anonymous data object in this module.897fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId>;898899/// Use this when you're building the IR of a function to reference a function.900///901/// TODO: Coalesce redundant decls and signatures.902/// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.903fn declare_func_in_func(&mut self, func_id: FuncId, func: &mut ir::Function) -> ir::FuncRef {904let decl = &self.declarations().functions[func_id];905let signature = func.import_signature(decl.signature.clone());906let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {907namespace: 0,908index: func_id.as_u32(),909});910let colocated = decl.linkage.is_final();911func.import_function(ir::ExtFuncData {912name: ir::ExternalName::user(user_name_ref),913signature,914colocated,915patchable: false,916})917}918919/// Use this when you're building the IR of a function to reference a data object.920///921/// TODO: Same as above.922fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {923let decl = &self.declarations().data_objects[data];924let colocated = decl.linkage.is_final();925let user_name_ref = func.declare_imported_user_function(ir::UserExternalName {926namespace: 1,927index: data.as_u32(),928});929func.create_global_value(ir::GlobalValueData::Symbol {930name: ir::ExternalName::user(user_name_ref),931offset: ir::immediates::Imm64::new(0),932colocated,933tls: decl.tls,934})935}936937/// TODO: Same as above.938fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {939data.import_function(ModuleRelocTarget::user(0, func_id.as_u32()))940}941942/// TODO: Same as above.943fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {944data.import_global_value(ModuleRelocTarget::user(1, data_id.as_u32()))945}946947/// Define a function, producing the function body from the given `Context`.948///949/// Returns the size of the function's code and constant data.950///951/// Unlike [`define_function_with_control_plane`] this uses a default [`ControlPlane`] for952/// convenience.953///954/// Note: After calling this function the given `Context` will contain the compiled function.955///956/// [`define_function_with_control_plane`]: Self::define_function_with_control_plane957fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {958self.define_function_with_control_plane(func, ctx, &mut ControlPlane::default())959}960961/// Define a function, producing the function body from the given `Context`.962///963/// Returns the size of the function's code and constant data.964///965/// Note: After calling this function the given `Context` will contain the compiled function.966fn define_function_with_control_plane(967&mut self,968func: FuncId,969ctx: &mut Context,970ctrl_plane: &mut ControlPlane,971) -> ModuleResult<()>;972973/// Define a function, taking the function body from the given `bytes`.974///975/// This function is generally only useful if you need to precisely specify976/// the emitted instructions for some reason; otherwise, you should use977/// `define_function`.978///979/// Returns the size of the function's code.980fn define_function_bytes(981&mut self,982func_id: FuncId,983alignment: u64,984bytes: &[u8],985relocs: &[ModuleReloc],986) -> ModuleResult<()>;987988/// Define a data object, producing the data contents from the given `DataDescription`.989fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()>;990}991992impl<M: Module + ?Sized> Module for &mut M {993fn isa(&self) -> &dyn isa::TargetIsa {994(**self).isa()995}996997fn declarations(&self) -> &ModuleDeclarations {998(**self).declarations()999}10001001fn get_name(&self, name: &str) -> Option<FuncOrDataId> {1002(**self).get_name(name)1003}10041005fn target_config(&self) -> isa::TargetFrontendConfig {1006(**self).target_config()1007}10081009fn make_context(&self) -> Context {1010(**self).make_context()1011}10121013fn clear_context(&self, ctx: &mut Context) {1014(**self).clear_context(ctx)1015}10161017fn make_signature(&self) -> ir::Signature {1018(**self).make_signature()1019}10201021fn clear_signature(&self, sig: &mut ir::Signature) {1022(**self).clear_signature(sig)1023}10241025fn declare_function(1026&mut self,1027name: &str,1028linkage: Linkage,1029signature: &ir::Signature,1030) -> ModuleResult<FuncId> {1031(**self).declare_function(name, linkage, signature)1032}10331034fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {1035(**self).declare_anonymous_function(signature)1036}10371038fn declare_data(1039&mut self,1040name: &str,1041linkage: Linkage,1042writable: bool,1043tls: bool,1044) -> ModuleResult<DataId> {1045(**self).declare_data(name, linkage, writable, tls)1046}10471048fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {1049(**self).declare_anonymous_data(writable, tls)1050}10511052fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {1053(**self).declare_func_in_func(func, in_func)1054}10551056fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {1057(**self).declare_data_in_func(data, func)1058}10591060fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {1061(**self).declare_func_in_data(func_id, data)1062}10631064fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {1065(**self).declare_data_in_data(data_id, data)1066}10671068fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {1069(**self).define_function(func, ctx)1070}10711072fn define_function_with_control_plane(1073&mut self,1074func: FuncId,1075ctx: &mut Context,1076ctrl_plane: &mut ControlPlane,1077) -> ModuleResult<()> {1078(**self).define_function_with_control_plane(func, ctx, ctrl_plane)1079}10801081fn define_function_bytes(1082&mut self,1083func_id: FuncId,1084alignment: u64,1085bytes: &[u8],1086relocs: &[ModuleReloc],1087) -> ModuleResult<()> {1088(**self).define_function_bytes(func_id, alignment, bytes, relocs)1089}10901091fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {1092(**self).define_data(data_id, data)1093}1094}10951096impl<M: Module + ?Sized> Module for Box<M> {1097fn isa(&self) -> &dyn isa::TargetIsa {1098(**self).isa()1099}11001101fn declarations(&self) -> &ModuleDeclarations {1102(**self).declarations()1103}11041105fn get_name(&self, name: &str) -> Option<FuncOrDataId> {1106(**self).get_name(name)1107}11081109fn target_config(&self) -> isa::TargetFrontendConfig {1110(**self).target_config()1111}11121113fn make_context(&self) -> Context {1114(**self).make_context()1115}11161117fn clear_context(&self, ctx: &mut Context) {1118(**self).clear_context(ctx)1119}11201121fn make_signature(&self) -> ir::Signature {1122(**self).make_signature()1123}11241125fn clear_signature(&self, sig: &mut ir::Signature) {1126(**self).clear_signature(sig)1127}11281129fn declare_function(1130&mut self,1131name: &str,1132linkage: Linkage,1133signature: &ir::Signature,1134) -> ModuleResult<FuncId> {1135(**self).declare_function(name, linkage, signature)1136}11371138fn declare_anonymous_function(&mut self, signature: &ir::Signature) -> ModuleResult<FuncId> {1139(**self).declare_anonymous_function(signature)1140}11411142fn declare_data(1143&mut self,1144name: &str,1145linkage: Linkage,1146writable: bool,1147tls: bool,1148) -> ModuleResult<DataId> {1149(**self).declare_data(name, linkage, writable, tls)1150}11511152fn declare_anonymous_data(&mut self, writable: bool, tls: bool) -> ModuleResult<DataId> {1153(**self).declare_anonymous_data(writable, tls)1154}11551156fn declare_func_in_func(&mut self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {1157(**self).declare_func_in_func(func, in_func)1158}11591160fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {1161(**self).declare_data_in_func(data, func)1162}11631164fn declare_func_in_data(&self, func_id: FuncId, data: &mut DataDescription) -> ir::FuncRef {1165(**self).declare_func_in_data(func_id, data)1166}11671168fn declare_data_in_data(&self, data_id: DataId, data: &mut DataDescription) -> ir::GlobalValue {1169(**self).declare_data_in_data(data_id, data)1170}11711172fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {1173(**self).define_function(func, ctx)1174}11751176fn define_function_with_control_plane(1177&mut self,1178func: FuncId,1179ctx: &mut Context,1180ctrl_plane: &mut ControlPlane,1181) -> ModuleResult<()> {1182(**self).define_function_with_control_plane(func, ctx, ctrl_plane)1183}11841185fn define_function_bytes(1186&mut self,1187func_id: FuncId,1188alignment: u64,1189bytes: &[u8],1190relocs: &[ModuleReloc],1191) -> ModuleResult<()> {1192(**self).define_function_bytes(func_id, alignment, bytes, relocs)1193}11941195fn define_data(&mut self, data_id: DataId, data: &DataDescription) -> ModuleResult<()> {1196(**self).define_data(data_id, data)1197}1198}119912001201