moved crates in lib/ to src/, renamed crates, modified some files' text (#660)

moved crates in lib/ to src/, renamed crates, modified some files' text (#660)
This commit is contained in:
lazypassion
2019-01-28 18:56:54 -05:00
committed by Dan Gohman
parent 54959cf5bb
commit 747ad3c4c5
508 changed files with 94 additions and 92 deletions

View File

@@ -0,0 +1,27 @@
[package]
name = "cranelift-module"
version = "0.28.0"
authors = ["The Cranelift Project Developers"]
description = "Support for linking functions and data with Cranelift"
repository = "https://github.com/CraneStation/cranelift"
documentation = "https://cranelift.readthedocs.io/"
categories = ["no-std"]
license = "Apache-2.0 WITH LLVM-exception"
readme = "README.md"
edition = "2018"
[dependencies]
cranelift-codegen = { path = "../cranelift-codegen", version = "0.28.0", default-features = false }
cranelift-entity = { path = "../cranelift-entity", version = "0.28.0", default-features = false }
hashmap_core = { version = "0.1.9", optional = true }
failure = { version = "0.1.1", default-features = false }
log = { version = "0.4.6", default-features = false }
[features]
default = ["std"]
std = ["cranelift-codegen/std", "cranelift-entity/std"]
core = ["hashmap_core", "cranelift-codegen/core"]
[badges]
maintenance = { status = "experimental" }
travis-ci = { repository = "CraneStation/cranelift" }

220
cranelift/module/LICENSE Normal file
View File

@@ -0,0 +1,220 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--- LLVM Exceptions to the Apache 2.0 License ----
As an exception, if, as a result of your compiling your source code, portions
of this Software are embedded into an Object form of such source code, you
may redistribute such embedded portions in such Object form without complying
with the conditions of Sections 4(a), 4(b) and 4(d) of the License.
In addition, if you combine or link compiled forms of this Software with
software that is licensed under the GPLv2 ("Combined Software") and if a
court of competent jurisdiction determines that the patent provision (Section
3), the indemnity provision (Section 9) or other Section of the License
conflicts with the conditions of the GPLv2, you may retroactively and
prospectively choose to deem waived or otherwise exclude such Section(s) of
the License, but only in their entirety and only with respect to the Combined
Software.

View File

@@ -0,0 +1,20 @@
This crate provides module-level functionality, which allow multiple
functions and data to be emitted with
[Cranelift](https://crates.io/crates/cranelift) and then linked together.
This crate is structured as an optional layer on top of cranelift-codegen.
It provides additional functionality, such as linking, however users that
require greater flexibility don't need to use it.
A `Module` is a collection of functions and data objects that are linked
together. `Backend` is a trait that defines an interface for backends
that compile modules into various forms. Most users will use one of the
following `Backend` implementations:
- `SimpleJITBackend`, provided by [cranelift-simplejit], which JITs
code to memory for direct execution.
- `FaerieBackend`, provided by [cranelift-faerie], which emits native
object files.
[cranelift-simplejit]: https://crates.io/crates/cranelift-simplejit
[cranelift-faerie]: https://crates.io/crates/cranelift-faerie

View File

@@ -0,0 +1,129 @@
//! Defines the `Backend` trait.
use crate::DataContext;
use crate::Linkage;
use crate::ModuleNamespace;
use crate::ModuleResult;
use core::marker;
use cranelift_codegen::isa::TargetIsa;
use cranelift_codegen::Context;
use cranelift_codegen::{binemit, ir};
/// A `Backend` implements the functionality needed to support a `Module`.
///
/// Two notable implementations of this trait are:
/// - `SimpleJITBackend`, defined in [cranelift-simplejit], which JITs
/// the contents of a `Module` to memory which can be directly executed.
/// - `FaerieBackend`, defined in [cranelift-faerie], which writes the
/// contents of a `Module` out as a native object file.
///
/// [cranelift-simplejit]: https://docs.rs/cranelift-simplejit/
/// [cranelift-faerie]: https://docs.rs/cranelift-faerie/
pub trait Backend
where
Self: marker::Sized,
{
/// A builder for constructing `Backend` instances.
type Builder;
/// The results of compiling a function.
type CompiledFunction;
/// The results of "compiling" a data object.
type CompiledData;
/// The completed output artifact for a function, if this is meaningful for
/// the `Backend`.
type FinalizedFunction;
/// The completed output artifact for a data object, if this is meaningful for
/// the `Backend`.
type FinalizedData;
/// This is an object returned by `Module`'s
/// [`finish`](struct.Module.html#method.finish) function,
/// if the `Backend` has a purpose for this.
type Product;
/// Create a new `Backend` instance.
fn new(_: Self::Builder) -> Self;
/// Return the `TargetIsa` to compile for.
fn isa(&self) -> &TargetIsa;
/// Declare a function.
fn declare_function(&mut self, name: &str, linkage: Linkage);
/// Declare a data object.
fn declare_data(&mut self, name: &str, linkage: Linkage, writable: bool);
/// Define a function, producing the function body from the given `Context`.
///
/// Functions must be declared before being defined.
fn define_function(
&mut self,
name: &str,
ctx: &Context,
namespace: &ModuleNamespace<Self>,
code_size: u32,
) -> ModuleResult<Self::CompiledFunction>;
/// Define a zero-initialized data object of the given size.
///
/// Data objects must be declared before being defined.
fn define_data(
&mut self,
name: &str,
writable: bool,
data_ctx: &DataContext,
namespace: &ModuleNamespace<Self>,
) -> ModuleResult<Self::CompiledData>;
/// Write the address of `what` into the data for `data` at `offset`. `data` must refer to a
/// defined data object.
fn write_data_funcaddr(
&mut self,
data: &mut Self::CompiledData,
offset: usize,
what: ir::FuncRef,
);
/// Write the address of `what` plus `addend` into the data for `data` at `offset`. `data` must
/// refer to a defined data object.
fn write_data_dataaddr(
&mut self,
data: &mut Self::CompiledData,
offset: usize,
what: ir::GlobalValue,
addend: binemit::Addend,
);
/// Perform all outstanding relocations on the given function. This requires all `Local`
/// and `Export` entities referenced to be defined.
fn finalize_function(
&mut self,
func: &Self::CompiledFunction,
namespace: &ModuleNamespace<Self>,
) -> Self::FinalizedFunction;
/// Return the finalized artifact from the backend, if relevant.
fn get_finalized_function(&self, func: &Self::CompiledFunction) -> Self::FinalizedFunction;
/// Perform all outstanding relocations on the given data object. This requires all
/// `Local` and `Export` entities referenced to be defined.
fn finalize_data(
&mut self,
data: &Self::CompiledData,
namespace: &ModuleNamespace<Self>,
) -> Self::FinalizedData;
/// Return the finalized artifact from the backend, if relevant.
fn get_finalized_data(&self, data: &Self::CompiledData) -> Self::FinalizedData;
/// "Publish" all finalized functions and data objects to their ultimate destinations.
fn publish(&mut self);
/// Consume this `Backend` and return a result. Some implementations may
/// provide additional functionality through this result.
fn finish(self) -> Self::Product;
}

View File

@@ -0,0 +1,198 @@
//! Defines `DataContext`.
use cranelift_codegen::binemit::{Addend, CodeOffset};
use cranelift_codegen::entity::PrimaryMap;
use cranelift_codegen::ir;
use std::boxed::Box;
use std::vec::Vec;
/// This specifies how data is to be initialized.
#[derive(PartialEq, Eq, Debug)]
pub enum Init {
/// This indicates that no initialization has been specified yet.
Uninitialized,
/// Initialize the data with all zeros.
Zeros {
/// The size of the data.
size: usize,
},
/// Initialize the data with the specified contents.
Bytes {
/// The contents, which also implies the size of the data.
contents: Box<[u8]>,
},
}
impl Init {
/// Return the size of the data to be initialized.
pub fn size(&self) -> usize {
match *self {
Init::Uninitialized => panic!("data size not initialized yet"),
Init::Zeros { size } => size,
Init::Bytes { ref contents } => contents.len(),
}
}
}
/// A description of a data object.
pub struct DataDescription {
/// How the data should be initialized.
pub init: Init,
/// External function declarations.
pub function_decls: PrimaryMap<ir::FuncRef, ir::ExternalName>,
/// External data object declarations.
pub data_decls: PrimaryMap<ir::GlobalValue, ir::ExternalName>,
/// Function addresses to write at specified offsets.
pub function_relocs: Vec<(CodeOffset, ir::FuncRef)>,
/// Data addresses to write at specified offsets.
pub data_relocs: Vec<(CodeOffset, ir::GlobalValue, Addend)>,
}
/// This is to data objects what cranelift_codegen::Context is to functions.
pub struct DataContext {
description: DataDescription,
}
impl DataContext {
/// Allocate a new context.
pub fn new() -> Self {
Self {
description: DataDescription {
init: Init::Uninitialized,
function_decls: PrimaryMap::new(),
data_decls: PrimaryMap::new(),
function_relocs: vec![],
data_relocs: vec![],
},
}
}
/// Clear all data structures in this context.
pub fn clear(&mut self) {
self.description.init = Init::Uninitialized;
self.description.function_decls.clear();
self.description.data_decls.clear();
self.description.function_relocs.clear();
self.description.data_relocs.clear();
}
/// Define a zero-initialized object with the given size.
pub fn define_zeroinit(&mut self, size: usize) {
debug_assert_eq!(self.description.init, Init::Uninitialized);
self.description.init = Init::Zeros { size };
}
/// Define an object initialized with the given contents.
///
/// TODO: Can we avoid a Box here?
pub fn define(&mut self, contents: Box<[u8]>) {
debug_assert_eq!(self.description.init, Init::Uninitialized);
self.description.init = Init::Bytes { contents };
}
/// Declare an external function import.
///
/// Users of the `Module` API generally should call
/// `Module::declare_func_in_data` instead, as it takes care of generating
/// the appropriate `ExternalName`.
pub fn import_function(&mut self, name: ir::ExternalName) -> ir::FuncRef {
self.description.function_decls.push(name)
}
/// Declares a global value import.
///
/// TODO: Rename to import_data?
///
/// Users of the `Module` API generally should call
/// `Module::declare_data_in_data` instead, as it takes care of generating
/// the appropriate `ExternalName`.
pub fn import_global_value(&mut self, name: ir::ExternalName) -> ir::GlobalValue {
self.description.data_decls.push(name)
}
/// Write the address of `func` into the data at offset `offset`.
pub fn write_function_addr(&mut self, offset: CodeOffset, func: ir::FuncRef) {
self.description.function_relocs.push((offset, func))
}
/// Write the address of `data` into the data at offset `offset`.
pub fn write_data_addr(&mut self, offset: CodeOffset, data: ir::GlobalValue, addend: Addend) {
self.description.data_relocs.push((offset, data, addend))
}
/// Reference the initializer data.
pub fn description(&self) -> &DataDescription {
debug_assert!(
self.description.init != Init::Uninitialized,
"data must be initialized first"
);
&self.description
}
}
#[cfg(test)]
mod tests {
use super::{DataContext, Init};
use cranelift_codegen::ir;
#[test]
fn basic_data_context() {
let mut data_ctx = DataContext::new();
{
let description = &data_ctx.description;
assert_eq!(description.init, Init::Uninitialized);
assert!(description.function_decls.is_empty());
assert!(description.data_decls.is_empty());
assert!(description.function_relocs.is_empty());
assert!(description.data_relocs.is_empty());
}
data_ctx.define_zeroinit(256);
let _func_a = data_ctx.import_function(ir::ExternalName::user(0, 0));
let func_b = data_ctx.import_function(ir::ExternalName::user(0, 1));
let func_c = data_ctx.import_function(ir::ExternalName::user(1, 0));
let _data_a = data_ctx.import_global_value(ir::ExternalName::user(2, 2));
let data_b = data_ctx.import_global_value(ir::ExternalName::user(2, 3));
data_ctx.write_function_addr(8, func_b);
data_ctx.write_function_addr(16, func_c);
data_ctx.write_data_addr(32, data_b, 27);
{
let description = data_ctx.description();
assert_eq!(description.init, Init::Zeros { size: 256 });
assert_eq!(description.function_decls.len(), 3);
assert_eq!(description.data_decls.len(), 2);
assert_eq!(description.function_relocs.len(), 2);
assert_eq!(description.data_relocs.len(), 1);
}
data_ctx.clear();
{
let description = &data_ctx.description;
assert_eq!(description.init, Init::Uninitialized);
assert!(description.function_decls.is_empty());
assert!(description.data_decls.is_empty());
assert!(description.function_relocs.is_empty());
assert!(description.data_relocs.is_empty());
}
let contents = vec![33, 34, 35, 36];
let contents_clone = contents.clone();
data_ctx.define(contents.into_boxed_slice());
{
let description = data_ctx.description();
assert_eq!(
description.init,
Init::Bytes {
contents: contents_clone.into_boxed_slice()
}
);
assert_eq!(description.function_decls.len(), 0);
assert_eq!(description.data_decls.len(), 0);
assert_eq!(description.function_relocs.len(), 0);
assert_eq!(description.data_relocs.len(), 0);
}
}
}

View File

@@ -0,0 +1,47 @@
//! Top-level lib.rs for `cranelift_module`.
#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)]
#![warn(unused_import_braces)]
#![cfg_attr(feature = "std", deny(unstable_features))]
#![cfg_attr(feature = "clippy", plugin(clippy(conf_file = "../../clippy.toml")))]
#![cfg_attr(feature = "cargo-clippy", allow(clippy::new_without_default))]
#![cfg_attr(
feature = "cargo-clippy",
warn(
clippy::float_arithmetic,
clippy::mut_mut,
clippy::nonminimal_bool,
clippy::option_map_unwrap_or,
clippy::option_map_unwrap_or_else,
clippy::print_stdout,
clippy::unicode_not_nfc,
clippy::use_self
)
)]
#![no_std]
#![cfg_attr(not(feature = "std"), feature(alloc))]
#[cfg(not(feature = "std"))]
#[macro_use]
extern crate alloc as std;
#[cfg(feature = "std")]
#[macro_use]
extern crate std;
#[cfg(not(feature = "std"))]
use hashmap_core::{map as hash_map, HashMap};
#[cfg(feature = "std")]
use std::collections::{hash_map, HashMap};
mod backend;
mod data_context;
mod module;
pub use crate::backend::Backend;
pub use crate::data_context::{DataContext, DataDescription, Init};
pub use crate::module::{
DataId, FuncId, FuncOrDataId, Linkage, Module, ModuleError, ModuleNamespace, ModuleResult,
};
/// Version number of this crate.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

View File

@@ -0,0 +1,688 @@
//! Defines `Module` and related types.
// TODO: Should `ir::Function` really have a `name`?
// TODO: Factor out `ir::Function`'s `ext_funcs` and `global_values` into a struct
// shared with `DataContext`?
use super::HashMap;
use crate::data_context::DataContext;
use crate::Backend;
use cranelift_codegen::entity::{entity_impl, PrimaryMap};
use cranelift_codegen::{binemit, ir, isa, CodegenError, Context};
use failure::Fail;
use log::info;
use std::borrow::ToOwned;
use std::string::String;
use std::vec::Vec;
/// A function identifier for use in the `Module` interface.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FuncId(u32);
entity_impl!(FuncId, "funcid");
/// Function identifiers are namespace 0 in `ir::ExternalName`
impl From<FuncId> for ir::ExternalName {
fn from(id: FuncId) -> Self {
ir::ExternalName::User {
namespace: 0,
index: id.0,
}
}
}
/// A data object identifier for use in the `Module` interface.
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct DataId(u32);
entity_impl!(DataId, "dataid");
/// Data identifiers are namespace 1 in `ir::ExternalName`
impl From<DataId> for ir::ExternalName {
fn from(id: DataId) -> Self {
ir::ExternalName::User {
namespace: 1,
index: id.0,
}
}
}
/// Linkage refers to where an entity is defined and who can see it.
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum Linkage {
/// Defined outside of a module.
Import,
/// Defined inside the module, but not visible outside it.
Local,
/// Defined inside the module, visible outside it, and may be preempted.
Preemptible,
/// Defined inside the module, and visible outside it.
Export,
}
impl Linkage {
fn merge(a: Self, b: Self) -> Self {
match a {
Linkage::Export => Linkage::Export,
Linkage::Preemptible => match b {
Linkage::Export => Linkage::Export,
_ => Linkage::Preemptible,
},
Linkage::Local => match b {
Linkage::Export => Linkage::Export,
Linkage::Preemptible => Linkage::Preemptible,
_ => Linkage::Local,
},
Linkage::Import => b,
}
}
/// Test whether this linkage can have a definition.
pub fn is_definable(self) -> bool {
match self {
Linkage::Import => false,
Linkage::Local | Linkage::Preemptible | Linkage::Export => true,
}
}
/// Test whether this linkage will have a definition that cannot be preempted.
pub fn is_final(self) -> bool {
match self {
Linkage::Import | Linkage::Preemptible => false,
Linkage::Local | Linkage::Export => true,
}
}
}
/// A declared name may refer to either a function or data declaration
#[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
pub enum FuncOrDataId {
/// When it's a FuncId
Func(FuncId),
/// When it's a DataId
Data(DataId),
}
/// Mapping to `ir::ExternalName` is trivial based on the `FuncId` and `DataId` mapping.
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),
}
}
}
/// Information about a function which can be called.
pub struct FunctionDeclaration {
pub name: String,
pub linkage: Linkage,
pub signature: ir::Signature,
}
/// Error messages for all `Module` and `Backend` methods
#[derive(Fail, Debug)]
pub enum ModuleError {
/// Indicates an identifier was used before it was declared
#[fail(display = "Undeclared identifier: {}", _0)]
Undeclared(String),
/// Indicates an identifier was used as data/function first, but then used as the other
#[fail(display = "Incompatible declaration of identifier: {}", _0)]
IncompatibleDeclaration(String),
/// Indicates a function identifier was declared with a
/// different signature than declared previously
#[fail(
display = "Function {} signature {:?} is incompatible with previous declaration {:?}",
_0, _2, _1
)]
IncompatibleSignature(String, ir::Signature, ir::Signature),
/// Indicates an identifier was defined more than once
#[fail(display = "Duplicate definition of identifier: {}", _0)]
DuplicateDefinition(String),
/// Indicates an identifier was defined, but was declared as an import
#[fail(display = "Invalid to define identifier declared as an import: {}", _0)]
InvalidImportDefinition(String),
/// Wraps a `cranelift-codegen` error
#[fail(display = "Compilation error: {}", _0)]
Compilation(CodegenError),
/// Wraps a generic error from a backend
#[fail(display = "Backend error: {}", _0)]
Backend(String),
}
/// A convenient alias for a `Result` that uses `ModuleError` as the error type.
pub type ModuleResult<T> = Result<T, ModuleError>;
/// A function belonging to a `Module`.
struct ModuleFunction<B>
where
B: Backend,
{
/// The function declaration.
decl: FunctionDeclaration,
/// The compiled artifact, once it's available.
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(())
}
}
/// Information about a data object which can be accessed.
pub struct DataDeclaration {
pub name: String,
pub linkage: Linkage,
pub writable: bool,
}
/// A data object belonging to a `Module`.
struct ModuleData<B>
where
B: Backend,
{
/// The data object declaration.
decl: DataDeclaration,
/// The "compiled" artifact, once it's available.
compiled: Option<B::CompiledData>,
}
impl<B> ModuleData<B>
where
B: Backend,
{
fn merge(&mut self, linkage: Linkage, writable: bool) {
self.decl.linkage = Linkage::merge(self.decl.linkage, linkage);
self.decl.writable = self.decl.writable || writable;
}
}
/// The functions and data objects belonging to a module.
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_info(&self, name: &ir::ExternalName) -> &ModuleFunction<B> {
if let ir::ExternalName::User { namespace, index } = *name {
debug_assert_eq!(namespace, 0);
let func = FuncId::from_u32(index);
&self.functions[func]
} else {
panic!("unexpected ExternalName kind {}", name)
}
}
/// Get the `DataDeclaration` for the function named by `name`.
fn get_data_info(&self, name: &ir::ExternalName) -> &ModuleData<B> {
if let ir::ExternalName::User { namespace, index } = *name {
debug_assert_eq!(namespace, 1);
let data = DataId::from_u32(index);
&self.data_objects[data]
} else {
panic!("unexpected ExternalName kind {}", name)
}
}
}
/// This provides a view to the state of a module which allows `ir::ExternalName`s to be translated
/// into `FunctionDeclaration`s and `DataDeclaration`s.
pub struct ModuleNamespace<'a, B: 'a>
where
B: Backend,
{
contents: &'a ModuleContents<B>,
}
impl<'a, B> ModuleNamespace<'a, B>
where
B: Backend,
{
/// Get the `FunctionDeclaration` for the function named by `name`.
pub fn get_function_decl(&self, name: &ir::ExternalName) -> &FunctionDeclaration {
&self.contents.get_function_info(name).decl
}
/// Get the `DataDeclaration` for the function named by `name`.
pub fn get_data_decl(&self, name: &ir::ExternalName) -> &DataDeclaration {
&self.contents.get_data_info(name).decl
}
/// Get the definition for the function named by `name`, along with its name
/// and signature.
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,
)
}
/// Get the definition for the data object named by `name`, along with its name
/// and writable flag
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)
}
/// Return whether `name` names a function, rather than a data object.
pub fn is_function(&self, name: &ir::ExternalName) -> bool {
if let ir::ExternalName::User { namespace, .. } = *name {
namespace == 0
} else {
panic!("unexpected ExternalName kind {}", name)
}
}
}
/// A `Module` is a utility for collecting functions and data objects, and linking them together.
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,
{
/// Create a new `Module`.
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),
}
}
/// Get the module identifier for a given name, if that name
/// has been declared.
pub fn get_name(&self, name: &str) -> Option<FuncOrDataId> {
self.names.get(name).cloned()
}
/// Return the target information needed by frontends to produce Cranelift IR
/// for the current target.
pub fn target_config(&self) -> isa::TargetFrontendConfig {
self.backend.isa().frontend_config()
}
/// Create a new `Context` initialized for use with this `Module`.
///
/// This ensures that the `Context` is initialized with the default calling
/// convention for the `TargetIsa`.
pub fn make_context(&self) -> Context {
let mut ctx = Context::new();
ctx.func.signature.call_conv = self.backend.isa().default_call_conv();
ctx
}
/// Clear the given `Context` and reset it for use with a new function.
///
/// This ensures that the `Context` is initialized with the default calling
/// convention for the `TargetIsa`.
pub fn clear_context(&self, ctx: &mut Context) {
ctx.clear();
ctx.func.signature.call_conv = self.backend.isa().default_call_conv();
}
/// Create a new empty `Signature` with the default calling convention for
/// the `TargetIsa`, to which parameter and return types can be added for
/// declaring a function to be called by this `Module`.
pub fn make_signature(&self) -> ir::Signature {
ir::Signature::new(self.backend.isa().default_call_conv())
}
/// Clear the given `Signature` and reset for use with a new function.
///
/// This ensures that the `Signature` is initialized with the default
/// calling convention for the `TargetIsa`.
pub fn clear_signature(&self, sig: &mut ir::Signature) {
sig.clear(self.backend.isa().default_call_conv());
}
/// Declare a function in this module.
pub fn declare_function(
&mut self,
name: &str,
linkage: Linkage,
signature: &ir::Signature,
) -> ModuleResult<FuncId> {
// TODO: Can we avoid allocating names so often?
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(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(name, linkage);
Ok(id)
}
}
}
/// Declare a data object in this module.
pub fn declare_data(
&mut self,
name: &str,
linkage: Linkage,
writable: bool,
) -> ModuleResult<DataId> {
// TODO: Can we avoid allocating names so often?
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);
self.backend
.declare_data(name, existing.decl.linkage, existing.decl.writable);
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,
},
compiled: None,
});
entry.insert(FuncOrDataId::Data(id));
self.backend.declare_data(name, linkage, writable);
Ok(id)
}
}
}
/// Use this when you're building the IR of a function to reference a function.
///
/// TODO: Coalesce redundant decls and signatures.
/// TODO: Look into ways to reduce the risk of using a FuncRef in the wrong function.
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,
})
}
/// Use this when you're building the IR of a function to reference a data object.
///
/// TODO: Same as above.
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,
})
}
/// TODO: Same as above.
pub fn declare_func_in_data(&self, func: FuncId, ctx: &mut DataContext) -> ir::FuncRef {
ctx.import_function(ir::ExternalName::user(0, func.as_u32()))
}
/// TODO: Same as above.
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()))
}
/// Define a function, producing the function body from the given `Context`.
pub fn define_function(&mut self, func: FuncId, ctx: &mut Context) -> ModuleResult<()> {
self.define_function_peek_compiled(func, ctx, |_, _, _| ())
}
/// Define a function, allowing to peek at the compiled function and producing the
/// function body from the given `Context`.
pub fn define_function_peek_compiled<T>(
&mut self,
func: FuncId,
ctx: &mut Context,
peek_compiled: impl FnOnce(u32, &Context, &isa::TargetIsa) -> T,
) -> ModuleResult<T> {
let code_size;
let compiled = {
code_size = ctx.compile(self.backend.isa()).map_err(|e| {
info!(
"defining function {}: {}",
func,
ctx.func.display(self.backend.isa())
);
ModuleError::Compilation(e)
})?;
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()));
}
Some(self.backend.define_function(
&info.decl.name,
ctx,
&ModuleNamespace::<B> {
contents: &self.contents,
},
code_size,
)?)
};
self.contents.functions[func].compiled = compiled;
self.functions_to_finalize.push(func);
Ok(peek_compiled(code_size, &ctx, self.backend.isa()))
}
/// Define a function, producing the data contents from the given `DataContext`.
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(
&info.decl.name,
info.decl.writable,
data_ctx,
&ModuleNamespace::<B> {
contents: &self.contents,
},
)?)
};
self.contents.data_objects[data].compiled = compiled;
self.data_objects_to_finalize.push(data);
Ok(())
}
/// Write the address of `what` into the data for `data` at `offset`. `data` must refer to a
/// defined data object.
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,
);
}
/// Write the address of `what` plus `addend` into the data for `data` at `offset`. `data` must
/// refer to a defined data object.
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,
);
}
/// Finalize all functions and data objects that are defined but not yet finalized.
/// All symbols referenced in their bodies that are declared as needing a definition
/// must be defined by this point.
///
/// Use `get_finalized_function` and `get_finalized_data` to obtain the final
/// artifacts.
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(
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(
info.compiled
.as_ref()
.expect("data object must be compiled before it can be finalized"),
&ModuleNamespace::<B> {
contents: &self.contents,
},
);
}
self.backend.publish();
}
/// Return the finalized artifact from the backend, if it provides one.
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"),
)
}
/// Return the finalized artifact from the backend, if it provides one.
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"),
)
}
/// Consume the module and return the resulting `Product`. Some `Backend`
/// implementations may provide additional functionality available after
/// a `Module` is complete.
pub fn finish(self) -> B::Product {
self.backend.finish()
}
}