use super::HashMap;
use crate::data_context::DataContext;
use cranelift_codegen::binemit;
use cranelift_codegen::entity::{entity_impl, PrimaryMap};
use cranelift_codegen::{ir, isa, CodegenError, Context};
use std::borrow::ToOwned;
use std::string::String;
use thiserror::Error;
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FuncId(u32);
entity_impl!(FuncId, "funcid");
impl From<FuncId> for ir::ExternalName {
fn from(id: FuncId) -> Self {
Self::User {
namespace: 0,
index: id.0,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DataId(u32);
entity_impl!(DataId, "dataid");
impl From<DataId> for ir::ExternalName {
fn from(id: DataId) -> Self {
Self::User {
namespace: 1,
index: id.0,
}
}
}
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Linkage {
Import,
Local,
Preemptible,
Hidden,
Export,
}
impl Linkage {
fn merge(a: Self, b: Self) -> Self {
match a {
Self::Export => Self::Export,
Self::Hidden => match b {
Self::Export => Self::Export,
Self::Preemptible => Self::Preemptible,
_ => Self::Hidden,
},
Self::Preemptible => match b {
Self::Export => Self::Export,
_ => Self::Preemptible,
},
Self::Local => match b {
Self::Export => Self::Export,
Self::Hidden => Self::Hidden,
Self::Preemptible => Self::Preemptible,
Self::Local | Self::Import => Self::Local,
},
Self::Import => b,
}
}
pub fn is_definable(self) -> bool {
match self {
Self::Import => false,
Self::Local | Self::Preemptible | Self::Hidden | Self::Export => true,
}
}
pub fn is_final(self) -> bool {
match self {
Self::Import | Self::Preemptible => false,
Self::Local | Self::Hidden | Self::Export => true,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub enum FuncOrDataId {
Func(FuncId),
Data(DataId),
}
impl From<FuncOrDataId> for ir::ExternalName {
fn from(id: FuncOrDataId) -> Self {
match id {
FuncOrDataId::Func(funcid) => Self::from(funcid),
FuncOrDataId::Data(dataid) => Self::from(dataid),
}
}
}
#[derive(Debug)]
pub struct FunctionDeclaration {
pub name: String,
pub linkage: Linkage,
pub signature: ir::Signature,
}
impl FunctionDeclaration {
fn merge(&mut self, linkage: Linkage, sig: &ir::Signature) -> Result<(), ModuleError> {
self.linkage = Linkage::merge(self.linkage, linkage);
if &self.signature != sig {
return Err(ModuleError::IncompatibleSignature(
self.name.clone(),
self.signature.clone(),
sig.clone(),
));
}
Ok(())
}
}
#[derive(Error, Debug)]
pub enum ModuleError {
#[error("Undeclared identifier: {0}")]
Undeclared(String),
#[error("Incompatible declaration of identifier: {0}")]
IncompatibleDeclaration(String),
#[error("Function {0} signature {2:?} is incompatible with previous declaration {1:?}")]
IncompatibleSignature(String, ir::Signature, ir::Signature),
#[error("Duplicate definition of identifier: {0}")]
DuplicateDefinition(String),
#[error("Invalid to define identifier declared as an import: {0}")]
InvalidImportDefinition(String),
#[error("Function {0} exceeds the maximum function size")]
FunctionTooLarge(String),
#[error("Compilation error: {0}")]
Compilation(#[from] CodegenError),
#[error("Backend error: {0}")]
Backend(#[source] anyhow::Error),
}
pub type ModuleResult<T> = Result<T, ModuleError>;
#[derive(Debug)]
pub struct DataDeclaration {
pub name: String,
pub linkage: Linkage,
pub writable: bool,
pub tls: bool,
}
impl DataDeclaration {
fn merge(&mut self, linkage: Linkage, writable: bool, tls: bool) {
self.linkage = Linkage::merge(self.linkage, linkage);
self.writable = self.writable || writable;
assert_eq!(
self.tls, tls,
"Can't change TLS data object to normal or in the opposite way",
);
}
}
#[derive(Debug, Default)]
pub struct ModuleDeclarations {
names: HashMap<String, FuncOrDataId>,
functions: PrimaryMap<FuncId, FunctionDeclaration>,
data_objects: PrimaryMap<DataId, DataDeclaration>,
}
impl ModuleDeclarations {
pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
self.names.get(name).copied()
}
pub fn get_functions(&self) -> impl Iterator<Item = (FuncId, &FunctionDeclaration)> {
self.functions.iter()
}
pub fn get_function_id(&self, name: &ir::ExternalName) -> FuncId {
if let ir::ExternalName::User { namespace, index } = *name {
debug_assert_eq!(namespace, 0);
FuncId::from_u32(index)
} else {
panic!("unexpected ExternalName kind {}", name)
}
}
pub fn get_data_id(&self, name: &ir::ExternalName) -> DataId {
if let ir::ExternalName::User { namespace, index } = *name {
debug_assert_eq!(namespace, 1);
DataId::from_u32(index)
} else {
panic!("unexpected ExternalName kind {}", name)
}
}
pub fn get_function_decl(&self, func_id: FuncId) -> &FunctionDeclaration {
&self.functions[func_id]
}
pub fn get_data_objects(&self) -> impl Iterator<Item = (DataId, &DataDeclaration)> {
self.data_objects.iter()
}
pub fn get_data_decl(&self, data_id: DataId) -> &DataDeclaration {
&self.data_objects[data_id]
}
pub fn is_function(&self, name: &ir::ExternalName) -> bool {
if let ir::ExternalName::User { namespace, .. } = *name {
namespace == 0
} else {
panic!("unexpected ExternalName kind {}", name)
}
}
pub fn declare_function(
&mut self,
name: &str,
linkage: Linkage,
signature: &ir::Signature,
) -> ModuleResult<(FuncId, &FunctionDeclaration)> {
use super::hash_map::Entry::*;
match self.names.entry(name.to_owned()) {
Occupied(entry) => match *entry.get() {
FuncOrDataId::Func(id) => {
let existing = &mut self.functions[id];
existing.merge(linkage, signature)?;
Ok((id, existing))
}
FuncOrDataId::Data(..) => {
Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
}
},
Vacant(entry) => {
let id = self.functions.push(FunctionDeclaration {
name: name.to_owned(),
linkage,
signature: signature.clone(),
});
entry.insert(FuncOrDataId::Func(id));
Ok((id, &self.functions[id]))
}
}
}
pub fn declare_data(
&mut self,
name: &str,
linkage: Linkage,
writable: bool,
tls: bool,
) -> ModuleResult<(DataId, &DataDeclaration)> {
use super::hash_map::Entry::*;
match self.names.entry(name.to_owned()) {
Occupied(entry) => match *entry.get() {
FuncOrDataId::Data(id) => {
let existing = &mut self.data_objects[id];
existing.merge(linkage, writable, tls);
Ok((id, existing))
}
FuncOrDataId::Func(..) => {
Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
}
},
Vacant(entry) => {
let id = self.data_objects.push(DataDeclaration {
name: name.to_owned(),
linkage,
writable,
tls,
});
entry.insert(FuncOrDataId::Data(id));
Ok((id, &self.data_objects[id]))
}
}
}
}
pub struct ModuleCompiledFunction {
pub size: binemit::CodeOffset,
}
pub trait Module {
fn isa(&self) -> &dyn isa::TargetIsa;
fn declarations(&self) -> &ModuleDeclarations;
fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
self.declarations().get_name(name)
}
fn target_config(&self) -> isa::TargetFrontendConfig {
self.isa().frontend_config()
}
fn make_context(&self) -> Context {
let mut ctx = Context::new();
ctx.func.signature.call_conv = self.isa().default_call_conv();
ctx
}
fn clear_context(&self, ctx: &mut Context) {
ctx.clear();
ctx.func.signature.call_conv = self.isa().default_call_conv();
}
fn make_signature(&self) -> ir::Signature {
ir::Signature::new(self.isa().default_call_conv())
}
fn clear_signature(&self, sig: &mut ir::Signature) {
sig.clear(self.isa().default_call_conv());
}
fn declare_function(
&mut self,
name: &str,
linkage: Linkage,
signature: &ir::Signature,
) -> ModuleResult<FuncId>;
fn declare_data(
&mut self,
name: &str,
linkage: Linkage,
writable: bool,
tls: bool,
) -> ModuleResult<DataId>;
fn declare_func_in_func(&self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
let decl = &self.declarations().functions[func];
let signature = in_func.import_signature(decl.signature.clone());
let colocated = decl.linkage.is_final();
in_func.import_function(ir::ExtFuncData {
name: ir::ExternalName::user(0, func.as_u32()),
signature,
colocated,
})
}
fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
let decl = &self.declarations().data_objects[data];
let colocated = decl.linkage.is_final();
func.create_global_value(ir::GlobalValueData::Symbol {
name: ir::ExternalName::user(1, data.as_u32()),
offset: ir::immediates::Imm64::new(0),
colocated,
tls: decl.tls,
})
}
fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
ctx.import_function(ir::ExternalName::user(0, func.as_u32()))
}
fn declare_data_in_data(&self, data: DataId, ctx: &mut DataContext) -> ir::GlobalValue {
ctx.import_global_value(ir::ExternalName::user(1, data.as_u32()))
}
fn define_function<TS>(
&mut self,
func: FuncId,
ctx: &mut Context,
trap_sink: &mut TS,
) -> ModuleResult<ModuleCompiledFunction>
where
TS: binemit::TrapSink;
fn define_function_bytes(
&mut self,
func: FuncId,
bytes: &[u8],
) -> ModuleResult<ModuleCompiledFunction>;
fn define_data(&mut self, data: DataId, data_ctx: &DataContext) -> ModuleResult<()>;
}