Emulate <Box<F> as FnOnce>::call_once without alloca

Fixes #884

cc #15
This commit is contained in:
bjorn3 2020-03-10 20:48:58 +01:00
parent 240d56c33c
commit dcc86d306c
5 changed files with 97 additions and 326 deletions

View File

@ -1,73 +0,0 @@
From 7403e2998345ef0650fd50628d7098d4d1e88e5c Mon Sep 17 00:00:00 2001
From: bjorn3 <bjorn3@users.noreply.github.com>
Date: Sat, 6 Apr 2019 12:16:21 +0200
Subject: [PATCH] Remove usage of unsized locals
---
src/liballoc/boxed.rs | 23 -----------------------
src/libstd/sys_common/at_exit_imp.rs | 2 ++
src/libstd/sys_common/mod.rs | 1 -
src/libstd/sys_common/thread.rs | 7 +------
4 files changed, 3 insertions(+), 30 deletions(-)
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs
index f6dee7c..0c6a8c0 100644
--- a/src/liballoc/boxed.rs
+++ b/src/liballoc/boxed.rs
@@ -694,29 +694,6 @@ impl<I: ExactSizeIterator + ?Sized> ExactSizeIterator for Box<I> {
#[stable(feature = "fused", since = "1.26.0")]
impl<I: FusedIterator + ?Sized> FusedIterator for Box<I> {}
-#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
-impl<A, F: FnOnce<A> + ?Sized> FnOnce<A> for Box<F> {
- type Output = <F as FnOnce<A>>::Output;
-
- extern "rust-call" fn call_once(self, args: A) -> Self::Output {
- <F as FnOnce<A>>::call_once(*self, args)
- }
-}
-
-#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
-impl<A, F: FnMut<A> + ?Sized> FnMut<A> for Box<F> {
- extern "rust-call" fn call_mut(&mut self, args: A) -> Self::Output {
- <F as FnMut<A>>::call_mut(self, args)
- }
-}
-
-#[stable(feature = "boxed_closure_impls", since = "1.35.0")]
-impl<A, F: Fn<A> + ?Sized> Fn<A> for Box<F> {
- extern "rust-call" fn call(&self, args: A) -> Self::Output {
- <F as Fn<A>>::call(self, args)
- }
-}
-
#[unstable(feature = "coerce_unsized", issue = "27732")]
impl<T: ?Sized + Unsize<U>, U: ?Sized> CoerceUnsized<Box<U>> for Box<T> {}
diff --git a/src/libstd/sys_common/thread.rs b/src/libstd/sys_common/thread.rs
index b2142e7..718bb1c 100644
--- a/src/libstd/sys_common/thread.rs
+++ b/src/libstd/sys_common/thread.rs
@@ -6,7 +6,7 @@ pub unsafe fn start_thread(main: *mut u8) {
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
- Box::from_raw(main as *mut Box<dyn FnOnce()>)()
+ Box::from_raw(main as *mut Box<dyn FnBox()>)()
}
pub fn min_stack() -> usize {
diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs
index f4a1783..362b537 100644
--- a/src/libstd/sys/unix/thread.rs
+++ b/src/libstd/sys/unix/thread.rs
@@ -40,5 +40,7 @@ impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
+ panic!("Warning: Threads are not yet fully supported, because cranelift doesn't support atomics.");
+
let p = box p;
let mut native: libc::pthread_t = mem::zeroed();
let mut attr: libc::pthread_attr_t = mem::zeroed();
--
2.20.1 (Apple Git-117)

View File

@ -11,24 +11,6 @@ diff --git a/src/libtest/lib.rs b/src/libtest/lib.rs
index 8b76080..9e65de2 100644
--- a/src/libtest/lib.rs
+++ b/src/libtest/lib.rs
@@ -52,7 +52,7 @@ use std::fmt;
use std::{
env, io,
io::prelude::Write,
- panic::{self, catch_unwind, AssertUnwindSafe, PanicInfo},
+ panic::{self, PanicInfo},
process::{self, Command, Termination},
sync::mpsc::{channel, Sender},
sync::{Arc, Mutex},
@@ -1493,7 +1493,7 @@ pub fn run_test(
fn run_test_inner(
desc: TestDesc,
monitor_ch: Sender<CompletedTest>,
- testfn: Box<dyn FnOnce() + Send>,
+ testfn: Box<impl FnOnce() + Send + 'static>,
opts: TestRunOpts,
) {
let concurrency = opts.concurrency;
@@ -1509,7 +1509,7 @@ pub fn run_test(
// If the platform is single-threaded we're just going to run
// the test synchronously, regardless of the concurrency
@ -38,55 +20,5 @@ index 8b76080..9e65de2 100644
if concurrency == Concurrent::Yes && supports_threads {
let cfg = thread::Builder::new().name(name.as_slice().to_owned());
cfg.spawn(runtest).unwrap();
@@ -1531,17 +1531,8 @@ pub fn run_test(
// Benchmarks aren't expected to panic, so we run them all in-process.
crate::bench::benchmark(desc, monitor_ch, opts.nocapture, benchfn);
}
- DynTestFn(f) => {
- match strategy {
- RunStrategy::InProcess => (),
- _ => panic!("Cannot run dynamic test fn out-of-process"),
- };
- run_test_inner(
- desc,
- monitor_ch,
- Box::new(move || __rust_begin_short_backtrace(f)),
- test_run_opts,
- );
+ DynTestFn(_f) => {
+ unimplemented!();
}
StaticTestFn(f) => run_test_inner(
desc,
@@ -1604,10 +1592,10 @@ fn get_result_from_exit_code(desc: &TestDesc, code: i32) -> TestResult {
fn run_test_in_process(
desc: TestDesc,
nocapture: bool,
report_time: bool,
- testfn: Box<dyn FnOnce() + Send>,
+ testfn: Box<impl FnOnce() + Send + 'static>,
monitor_ch: Sender<CompletedTest>,
time_opts: Option<time::TestTimeOptions>,
) {
// Buffer for capturing standard I/O
let data = Arc::new(Mutex::new(Vec::new()));
@@ -1623,7 +1611,7 @@ fn run_test_in_process(desc: TestDesc,
};
let start = report_time.then(Instant::now);
- let result = catch_unwind(AssertUnwindSafe(testfn));
+ let result = Ok::<(), Box<dyn std::any::Any + Send>>(testfn());
let exec_time = start.map(|start| {
let duration = start.elapsed();
TestExecTime(duration)
@@ -1688,7 +1676,7 @@ fn spawn_test_subprocess(desc: TestDesc, report_time: bool, monitor_ch: Sender<M
monitor_ch.send(message).unwrap();
}
-fn run_test_in_spawned_subprocess(desc: TestDesc, testfn: Box<dyn FnOnce() + Send>) -> ! {
+fn run_test_in_spawned_subprocess(desc: TestDesc, testfn: Box<impl FnOnce() + Send + 'static>) -> ! {
let builtin_panic_hook = panic::take_hook();
let record_result = Arc::new(move |panic_info: Option<&'_ PanicInfo<'_>>| {
let test_result = match panic_info {
--
2.20.1

View File

@ -1,174 +0,0 @@
From 8617310c3c9e192080df6a0c7b4835d3f02e27b9 Mon Sep 17 00:00:00 2001
From: bjorn3 <bjorn3@users.noreply.github.com>
Date: Fri, 1 Nov 2019 20:58:30 +0100
Subject: [PATCH] Add FnBox back
---
src/liballoc/boxed.rs | 13 +++++++++++++
src/libstd/prelude/v1.rs | 2 +-
src/libstd/sys/cloudabi/thread.rs | 2 +-
src/libstd/sys/hermit/thread.rs | 4 ++--
src/libstd/sys/unix/thread.rs | 4 ++--
src/libstd/sys_common/at_exit_imp.rs | 6 +++---
src/libstd/sys_common/mod.rs | 2 +-
src/libstd/sys_common/thread.rs | 2 +-
src/libstd/thread/mod.rs | 2 +-
9 files changed, 25 insertions(+), 12 deletions(-)
diff --git a/src/liballoc/boxed.rs b/src/liballoc/boxed.rs
index ef9b648..e32b870 100644
--- a/src/liballoc/boxed.rs
+++ b/src/liballoc/boxed.rs
@@ -1079,3 +1079,16 @@ impl<F: ?Sized + Future + Unpin> Future for Box<F> {
F::poll(Pin::new(&mut *self), cx)
}
}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+pub trait FnBox<A>: FnOnce<A> {
+ #[stable(feature = "rust1", since = "1.0.0")]
+ extern "rust-call" fn call_box(self: Box<Self>, args: A) -> Self::Output;
+}
+
+#[stable(feature = "rust1", since = "1.0.0")]
+impl<A, F: FnOnce<A>> FnBox<A> for F {
+ extern "rust-call" fn call_box(self: Box<Self>, args: A) -> Self::Output {
+ <F as FnOnce<A>>::call_once(*self, args)
+ }
+}
diff --git a/src/libstd/prelude/v1.rs b/src/libstd/prelude/v1.rs
index 3e4cf91..1f50eb3 100644
--- a/src/libstd/prelude/v1.rs
+++ b/src/libstd/prelude/v1.rs
@@ -94,6 +94,6 @@ pub use core::prelude::v1::{
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)]
-pub use crate::boxed::Box;
+pub use crate::boxed::{Box, FnBox};
#[stable(feature = "rust1", since = "1.0.0")]
#[doc(no_inline)]
pub use crate::string::{String, ToString};
diff --git a/src/libstd/sys/cloudabi/thread.rs b/src/libstd/sys/cloudabi/thread.rs
index 240b6ea..6f71c6b 100644
--- a/src/libstd/sys/cloudabi/thread.rs
+++ b/src/libstd/sys/cloudabi/thread.rs
@@ -21,7 +21,7 @@ unsafe impl Sync for Thread {}
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
- pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
+ pub unsafe fn new(stack: usize, p: Box<dyn FnBox()>) -> io::Result<Thread> {
let p = box p;
let mut native: libc::pthread_t = mem::zeroed();
let mut attr: libc::pthread_attr_t = mem::zeroed();
diff --git a/src/libstd/sys/hermit/thread.rs b/src/libstd/sys/hermit/thread.rs
index 99a9c83..b8bc392 100644
--- a/src/libstd/sys/hermit/thread.rs
+++ b/src/libstd/sys/hermit/thread.rs
@@ -44,9 +44,9 @@ unsafe impl Sync for Thread {}
pub const DEFAULT_MIN_STACK_SIZE: usize = 262144;
impl Thread {
pub unsafe fn new_with_coreid(
_stack: usize,
- p: Box<dyn FnOnce()>,
+ p: Box<dyn FnBox()>,
core_id: isize,
) -> io::Result<Thread> {
let p = box p;
@@ -67,7 +67,7 @@ impl Thread {
}
}
- pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
+ pub unsafe fn new(stack: usize, p: Box<dyn FnBox()>) -> io::Result<Thread> {
Thread::new_with_coreid(stack, p, -1 /* = no specific core */)
}
diff --git a/src/libstd/sys/unix/thread.rs b/src/libstd/sys/unix/thread.rs
index 143cf2f..a6e8faf 100644
--- a/src/libstd/sys/unix/thread.rs
+++ b/src/libstd/sys/unix/thread.rs
@@ -38,8 +38,8 @@ unsafe fn pthread_attr_setstacksize(_attr: *mut libc::pthread_attr_t,
impl Thread {
// unsafe: see thread::Builder::spawn_unchecked for safety requirements
- pub unsafe fn new(stack: usize, p: Box<dyn FnOnce()>) -> io::Result<Thread> {
+ pub unsafe fn new(stack: usize, p: Box<dyn FnBox()>) -> io::Result<Thread> {
- panic!("Warning: Threads are not yet fully supported, because cranelift doesn't support atomics.");
+ println!("Spawned thread");
let p = box p;
let mut native: libc::pthread_t = mem::zeroed();
diff --git a/src/libstd/sys_common/at_exit_imp.rs b/src/libstd/sys_common/at_exit_imp.rs
index cdb72ee..e523333 100644
--- a/src/libstd/sys_common/at_exit_imp.rs
+++ b/src/libstd/sys_common/at_exit_imp.rs
@@ -6,7 +6,7 @@ use crate::mem;
use crate::ptr;
use crate::sys_common::mutex::Mutex;
-type Queue = Vec<Box<dyn FnOnce()>>;
+type Queue = Vec<Box<dyn FnBox()>>;
// NB these are specifically not types from `std::sync` as they currently rely
// on poisoning and this module needs to operate at a lower level than requiring
@@ -53,14 +53,14 @@ pub fn cleanup() {
let queue: Box<Queue> = Box::from_raw(queue);
for to_run in *queue {
// We are not holding any lock, so reentrancy is fine.
- to_run();
+ to_run.call_box(());
}
}
}
}
}
-pub fn push(f: Box<dyn FnOnce()>) -> bool {
+pub fn push(f: Box<dyn FnBox()>) -> bool {
unsafe {
let _guard = LOCK.lock();
if init() {
diff --git a/src/libstd/sys_common/mod.rs b/src/libstd/sys_common/mod.rs
index 7a0bcd0..668bef2 100644
--- a/src/libstd/sys_common/mod.rs
+++ b/src/libstd/sys_common/mod.rs
@@ -113,7 +113,7 @@ pub trait FromInner<Inner> {
/// closure will be run once the main thread exits. Returns `Err` to indicate
/// that the closure could not be registered, meaning that it is not scheduled
/// to be run.
-pub fn at_exit<F: FnOnce() + Send + 'static>(f: F) -> Result<(), ()> {
+pub fn at_exit<F: FnBox() + Send + 'static>(f: F) -> Result<(), ()> {
if at_exit_imp::push(Box::new(f)) { Ok(()) } else { Err(()) }
}
diff --git a/src/libstd/sys_common/thread.rs b/src/libstd/sys_common/thread.rs
index c638be9..5c18a18 100644
--- a/src/libstd/sys_common/thread.rs
+++ b/src/libstd/sys_common/thread.rs
@@ -10,7 +10,7 @@ pub unsafe fn start_thread(main: *mut u8) {
let _handler = stack_overflow::Handler::new();
// Finally, let's run some code.
- Box::from_raw(main as *mut Box<dyn FnBox()>)()
+ Box::from_raw(main as *mut Box<dyn FnBox()>).call_box(())
}
pub fn min_stack() -> usize {
diff --git a/src/libstd/thread/mod.rs b/src/libstd/thread/mod.rs
index 0ffa6ac..4a3e3d6 100644
--- a/src/libstd/thread/mod.rs
+++ b/src/libstd/thread/mod.rs
@@ -485,7 +485,7 @@ impl Builder {
// returning.
native: Some(imp::Thread::new(
stack_size,
- mem::transmute::<Box<dyn FnOnce() + 'a>, Box<dyn FnOnce() + 'static>>(Box::new(
+ mem::transmute::<Box<dyn FnBox() + 'a>, Box<dyn FnBox() + 'static>>(Box::new(
main,
)),
)?),
--
2.20.1

View File

@ -288,7 +288,7 @@ fn local_place<'tcx>(
fx.local_map[&local]
}
pub fn codegen_fn_prelude(fx: &mut FunctionCx<'_, '_, impl Backend>, start_block: Block) {
pub fn codegen_fn_prelude(fx: &mut FunctionCx<'_, '_, impl Backend>, start_block: Block, should_codegen_locals: bool) {
let ssa_analyzed = crate::analyze::analyze(fx);
#[cfg(debug_assertions)]
@ -405,13 +405,17 @@ enum ArgKind<'tcx> {
}
}
for local in fx.mir.vars_and_temps_iter() {
let ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
let layout = fx.layout_of(ty);
// HACK should_codegen_locals required for the ``implement `<Box<F> as FnOnce>::call_once`
// without `alloca``` hack in `base::trans_fn`.
if should_codegen_locals {
for local in fx.mir.vars_and_temps_iter() {
let ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
let layout = fx.layout_of(ty);
let is_ssa = ssa_analyzed[local] == crate::analyze::SsaKind::Ssa;
let is_ssa = ssa_analyzed[local] == crate::analyze::SsaKind::Ssa;
local_place(fx, local, layout, is_ssa);
local_place(fx, local, layout, is_ssa);
}
}
fx.bcx

View File

@ -57,14 +57,96 @@ pub fn trans_fn<'clif, 'tcx, B: Backend + 'static>(
source_info_set: indexmap::IndexSet::new(),
};
if fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited()) {
let entry_block = fx.bcx.create_block();
fx.bcx.append_block_params_for_function_params(entry_block);
fx.bcx.switch_to_block(entry_block);
let arg_uninhabited = fx.mir.args_iter().any(|arg| fx.layout_of(fx.monomorphize(&fx.mir.local_decls[arg].ty)).abi.is_uninhabited());
let is_call_once_for_box = name.starts_with("_ZN83_$LT$alloc..boxed..Box$LT$F$GT$$u20$as$u20$core..ops..function..FnOnce$LT$A$GT$$GT$9call_once");
if arg_uninhabited {
fx.bcx.append_block_params_for_function_params(fx.block_map[START_BLOCK]);
fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
crate::trap::trap_unreachable(&mut fx, "function has uninhabited argument");
} else if is_call_once_for_box {
// HACK implement `<Box<F> as FnOnce>::call_once` without `alloca`.
tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block, false));
fx.bcx.switch_to_block(fx.block_map[START_BLOCK]);
let bb_data = &fx.mir.basic_blocks()[START_BLOCK];
let destination = match &bb_data.terminator().kind {
TerminatorKind::Call {
func,
args,
destination,
cleanup: _,
from_hir_call: _,
} => {
assert_eq!(args.len(), 2);
let closure_arg = Local::new(1);
let closure_local = args[0].place().unwrap().as_local().unwrap();
assert_eq!(fx.mir.local_decls[closure_local].ty, fx.mir.local_decls[closure_arg].ty.builtin_deref(true).unwrap().ty);
let closure_deref = fx.local_map[&closure_arg].place_deref(&mut fx);
fx.local_map.insert(closure_local, closure_deref);
let args_arg = Local::new(2);
let args_local = args[1].place().unwrap().as_local().unwrap();
assert_eq!(fx.mir.local_decls[args_local].ty, fx.mir.local_decls[args_arg].ty);
fx.local_map.insert(args_local, fx.local_map[&args_arg]);
fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
&mut fx,
bb_data.terminator().source_info.span,
func,
args,
destination,
));
destination.map(|(_ret_place, ret_block)| ret_block)
}
_ => unreachable!(),
};
let destination = if let Some(destination) = destination {
fx.bcx.switch_to_block(fx.block_map[destination]);
let bb_data = &fx.mir.basic_blocks()[destination];
match &bb_data.terminator().kind {
TerminatorKind::Call {
func,
args,
destination,
cleanup: _,
from_hir_call: _,
} => {
match destination {
Some((ret_place, _ret_block)) => {
fx.local_map.insert(ret_place.as_local().unwrap(), CPlace::no_place(fx.layout_of(fx.tcx.mk_unit())));
}
None => {}
}
assert_eq!(args.len(), 1);
fx.tcx.sess.time("codegen call", || crate::abi::codegen_terminator_call(
&mut fx,
bb_data.terminator().source_info.span,
func,
args,
destination,
));
destination.map(|(_ret_place, ret_block)| ret_block)
}
_ => unreachable!(),
}
} else {
None
};
if let Some(destination) = destination {
fx.bcx.switch_to_block(fx.block_map[destination]);
let bb_data = &fx.mir.basic_blocks()[destination];
match &bb_data.terminator().kind {
TerminatorKind::Return => crate::abi::codegen_return(&mut fx),
_ => unreachable!(),
}
}
} else {
tcx.sess.time("codegen clif ir", || {
tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block));
tcx.sess.time("codegen prelude", || crate::abi::codegen_fn_prelude(&mut fx, start_block, true));
codegen_fn_content(&mut fx);
});
}