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,26 @@
[package]
authors = ["The Cranelift Project Developers"]
name = "cranelift-frontend"
version = "0.28.0"
description = "Cranelift IR builder helper"
license = "Apache-2.0 WITH LLVM-exception"
documentation = "https://cranelift.readthedocs.io/"
categories = ["no-std"]
repository = "https://github.com/CraneStation/cranelift"
readme = "README.md"
edition = "2018"
[dependencies]
cranelift-codegen = { path = "../cranelift-codegen", version = "0.28.0", default-features = false }
target-lexicon = { version = "0.2.0", default-features = false }
log = { version = "0.4.6", default-features = false }
hashmap_core = { version = "0.1.9", optional = true }
[features]
default = ["std"]
std = ["cranelift-codegen/std"]
core = ["hashmap_core", "cranelift-codegen/core"]
[badges]
maintenance = { status = "experimental" }
travis-ci = { repository = "CraneStation/cranelift" }

220
cranelift/frontend/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,5 @@
This crate provides a straightforward way to create a
[Cranelift](https://crates.io/crates/cranelift) IR function and fill it with
instructions translated from another language. It contains an SSA construction
module that provides convenient methods for translating non-SSA variables into
SSA Cranelift IR values via `use_var` and `def_var` calls.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,202 @@
//! Cranelift IR builder library.
//!
//! Provides a straightforward way to create a Cranelift IR function and fill it with instructions
//! corresponding to your source program written in another language.
//!
//! To get started, create an [`FunctionBuilderContext`](struct.FunctionBuilderContext.html) and
//! pass it as an argument to a [`FunctionBuilder`](struct.FunctionBuilder.html).
//!
//! # Mutable variables and Cranelift IR values
//!
//! The most interesting feature of this API is that it provides a single way to deal with all your
//! variable problems. Indeed, the [`FunctionBuilder`](struct.FunctionBuilder.html) struct has a
//! type `Variable` that should be an index of your source language variables. Then, through
//! calling the functions
//! [`declare_var`](struct.FunctionBuilder.html#method.declare_var),
//! [`def_var`](struct.FunctionBuilder.html#method.def_var) and
//! [`use_var`](struct.FunctionBuilder.html#method.use_var), the
//! [`FunctionBuilder`](struct.FunctionBuilder.html) will create for you all the Cranelift IR
//! values corresponding to your variables.
//!
//! This API has been designed to help you translate your mutable variables into
//! [`SSA`](https://en.wikipedia.org/wiki/Static_single_assignment_form) form.
//! [`use_var`](struct.FunctionBuilder.html#method.use_var) will returns the Cranelift IR value
//! that corresponds to your mutable variable at a precise point in the program. However, you know
//! beforehand that one of your variables is defined only once, for instance if it is the result
//! of an intermediate expression in an expression-based language, then you can translate it
//! directly by the Cranelift IR value returned by the instruction builder. Using the
//! [`use_var`](struct.FunctionBuilder.html#method.use_var) API for such an immutable variable
//! would also work but with a slight additional overhead (the SSA algorithm does not know
//! beforehand if a variable is immutable or not).
//!
//! The moral is that you should use these three functions to handle all your mutable variables,
//! even those that are not present in the source code but artefacts of the translation. It is up
//! to you to keep a mapping between the mutable variables of your language and their `Variable`
//! index that is used by Cranelift. Caution: as the `Variable` is used by Cranelift to index an
//! array containing information about your mutable variables, when you create a new `Variable`
//! with [`Variable::new(var_index)`] you should make sure that `var_index` is provided by a
//! counter incremented by 1 each time you encounter a new mutable variable.
//!
//! # Example
//!
//! Here is a pseudo-program we want to transform into Cranelift IR:
//!
//! ```clif
//! function(x) {
//! x, y, z : i32
//! block0:
//! y = 2;
//! z = x + y;
//! jump block1
//! block1:
//! z = z + y;
//! brnz y, block2;
//! z = z - x;
//! return y
//! block2:
//! y = y - x
//! jump block1
//! }
//! ```
//!
//! Here is how you build the corresponding Cranelift IR function using `FunctionBuilderContext`:
//!
//! ```rust
//! extern crate cranelift_codegen;
//! extern crate cranelift_frontend;
//!
//! use cranelift_codegen::entity::EntityRef;
//! use cranelift_codegen::ir::types::*;
//! use cranelift_codegen::ir::{AbiParam, ExternalName, Function, InstBuilder, Signature};
//! use cranelift_codegen::isa::CallConv;
//! use cranelift_codegen::settings;
//! use cranelift_codegen::verifier::verify_function;
//! use cranelift_frontend::{FunctionBuilder, FunctionBuilderContext, Variable};
//!
//! fn main() {
//! let mut sig = Signature::new(CallConv::SystemV);
//! sig.returns.push(AbiParam::new(I32));
//! sig.params.push(AbiParam::new(I32));
//! let mut fn_builder_ctx = FunctionBuilderContext::new();
//! let mut func = Function::with_name_signature(ExternalName::user(0, 0), sig);
//! {
//! let mut builder = FunctionBuilder::new(&mut func, &mut fn_builder_ctx);
//!
//! let block0 = builder.create_ebb();
//! let block1 = builder.create_ebb();
//! let block2 = builder.create_ebb();
//! let x = Variable::new(0);
//! let y = Variable::new(1);
//! let z = Variable::new(2);
//! builder.declare_var(x, I32);
//! builder.declare_var(y, I32);
//! builder.declare_var(z, I32);
//! builder.append_ebb_params_for_function_params(block0);
//!
//! builder.switch_to_block(block0);
//! builder.seal_block(block0);
//! {
//! let tmp = builder.ebb_params(block0)[0]; // the first function parameter
//! builder.def_var(x, tmp);
//! }
//! {
//! let tmp = builder.ins().iconst(I32, 2);
//! builder.def_var(y, tmp);
//! }
//! {
//! let arg1 = builder.use_var(x);
//! let arg2 = builder.use_var(y);
//! let tmp = builder.ins().iadd(arg1, arg2);
//! builder.def_var(z, tmp);
//! }
//! builder.ins().jump(block1, &[]);
//!
//! builder.switch_to_block(block1);
//! {
//! let arg1 = builder.use_var(y);
//! let arg2 = builder.use_var(z);
//! let tmp = builder.ins().iadd(arg1, arg2);
//! builder.def_var(z, tmp);
//! }
//! {
//! let arg = builder.use_var(y);
//! builder.ins().brnz(arg, block2, &[]);
//! }
//! {
//! let arg1 = builder.use_var(z);
//! let arg2 = builder.use_var(x);
//! let tmp = builder.ins().isub(arg1, arg2);
//! builder.def_var(z, tmp);
//! }
//! {
//! let arg = builder.use_var(y);
//! builder.ins().return_(&[arg]);
//! }
//!
//! builder.switch_to_block(block2);
//! builder.seal_block(block2);
//!
//! {
//! let arg1 = builder.use_var(y);
//! let arg2 = builder.use_var(x);
//! let tmp = builder.ins().isub(arg1, arg2);
//! builder.def_var(y, tmp);
//! }
//! builder.ins().jump(block1, &[]);
//! builder.seal_block(block1);
//!
//! builder.finalize();
//! }
//!
//! let flags = settings::Flags::new(settings::builder());
//! let res = verify_function(&func, &flags);
//! println!("{}", func.display(None));
//! if let Err(errors) = res {
//! panic!("{}", errors);
//! }
//! }
//! ```
#![deny(missing_docs, trivial_numeric_casts, unused_extern_crates)]
#![warn(unused_import_braces)]
#![cfg_attr(feature = "std", deny(unstable_features))]
#![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::HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
pub use crate::frontend::{FunctionBuilder, FunctionBuilderContext};
pub use crate::switch::Switch;
pub use crate::variable::Variable;
mod frontend;
mod ssa;
mod switch;
mod variable;
/// Version number of this crate.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,366 @@
use super::HashMap;
use crate::frontend::FunctionBuilder;
use cranelift_codegen::ir::condcodes::IntCC;
use cranelift_codegen::ir::*;
use log::debug;
use std::vec::Vec;
type EntryIndex = u64;
/// Unlike with `br_table`, `Switch` cases may be sparse or non-0-based.
/// They emit efficient code using branches, jump tables, or a combination of both.
#[derive(Debug, Default)]
pub struct Switch {
cases: HashMap<EntryIndex, Ebb>,
}
impl Switch {
/// Create a new empty switch
pub fn new() -> Self {
Self {
cases: HashMap::new(),
}
}
/// Set a switch entry
pub fn set_entry(&mut self, index: EntryIndex, ebb: Ebb) {
let prev = self.cases.insert(index, ebb);
assert!(
prev.is_none(),
"Tried to set the same entry {} twice",
index
);
}
fn collect_contiguous_case_ranges(self) -> Vec<ContiguousCaseRange> {
debug!("build_contiguous_case_ranges before: {:#?}", self.cases);
let mut cases = self.cases.into_iter().collect::<Vec<(_, _)>>();
cases.sort_by_key(|&(index, _)| index);
let mut contiguous_case_ranges: Vec<ContiguousCaseRange> = vec![];
let mut last_index = None;
for (index, ebb) in cases {
match last_index {
None => contiguous_case_ranges.push(ContiguousCaseRange::new(index)),
Some(last_index) => {
if index > last_index + 1 {
contiguous_case_ranges.push(ContiguousCaseRange::new(index));
}
}
}
contiguous_case_ranges.last_mut().unwrap().ebbs.push(ebb);
last_index = Some(index);
}
debug!(
"build_contiguous_case_ranges after: {:#?}",
contiguous_case_ranges
);
contiguous_case_ranges
}
fn build_search_tree(
bx: &mut FunctionBuilder,
val: Value,
otherwise: Ebb,
contiguous_case_ranges: Vec<ContiguousCaseRange>,
) -> Vec<(EntryIndex, Ebb, Vec<Ebb>)> {
let mut cases_and_jt_ebbs = Vec::new();
// Avoid allocation in the common case
if contiguous_case_ranges.len() <= 3 {
Self::build_search_branches(
bx,
val,
otherwise,
contiguous_case_ranges,
&mut cases_and_jt_ebbs,
);
return cases_and_jt_ebbs;
}
let mut stack: Vec<(Option<Ebb>, Vec<ContiguousCaseRange>)> = Vec::new();
stack.push((None, contiguous_case_ranges));
while let Some((ebb, contiguous_case_ranges)) = stack.pop() {
if let Some(ebb) = ebb {
bx.switch_to_block(ebb);
}
if contiguous_case_ranges.len() <= 3 {
Self::build_search_branches(
bx,
val,
otherwise,
contiguous_case_ranges,
&mut cases_and_jt_ebbs,
);
} else {
let split_point = contiguous_case_ranges.len() / 2;
let mut left = contiguous_case_ranges;
let right = left.split_off(split_point);
let left_ebb = bx.create_ebb();
let right_ebb = bx.create_ebb();
let should_take_right_side = bx.ins().icmp_imm(
IntCC::UnsignedGreaterThanOrEqual,
val,
right[0].first_index as i64,
);
bx.ins().brnz(should_take_right_side, right_ebb, &[]);
bx.ins().jump(left_ebb, &[]);
stack.push((Some(left_ebb), left));
stack.push((Some(right_ebb), right));
}
}
cases_and_jt_ebbs
}
fn build_search_branches(
bx: &mut FunctionBuilder,
val: Value,
otherwise: Ebb,
contiguous_case_ranges: Vec<ContiguousCaseRange>,
cases_and_jt_ebbs: &mut Vec<(EntryIndex, Ebb, Vec<Ebb>)>,
) {
for ContiguousCaseRange { first_index, ebbs } in contiguous_case_ranges.into_iter().rev() {
if ebbs.len() == 1 {
let is_good_val = bx.ins().icmp_imm(IntCC::Equal, val, first_index as i64);
bx.ins().brnz(is_good_val, ebbs[0], &[]);
} else {
let jt_ebb = bx.create_ebb();
let is_good_val =
bx.ins()
.icmp_imm(IntCC::UnsignedGreaterThanOrEqual, val, first_index as i64);
bx.ins().brnz(is_good_val, jt_ebb, &[]);
cases_and_jt_ebbs.push((first_index, jt_ebb, ebbs));
}
}
bx.ins().jump(otherwise, &[]);
}
fn build_jump_tables(
bx: &mut FunctionBuilder,
val: Value,
otherwise: Ebb,
cases_and_jt_ebbs: Vec<(EntryIndex, Ebb, Vec<Ebb>)>,
) {
for (first_index, jt_ebb, ebbs) in cases_and_jt_ebbs.into_iter().rev() {
let mut jt_data = JumpTableData::new();
for ebb in ebbs {
jt_data.push_entry(ebb);
}
let jump_table = bx.create_jump_table(jt_data);
bx.switch_to_block(jt_ebb);
let discr = bx.ins().iadd_imm(val, (first_index as i64).wrapping_neg());
bx.ins().br_table(discr, otherwise, jump_table);
}
}
/// Build the switch
///
/// # Arguments
///
/// * The function builder to emit to
/// * The value to switch on
/// * The default ebb
pub fn emit(self, bx: &mut FunctionBuilder, val: Value, otherwise: Ebb) {
// FIXME icmp(_imm) doesn't have encodings for i8 and i16 on x86(_64) yet
let val = match bx.func.dfg.value_type(val) {
types::I8 | types::I16 => bx.ins().uextend(types::I32, val),
_ => val,
};
let contiguous_case_ranges = self.collect_contiguous_case_ranges();
let cases_and_jt_ebbs = Self::build_search_tree(bx, val, otherwise, contiguous_case_ranges);
Self::build_jump_tables(bx, val, otherwise, cases_and_jt_ebbs);
}
}
#[derive(Debug)]
struct ContiguousCaseRange {
first_index: EntryIndex,
ebbs: Vec<Ebb>,
}
impl ContiguousCaseRange {
fn new(first_index: EntryIndex) -> Self {
Self {
first_index,
ebbs: Vec::new(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::frontend::FunctionBuilderContext;
use cranelift_codegen::ir::Function;
use std::string::ToString;
macro_rules! setup {
($default:expr, [$($index:expr,)*]) => {{
let mut func = Function::new();
let mut func_ctx = FunctionBuilderContext::new();
{
let mut bx = FunctionBuilder::new(&mut func, &mut func_ctx);
let ebb = bx.create_ebb();
bx.switch_to_block(ebb);
let val = bx.ins().iconst(types::I8, 0);
let mut switch = Switch::new();
$(
let ebb = bx.create_ebb();
switch.set_entry($index, ebb);
)*
switch.emit(&mut bx, val, Ebb::with_number($default).unwrap());
}
func
.to_string()
.trim_start_matches("function u0:0() fast {\n")
.trim_end_matches("\n}\n")
.to_string()
}};
}
#[test]
fn switch_zero() {
let func = setup!(0, [0,]);
assert_eq!(
func,
"ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm eq v1, 0
brnz v2, ebb1
jump ebb0"
);
}
#[test]
fn switch_single() {
let func = setup!(0, [1,]);
assert_eq!(
func,
"ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm eq v1, 1
brnz v2, ebb1
jump ebb0"
);
}
#[test]
fn switch_bool() {
let func = setup!(0, [0, 1,]);
assert_eq!(
func,
" jt0 = jump_table [ebb1, ebb2]
ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm uge v1, 0
brnz v2, ebb3
jump ebb0
ebb3:
v3 = iadd_imm.i32 v1, 0
br_table v3, ebb0, jt0"
);
}
#[test]
fn switch_two_gap() {
let func = setup!(0, [0, 2,]);
assert_eq!(
func,
"ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm eq v1, 2
brnz v2, ebb2
v3 = icmp_imm eq v1, 0
brnz v3, ebb1
jump ebb0"
);
}
#[test]
fn switch_many() {
let func = setup!(0, [0, 1, 5, 7, 10, 11, 12,]);
assert_eq!(
func,
" jt0 = jump_table [ebb1, ebb2]
jt1 = jump_table [ebb5, ebb6, ebb7]
ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm uge v1, 7
brnz v2, ebb9
jump ebb8
ebb9:
v3 = icmp_imm.i32 uge v1, 10
brnz v3, ebb10
v4 = icmp_imm.i32 eq v1, 7
brnz v4, ebb4
jump ebb0
ebb8:
v5 = icmp_imm.i32 eq v1, 5
brnz v5, ebb3
v6 = icmp_imm.i32 uge v1, 0
brnz v6, ebb11
jump ebb0
ebb11:
v7 = iadd_imm.i32 v1, 0
br_table v7, ebb0, jt0
ebb10:
v8 = iadd_imm.i32 v1, -10
br_table v8, ebb0, jt1"
);
}
#[test]
fn switch_min_index_value() {
let func = setup!(0, [::core::i64::MIN as u64, 1,]);
assert_eq!(
func,
"ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm eq v1, 0x8000_0000_0000_0000
brnz v2, ebb1
v3 = icmp_imm eq v1, 1
brnz v3, ebb2
jump ebb0"
);
}
#[test]
fn switch_max_index_value() {
let func = setup!(0, [::core::i64::MAX as u64, 1,]);
assert_eq!(
func,
"ebb0:
v0 = iconst.i8 0
v1 = uextend.i32 v0
v2 = icmp_imm eq v1, 0x7fff_ffff_ffff_ffff
brnz v2, ebb1
v3 = icmp_imm eq v1, 1
brnz v3, ebb2
jump ebb0"
)
}
}

View File

@@ -0,0 +1,32 @@
//! A basic `Variable` implementation.
//!
//! `FunctionBuilderContext`, `FunctionBuilder`, and related types have a `Variable`
//! type parameter, to allow frontends that identify variables with
//! their own index types to use them directly. Frontends which don't
//! can use the `Variable` defined here.
use core::u32;
use cranelift_codegen::entity::EntityRef;
///! An opaque reference to a variable.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct Variable(u32);
impl Variable {
/// Create a new Variable with the given index.
pub fn with_u32(index: u32) -> Self {
debug_assert!(index < u32::MAX);
Variable(index)
}
}
impl EntityRef for Variable {
fn new(index: usize) -> Self {
debug_assert!(index < (u32::MAX as usize));
Variable(index as u32)
}
fn index(self) -> usize {
self.0 as usize
}
}