Skip to content

Commit 98548f0

Browse files
committed
Auto merge of #67502 - Mark-Simulacrum:opt-catch, r=<try>
Optimize catch_unwind to match C++ try/catch This refactors the implementation of catching unwinds to allow LLVM to inline the "try" closure directly into the happy path, avoiding indirection. This means that the catch_unwind implementation is (after this PR) zero-cost unless a panic is thrown. https://rust.godbolt.org/z/cZcUSB is an example of the current codegen in a simple case. Notably, the codegen is *exactly the same* if `-Cpanic=abort` is passed, which is clearly not great. This PR, on the other hand, generates the following assembly: ```asm # -Cpanic=unwind: push rbx mov ebx,0x2a call QWORD PTR [rip+0x1c53c] # <happy> mov eax,ebx pop rbx ret mov rdi,rax call QWORD PTR [rip+0x1c537] # cleanup function call call QWORD PTR [rip+0x1c539] # <unfortunate> mov ebx,0xd mov eax,ebx pop rbx ret # -Cpanic=abort: push rax call QWORD PTR [rip+0x20a1] # <happy> mov eax,0x2a pop rcx ret ``` Fixes #64224, and resolves #64222.
2 parents 21ed505 + 0b87a43 commit 98548f0

File tree

31 files changed

+329
-233
lines changed

31 files changed

+329
-233
lines changed

Cargo.lock

+1
Original file line numberDiff line numberDiff line change
@@ -2308,6 +2308,7 @@ dependencies = [
23082308
name = "panic_abort"
23092309
version = "0.0.0"
23102310
dependencies = [
2311+
"cfg-if",
23112312
"compiler_builtins",
23122313
"core",
23132314
"libc",

src/ci/azure-pipelines/try.yml

+46-33
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@ variables:
66
- group: prod-credentials
77

88
jobs:
9-
- job: Linux
10-
timeoutInMinutes: 600
11-
pool:
12-
vmImage: ubuntu-16.04
13-
steps:
14-
- template: steps/run.yml
15-
strategy:
16-
matrix:
17-
dist-x86_64-linux: {}
18-
dist-x86_64-linux-alt:
19-
IMAGE: dist-x86_64-linux
9+
# - job: Linux
10+
# timeoutInMinutes: 600
11+
# pool:
12+
# vmImage: ubuntu-16.04
13+
# steps:
14+
# - template: steps/run.yml
15+
# strategy:
16+
# matrix:
17+
# dist-x86_64-linux: {}
18+
# dist-x86_64-linux-alt:
19+
# IMAGE: dist-x86_64-linux
2020

2121
# The macOS and Windows builds here are currently disabled due to them not being
2222
# overly necessary on `try` builds. We also don't actually have anything that
@@ -49,25 +49,38 @@ jobs:
4949
# NO_LLVM_ASSERTIONS: 1
5050
# NO_DEBUG_ASSERTIONS: 1
5151
#
52-
# - job: Windows
53-
# timeoutInMinutes: 600
54-
# pool:
55-
# vmImage: 'vs2017-win2016'
56-
# steps:
57-
# - template: steps/run.yml
58-
# strategy:
59-
# matrix:
60-
# dist-x86_64-msvc:
61-
# RUST_CONFIGURE_ARGS: >
62-
# --build=x86_64-pc-windows-msvc
63-
# --target=x86_64-pc-windows-msvc,aarch64-pc-windows-msvc
64-
# --enable-full-tools
65-
# --enable-profiler
66-
# SCRIPT: python x.py dist
67-
# DIST_REQUIRE_ALL_TOOLS: 1
68-
# DEPLOY: 1
69-
#
70-
# dist-x86_64-msvc-alt:
71-
# RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-msvc --enable-extended --enable-profiler
72-
# SCRIPT: python x.py dist
73-
# DEPLOY_ALT: 1
52+
- job: Windows
53+
timeoutInMinutes: 600
54+
pool:
55+
vmImage: 'vs2017-win2016'
56+
steps:
57+
- template: steps/run.yml
58+
strategy:
59+
matrix:
60+
x86_64-mingw-1:
61+
SCRIPT: make ci-mingw-subset-1
62+
RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu
63+
CUSTOM_MINGW: 1
64+
# FIXME(#59637)
65+
NO_DEBUG_ASSERTIONS: 1
66+
NO_LLVM_ASSERTIONS: 1
67+
# x86_64-mingw-2:
68+
# SCRIPT: make ci-mingw-subset-2
69+
# RUST_CONFIGURE_ARGS: --build=x86_64-pc-windows-gnu
70+
# CUSTOM_MINGW: 1
71+
# i686-mingw-1:
72+
# RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu
73+
# SCRIPT: make ci-mingw-subset-1
74+
# CUSTOM_MINGW: 1
75+
# # FIXME(#59637)
76+
# NO_DEBUG_ASSERTIONS: 1
77+
# NO_LLVM_ASSERTIONS: 1
78+
i686-mingw-2:
79+
RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu
80+
SCRIPT: make ci-mingw-subset-2
81+
CUSTOM_MINGW: 1
82+
# dist-i686-mingw:
83+
# RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu --enable-full-tools --enable-profiler
84+
# SCRIPT: python x.py dist
85+
# CUSTOM_MINGW: 1
86+
# DIST_REQUIRE_ALL_TOOLS: 1

src/doc/unstable-book/src/language-features/lang-items.md

+15-8
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,11 @@ fn main(_argc: isize, _argv: *const *const u8) -> isize {
5252
5353
#[lang = "eh_personality"] extern fn rust_eh_personality() {}
5454
#[lang = "panic_impl"] extern fn rust_begin_panic(info: &PanicInfo) -> ! { unsafe { intrinsics::abort() } }
55-
#[lang = "eh_unwind_resume"] extern fn rust_eh_unwind_resume() {}
55+
unsafe extern "C" fn eh_unwind_resume(_: *mut u8) -> ! {
56+
intrinsics::abort()
57+
}
58+
#[lang = "eh_unwind_resume"]
59+
static _RESUME: unsafe extern "C" fn(*mut u8) -> ! = eh_unwind_resume;
5660
#[no_mangle] pub extern fn rust_eh_register_frames () {}
5761
#[no_mangle] pub extern fn rust_eh_unregister_frames () {}
5862
```
@@ -131,10 +135,12 @@ pub extern fn rust_eh_personality() {
131135
}
132136
133137
// This function may be needed based on the compilation target.
134-
#[lang = "eh_unwind_resume"]
135-
#[no_mangle]
136-
pub extern fn rust_eh_unwind_resume() {
138+
unsafe extern "C" fn eh_unwind_resume(_: *mut u8) -> ! {
139+
intrinsics::abort()
137140
}
141+
#[lang = "eh_unwind_resume"]
142+
static _RESUME: unsafe extern "C" fn(*mut u8) -> ! = eh_unwind_resume;
143+
138144
139145
#[lang = "panic_impl"]
140146
#[no_mangle]
@@ -174,10 +180,12 @@ pub extern fn rust_eh_personality() {
174180
}
175181
176182
// This function may be needed based on the compilation target.
177-
#[lang = "eh_unwind_resume"]
178-
#[no_mangle]
179-
pub extern fn rust_eh_unwind_resume() {
183+
unsafe extern "C" fn eh_unwind_resume(_: *mut u8) -> ! {
184+
intrinsics::abort()
180185
}
186+
#[lang = "eh_unwind_resume"]
187+
static _RESUME: unsafe extern "C" fn(*mut u8) -> ! = eh_unwind_resume;
188+
181189
182190
#[lang = "panic_impl"]
183191
#[no_mangle]
@@ -248,7 +256,6 @@ the source code.
248256
- `eh_personality`: `libpanic_unwind/gcc.rs` (GNU)
249257
- `eh_personality`: `libpanic_unwind/seh.rs` (SEH)
250258
- `eh_unwind_resume`: `libpanic_unwind/gcc.rs` (GCC)
251-
- `eh_catch_typeinfo`: `libpanic_unwind/seh.rs` (SEH)
252259
- `eh_catch_typeinfo`: `libpanic_unwind/emcc.rs` (EMCC)
253260
- `panic`: `libcore/panicking.rs`
254261
- `panic_bounds_check`: `libcore/panicking.rs`

src/libpanic_abort/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -14,3 +14,4 @@ doc = false
1414
core = { path = "../libcore" }
1515
libc = { version = "0.2", default-features = false }
1616
compiler_builtins = "0.1.0"
17+
cfg-if = "0.1.8"

src/libpanic_abort/lib.rs

+7-10
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,14 @@
1818
#![feature(staged_api)]
1919
#![feature(rustc_attrs)]
2020

21-
// Rust's "try" function, but if we're aborting on panics we just call the
22-
// function as there's nothing else we need to do here.
21+
use core::any::Any;
22+
23+
// We need the definition of TryPayload for __rust_panic_cleanup.
24+
include!("../libpanic_unwind/payload.rs");
25+
2326
#[rustc_std_internal_symbol]
24-
pub unsafe extern "C" fn __rust_maybe_catch_panic(
25-
f: fn(*mut u8),
26-
data: *mut u8,
27-
_data_ptr: *mut usize,
28-
_vtable_ptr: *mut usize,
29-
) -> u32 {
30-
f(data);
31-
0
27+
pub unsafe extern "C" fn __rust_panic_cleanup(_: TryPayload) -> *mut (dyn Any + Send + 'static) {
28+
unreachable!()
3229
}
3330

3431
// "Leak" the payload and shim to the relevant abort on the platform in

src/libpanic_unwind/dummy.rs

-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@ use alloc::boxed::Box;
66
use core::any::Any;
77
use core::intrinsics;
88

9-
pub fn payload() -> *mut u8 {
10-
core::ptr::null_mut()
11-
}
12-
139
pub unsafe fn cleanup(_ptr: *mut u8) -> Box<dyn Any + Send> {
1410
intrinsics::abort()
1511
}

src/libpanic_unwind/emcc.rs

-4
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,6 @@ static EXCEPTION_TYPE_INFO: TypeInfo = TypeInfo {
4848
name: b"rust_panic\0".as_ptr(),
4949
};
5050

51-
pub fn payload() -> *mut u8 {
52-
ptr::null_mut()
53-
}
54-
5551
struct Exception {
5652
// This needs to be an Option because the object's lifetime follows C++
5753
// semantics: when catch_unwind moves the Box out of the exception it must

src/libpanic_unwind/gcc.rs

+13-9
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,6 @@
4848

4949
use alloc::boxed::Box;
5050
use core::any::Any;
51-
use core::ptr;
5251

5352
use crate::dwarf::eh::{self, EHAction, EHContext};
5453
use libc::{c_int, uintptr_t};
@@ -83,10 +82,6 @@ pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
8382
}
8483
}
8584

86-
pub fn payload() -> *mut u8 {
87-
ptr::null_mut()
88-
}
89-
9085
pub unsafe fn cleanup(ptr: *mut u8) -> Box<dyn Any + Send> {
9186
let exception = Box::from_raw(ptr as *mut Exception);
9287
exception.cause
@@ -329,16 +324,25 @@ unsafe fn find_eh_action(
329324
eh::find_eh_action(lsda, &eh_context, foreign_exception)
330325
}
331326

332-
// See docs in the `unwind` module.
327+
#[cfg(all(
328+
target_os = "windows",
329+
any(target_arch = "x86", target_arch = "x86_64"),
330+
target_env = "gnu"
331+
))]
332+
#[cfg_attr(not(bootstrap), lang = "eh_unwind_resume")]
333+
#[used]
334+
pub static RESUME: unsafe extern "C" fn(*mut uw::_Unwind_Exception) -> ! =
335+
uw::_Unwind_Resume as unsafe extern "C" fn(_) -> !;
336+
333337
#[cfg(all(
334338
target_os = "windows",
335339
any(target_arch = "x86", target_arch = "x86_64"),
336340
target_env = "gnu"
337341
))]
338342
#[lang = "eh_unwind_resume"]
339-
#[unwind(allowed)]
340-
unsafe extern "C" fn rust_eh_unwind_resume(panic_ctx: *mut u8) -> ! {
341-
uw::_Unwind_Resume(panic_ctx as *mut uw::_Unwind_Exception);
343+
#[cfg(bootstrap)]
344+
pub unsafe extern "C" fn rust_eh_unwind_resume(p: *mut u8) -> ! {
345+
uw::_Unwind_Resume(p as *mut uw::_Unwind_Exception)
342346
}
343347

344348
// Frame unwind info registration

src/libpanic_unwind/hermit.rs

-4
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,6 @@ use alloc::boxed::Box;
66
use core::any::Any;
77
use core::ptr;
88

9-
pub fn payload() -> *mut u8 {
10-
ptr::null_mut()
11-
}
12-
139
pub unsafe fn cleanup(_ptr: *mut u8) -> Box<dyn Any + Send> {
1410
extern "C" {
1511
pub fn __rust_abort() -> !;

src/libpanic_unwind/lib.rs

+12-25
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,22 @@
2222
#![feature(libc)]
2323
#![feature(nll)]
2424
#![feature(panic_unwind)]
25-
#![feature(raw)]
2625
#![feature(staged_api)]
2726
#![feature(std_internals)]
2827
#![feature(unwind_attributes)]
2928
#![feature(abi_thiscall)]
29+
#![feature(rustc_attrs)]
30+
#![feature(raw)]
3031
#![panic_runtime]
3132
#![feature(panic_runtime)]
33+
#![allow(dead_code)]
3234

3335
use alloc::boxed::Box;
34-
use core::intrinsics;
35-
use core::mem;
36+
use core::any::Any;
3637
use core::panic::BoxMeUp;
37-
use core::raw;
3838

39+
// If adding to this list, you should also look at the list of TryPayload types
40+
// defined in payload.rs and likely add to there as well.
3941
cfg_if::cfg_if! {
4042
if #[cfg(target_os = "emscripten")] {
4143
#[path = "emcc.rs"]
@@ -61,6 +63,8 @@ cfg_if::cfg_if! {
6163
}
6264
}
6365

66+
include!("payload.rs");
67+
6468
extern "C" {
6569
/// Handler in libstd called when a panic object is dropped outside of
6670
/// `catch_unwind`.
@@ -69,28 +73,11 @@ extern "C" {
6973

7074
mod dwarf;
7175

72-
// Entry point for catching an exception, implemented using the `try` intrinsic
73-
// in the compiler.
74-
//
75-
// The interaction between the `payload` function and the compiler is pretty
76-
// hairy and tightly coupled, for more information see the compiler's
77-
// implementation of this.
7876
#[no_mangle]
79-
pub unsafe extern "C" fn __rust_maybe_catch_panic(
80-
f: fn(*mut u8),
81-
data: *mut u8,
82-
data_ptr: *mut usize,
83-
vtable_ptr: *mut usize,
84-
) -> u32 {
85-
let mut payload = imp::payload();
86-
if intrinsics::r#try(f, data, &mut payload as *mut _ as *mut _) == 0 {
87-
0
88-
} else {
89-
let obj = mem::transmute::<_, raw::TraitObject>(imp::cleanup(payload));
90-
*data_ptr = obj.data as usize;
91-
*vtable_ptr = obj.vtable as usize;
92-
1
93-
}
77+
pub unsafe extern "C" fn __rust_panic_cleanup(
78+
payload: TryPayload,
79+
) -> *mut (dyn Any + Send + 'static) {
80+
Box::into_raw(imp::cleanup(payload))
9481
}
9582

9683
// Entry point for raising an exception, just delegates to the platform-specific

src/libpanic_unwind/payload.rs

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Type definition for the payload argument of the try intrinsic.
2+
//
3+
// This must be kept in sync with the implementations of the try intrinsic.
4+
//
5+
// This file is included by both panic runtimes and libstd. It is part of the
6+
// panic runtime ABI.
7+
cfg_if::cfg_if! {
8+
if #[cfg(target_os = "emscripten")] {
9+
type TryPayload = *mut u8;
10+
} else if #[cfg(target_arch = "wasm32")] {
11+
type TryPayload = *mut u8;
12+
} else if #[cfg(target_os = "hermit")] {
13+
type TryPayload = *mut u8;
14+
} else if #[cfg(all(target_env = "msvc", target_arch = "aarch64"))] {
15+
type TryPayload = *mut u8;
16+
} else if #[cfg(target_env = "msvc")] {
17+
type TryPayload = [u64; 2];
18+
} else {
19+
type TryPayload = *mut u8;
20+
}
21+
}

src/libpanic_unwind/seh.rs

+8-9
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,9 @@ pub struct _TypeDescriptor {
167167

168168
// Note that we intentionally ignore name mangling rules here: we don't want C++
169169
// to be able to catch Rust panics by simply declaring a `struct rust_panic`.
170+
//
171+
// When modifying, make sure that the type name string exactly matches
172+
// the one used in src/librustc_codegen_llvm/intrinsic.rs.
170173
const TYPE_NAME: [u8; 11] = *b"rust_panic\0";
171174

172175
static mut THROW_INFO: _ThrowInfo = _ThrowInfo {
@@ -199,12 +202,12 @@ extern "C" {
199202
static TYPE_INFO_VTABLE: *const u8;
200203
}
201204

202-
// We use #[lang = "eh_catch_typeinfo"] here as this is the type descriptor which
203-
// we'll use in LLVM's `catchpad` instruction which ends up also being passed as
204-
// an argument to the C++ personality function.
205+
// This type descriptor is only used when throwing an exception. The catch part
206+
// is handled by the try intrinsic, which generates its own TypeDescriptor.
205207
//
206-
// Again, I'm not entirely sure what this is describing, it just seems to work.
207-
#[cfg_attr(not(test), lang = "eh_catch_typeinfo")]
208+
// This is fine since the MSVC runtime uses string comparison on the type name
209+
// to match TypeDescriptors rather than pointer equality.
210+
#[cfg_attr(bootstrap, lang = "eh_catch_typeinfo")]
208211
static mut TYPE_DESCRIPTOR: _TypeDescriptor = _TypeDescriptor {
209212
pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _,
210213
spare: core::ptr::null_mut(),
@@ -308,10 +311,6 @@ pub unsafe fn panic(data: Box<dyn Any + Send>) -> u32 {
308311
_CxxThrowException(throw_ptr, &mut THROW_INFO as *mut _ as *mut _);
309312
}
310313

311-
pub fn payload() -> [u64; 2] {
312-
[0; 2]
313-
}
314-
315314
pub unsafe fn cleanup(payload: [u64; 2]) -> Box<dyn Any + Send> {
316315
mem::transmute(raw::TraitObject { data: payload[0] as *mut _, vtable: payload[1] as *mut _ })
317316
}

0 commit comments

Comments
 (0)