use super::HashMap;
use crate::data_context::DataContext;
use crate::Backend;
use cranelift_codegen::binemit::{self, CodeInfo};
use cranelift_codegen::entity::{entity_impl, PrimaryMap};
use cranelift_codegen::{ir, isa, CodegenError, Context};
use log::info;
use std::borrow::ToOwned;
use std::string::String;
use std::vec::Vec;
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,
Export,
}
impl Linkage {
fn merge(a: Self, b: Self) -> Self {
match a {
Self::Export => Self::Export,
Self::Preemptible => match b {
Self::Export => Self::Export,
_ => Self::Preemptible,
},
Self::Local => match b {
Self::Export => Self::Export,
Self::Preemptible => Self::Preemptible,
_ => Self::Local,
},
Self::Import => b,
}
}
pub fn is_definable(self) -> bool {
match self {
Self::Import => false,
Self::Local | Self::Preemptible | Self::Export => true,
}
}
pub fn is_final(self) -> bool {
match self {
Self::Import | Self::Preemptible => false,
Self::Local | 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),
}
}
}
pub struct FunctionDeclaration {
pub name: String,
pub linkage: Linkage,
pub signature: ir::Signature,
}
#[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("Compilation error: {0}")]
Compilation(#[from] CodegenError),
#[error("Backend error: {0}")]
Backend(String),
}
pub type ModuleResult<T> = Result<T, ModuleError>;
pub struct ModuleFunction<B>
where
B: Backend,
{
pub decl: FunctionDeclaration,
pub compiled: Option<B::CompiledFunction>,
}
impl<B> ModuleFunction<B>
where
B: Backend,
{
fn merge(&mut self, linkage: Linkage, sig: &ir::Signature) -> Result<(), ModuleError> {
self.decl.linkage = Linkage::merge(self.decl.linkage, linkage);
if &self.decl.signature != sig {
return Err(ModuleError::IncompatibleSignature(
self.decl.name.clone(),
self.decl.signature.clone(),
sig.clone(),
));
}
Ok(())
}
}
pub struct DataDeclaration {
pub name: String,
pub linkage: Linkage,
pub writable: bool,
pub align: Option<u8>,
}
struct ModuleData<B>
where
B: Backend,
{
decl: DataDeclaration,
compiled: Option<B::CompiledData>,
}
impl<B> ModuleData<B>
where
B: Backend,
{
fn merge(&mut self, linkage: Linkage, writable: bool, align: Option<u8>) {
self.decl.linkage = Linkage::merge(self.decl.linkage, linkage);
self.decl.writable = self.decl.writable || writable;
self.decl.align = self.decl.align.max(align);
}
}
struct ModuleContents<B>
where
B: Backend,
{
functions: PrimaryMap<FuncId, ModuleFunction<B>>,
data_objects: PrimaryMap<DataId, ModuleData<B>>,
}
impl<B> ModuleContents<B>
where
B: Backend,
{
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)
}
}
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)
}
}
fn get_function_info(&self, name: &ir::ExternalName) -> &ModuleFunction<B> {
&self.functions[self.get_function_id(name)]
}
fn get_data_info(&self, name: &ir::ExternalName) -> &ModuleData<B> {
&self.data_objects[self.get_data_id(name)]
}
}
pub struct ModuleNamespace<'a, B: 'a>
where
B: Backend,
{
contents: &'a ModuleContents<B>,
}
impl<'a, B> ModuleNamespace<'a, B>
where
B: Backend,
{
pub fn get_function_id(&self, name: &ir::ExternalName) -> FuncId {
self.contents.get_function_id(name)
}
pub fn get_data_id(&self, name: &ir::ExternalName) -> DataId {
self.contents.get_data_id(name)
}
pub fn get_function_decl(&self, name: &ir::ExternalName) -> &FunctionDeclaration {
&self.contents.get_function_info(name).decl
}
pub fn get_data_decl(&self, name: &ir::ExternalName) -> &DataDeclaration {
&self.contents.get_data_info(name).decl
}
pub fn get_function_definition(
&self,
name: &ir::ExternalName,
) -> (Option<&B::CompiledFunction>, &str, &ir::Signature) {
let info = self.contents.get_function_info(name);
debug_assert!(
!info.decl.linkage.is_definable() || info.compiled.is_some(),
"Finalization requires a definition for function {}.",
name,
);
debug_assert_eq!(info.decl.linkage.is_definable(), info.compiled.is_some());
(
info.compiled.as_ref(),
&info.decl.name,
&info.decl.signature,
)
}
pub fn get_data_definition(
&self,
name: &ir::ExternalName,
) -> (Option<&B::CompiledData>, &str, bool) {
let info = self.contents.get_data_info(name);
debug_assert!(
!info.decl.linkage.is_definable() || info.compiled.is_some(),
"Finalization requires a definition for data object {}.",
name,
);
debug_assert_eq!(info.decl.linkage.is_definable(), info.compiled.is_some());
(info.compiled.as_ref(), &info.decl.name, info.decl.writable)
}
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 struct Module<B>
where
B: Backend,
{
names: HashMap<String, FuncOrDataId>,
contents: ModuleContents<B>,
functions_to_finalize: Vec<FuncId>,
data_objects_to_finalize: Vec<DataId>,
backend: B,
}
impl<B> Module<B>
where
B: Backend,
{
pub fn new(backend_builder: B::Builder) -> Self {
Self {
names: HashMap::new(),
contents: ModuleContents {
functions: PrimaryMap::new(),
data_objects: PrimaryMap::new(),
},
functions_to_finalize: Vec::new(),
data_objects_to_finalize: Vec::new(),
backend: B::new(backend_builder),
}
}
pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
self.names.get(name).cloned()
}
pub fn target_config(&self) -> isa::TargetFrontendConfig {
self.backend.isa().frontend_config()
}
pub fn make_context(&self) -> Context {
let mut ctx = Context::new();
ctx.func.signature.call_conv = self.backend.isa().default_call_conv();
ctx
}
pub fn clear_context(&self, ctx: &mut Context) {
ctx.clear();
ctx.func.signature.call_conv = self.backend.isa().default_call_conv();
}
pub fn make_signature(&self) -> ir::Signature {
ir::Signature::new(self.backend.isa().default_call_conv())
}
pub fn clear_signature(&self, sig: &mut ir::Signature) {
sig.clear(self.backend.isa().default_call_conv());
}
pub fn declare_function(
&mut self,
name: &str,
linkage: Linkage,
signature: &ir::Signature,
) -> ModuleResult<FuncId> {
use super::hash_map::Entry::*;
match self.names.entry(name.to_owned()) {
Occupied(entry) => match *entry.get() {
FuncOrDataId::Func(id) => {
let existing = &mut self.contents.functions[id];
existing.merge(linkage, signature)?;
self.backend
.declare_function(id, name, existing.decl.linkage);
Ok(id)
}
FuncOrDataId::Data(..) => {
Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
}
},
Vacant(entry) => {
let id = self.contents.functions.push(ModuleFunction {
decl: FunctionDeclaration {
name: name.to_owned(),
linkage,
signature: signature.clone(),
},
compiled: None,
});
entry.insert(FuncOrDataId::Func(id));
self.backend.declare_function(id, name, linkage);
Ok(id)
}
}
}
pub fn declared_functions(&self) -> core::slice::Iter<'_, ModuleFunction<B>> {
self.contents.functions.values()
}
pub fn declare_data(
&mut self,
name: &str,
linkage: Linkage,
writable: bool,
align: Option<u8>,
) -> ModuleResult<DataId> {
use super::hash_map::Entry::*;
match self.names.entry(name.to_owned()) {
Occupied(entry) => match *entry.get() {
FuncOrDataId::Data(id) => {
let existing = &mut self.contents.data_objects[id];
existing.merge(linkage, writable, align);
self.backend.declare_data(
id,
name,
existing.decl.linkage,
existing.decl.writable,
existing.decl.align,
);
Ok(id)
}
FuncOrDataId::Func(..) => {
Err(ModuleError::IncompatibleDeclaration(name.to_owned()))
}
},
Vacant(entry) => {
let id = self.contents.data_objects.push(ModuleData {
decl: DataDeclaration {
name: name.to_owned(),
linkage,
writable,
align,
},
compiled: None,
});
entry.insert(FuncOrDataId::Data(id));
self.backend
.declare_data(id, name, linkage, writable, align);
Ok(id)
}
}
}
pub fn declare_func_in_func(&self, func: FuncId, in_func: &mut ir::Function) -> ir::FuncRef {
let decl = &self.contents.functions[func].decl;
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,
})
}
pub fn declare_data_in_func(&self, data: DataId, func: &mut ir::Function) -> ir::GlobalValue {
let decl = &self.contents.data_objects[data].decl;
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,
})
}
pub fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
ctx.import_function(ir::ExternalName::user(0, func.as_u32()))
}
pub fn declare_data_in_data(&self, data: DataId, ctx: &mut DataContext) -> ir::GlobalValue {
ctx.import_global_value(ir::ExternalName::user(1, data.as_u32()))
}
pub fn define_function(
&mut self,
func: FuncId,
ctx: &mut Context,
) -> ModuleResult<binemit::CodeOffset> {
info!(
"defining function {}: {}",
func,
ctx.func.display(self.backend.isa())
);
let CodeInfo { total_size, .. } = ctx.compile(self.backend.isa())?;
let info = &self.contents.functions[func];
if info.compiled.is_some() {
return Err(ModuleError::DuplicateDefinition(info.decl.name.clone()));
}
if !info.decl.linkage.is_definable() {
return Err(ModuleError::InvalidImportDefinition(info.decl.name.clone()));
}
let compiled = Some(self.backend.define_function(
func,
&info.decl.name,
ctx,
&ModuleNamespace::<B> {
contents: &self.contents,
},
total_size,
)?);
self.contents.functions[func].compiled = compiled;
self.functions_to_finalize.push(func);
Ok(total_size)
}
pub fn define_data(&mut self, data: DataId, data_ctx: &DataContext) -> ModuleResult<()> {
let compiled = {
let info = &self.contents.data_objects[data];
if info.compiled.is_some() {
return Err(ModuleError::DuplicateDefinition(info.decl.name.clone()));
}
if !info.decl.linkage.is_definable() {
return Err(ModuleError::InvalidImportDefinition(info.decl.name.clone()));
}
Some(self.backend.define_data(
data,
&info.decl.name,
info.decl.writable,
info.decl.align,
data_ctx,
&ModuleNamespace::<B> {
contents: &self.contents,
},
)?)
};
self.contents.data_objects[data].compiled = compiled;
self.data_objects_to_finalize.push(data);
Ok(())
}
pub fn write_data_funcaddr(&mut self, data: DataId, offset: usize, what: ir::FuncRef) {
let info = &mut self.contents.data_objects[data];
debug_assert!(
info.decl.linkage.is_definable(),
"imported data cannot contain references"
);
self.backend.write_data_funcaddr(
&mut info
.compiled
.as_mut()
.expect("`data` must refer to a defined data object"),
offset,
what,
);
}
pub fn write_data_dataaddr(
&mut self,
data: DataId,
offset: usize,
what: ir::GlobalValue,
addend: binemit::Addend,
) {
let info = &mut self.contents.data_objects[data];
debug_assert!(
info.decl.linkage.is_definable(),
"imported data cannot contain references"
);
self.backend.write_data_dataaddr(
&mut info
.compiled
.as_mut()
.expect("`data` must refer to a defined data object"),
offset,
what,
addend,
);
}
pub fn finalize_definitions(&mut self) {
for func in self.functions_to_finalize.drain(..) {
let info = &self.contents.functions[func];
debug_assert!(info.decl.linkage.is_definable());
self.backend.finalize_function(
func,
info.compiled
.as_ref()
.expect("function must be compiled before it can be finalized"),
&ModuleNamespace::<B> {
contents: &self.contents,
},
);
}
for data in self.data_objects_to_finalize.drain(..) {
let info = &self.contents.data_objects[data];
debug_assert!(info.decl.linkage.is_definable());
self.backend.finalize_data(
data,
info.compiled
.as_ref()
.expect("data object must be compiled before it can be finalized"),
&ModuleNamespace::<B> {
contents: &self.contents,
},
);
}
self.backend.publish();
}
pub fn get_finalized_function(&mut self, func: FuncId) -> B::FinalizedFunction {
let info = &self.contents.functions[func];
debug_assert!(
!self.functions_to_finalize.iter().any(|x| *x == func),
"function not yet finalized"
);
self.backend.get_finalized_function(
info.compiled
.as_ref()
.expect("function must be compiled before it can be finalized"),
)
}
pub fn get_finalized_data(&mut self, data: DataId) -> B::FinalizedData {
let info = &self.contents.data_objects[data];
debug_assert!(
!self.data_objects_to_finalize.iter().any(|x| *x == data),
"data object not yet finalized"
);
self.backend.get_finalized_data(
info.compiled
.as_ref()
.expect("data object must be compiled before it can be finalized"),
)
}
pub fn isa(&self) -> &dyn isa::TargetIsa {
self.backend.isa()
}
pub fn finish(mut self) -> B::Product {
self.finalize_definitions();
self.backend.finish()
}
}