Skip to content

Commit f7f883c

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 3f9bddc + 0f185e0 commit f7f883c

File tree

36 files changed

+218
-249
lines changed

36 files changed

+218
-249
lines changed

Diff for: .gitmodules

+2-2
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,8 @@
3939
url = https://github.com/rust-lang/edition-guide.git
4040
[submodule "src/llvm-project"]
4141
path = src/llvm-project
42-
url = https://github.com/rust-lang/llvm-project.git
43-
branch = rustc/9.0-2019-12-19
42+
url = https://github.com/Amanieu/llvm-project.git
43+
branch = opt-catch
4444
[submodule "src/doc/embedded-book"]
4545
path = src/doc/embedded-book
4646
url = https://github.com/rust-embedded/book.git

Diff for: 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",

Diff for: src/ci/azure-pipelines/try.yml

+28-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,20 @@ 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+
i686-mingw-2:
61+
RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu
62+
SCRIPT: make ci-mingw-subset-2
63+
CUSTOM_MINGW: 1
64+
dist-i686-mingw:
65+
RUST_CONFIGURE_ARGS: --build=i686-pc-windows-gnu --enable-debug-assertions --enable-optimize --debuginfo-level=1
66+
SCRIPT: python x.py dist
67+
CUSTOM_MINGW: 1
68+
N_DIST_REQUIRE_ALL_TOOLS: 1

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

+4-18
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,6 @@ 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() {}
5655
#[no_mangle] pub extern fn rust_eh_register_frames () {}
5756
#[no_mangle] pub extern fn rust_eh_unregister_frames () {}
5857
```
@@ -67,7 +66,7 @@ Other features provided by lang items include:
6766
marked with lang items; those specific four are `eq`, `ord`,
6867
`deref`, and `add` respectively.
6968
- stack unwinding and general failure; the `eh_personality`,
70-
`eh_unwind_resume`, `fail` and `fail_bounds_checks` lang items.
69+
`fail` and `fail_bounds_checks` lang items.
7170
- the traits in `std::marker` used to indicate types of
7271
various kinds; lang items `send`, `sync` and `copy`.
7372
- the marker types and variance indicators found in
@@ -130,12 +129,6 @@ fn start(_argc: isize, _argv: *const *const u8) -> isize {
130129
pub extern fn rust_eh_personality() {
131130
}
132131
133-
// 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() {
137-
}
138-
139132
#[lang = "panic_impl"]
140133
#[no_mangle]
141134
pub extern fn rust_begin_panic(info: &PanicInfo) -> ! {
@@ -173,12 +166,6 @@ pub extern fn main(_argc: i32, _argv: *const *const u8) -> i32 {
173166
pub extern fn rust_eh_personality() {
174167
}
175168
176-
// 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() {
180-
}
181-
182169
#[lang = "panic_impl"]
183170
#[no_mangle]
184171
pub extern fn rust_begin_panic(info: &PanicInfo) -> ! {
@@ -213,8 +200,8 @@ the screen. While the language item's name is `panic_impl`, the symbol name is
213200

214201
A third function, `rust_eh_unwind_resume`, is also needed if the `custom_unwind_resume`
215202
flag is set in the options of the compilation target. It allows customizing the
216-
process of resuming unwind at the end of the landing pads. The language item's name
217-
is `eh_unwind_resume`.
203+
process of resuming unwind at the end of the landing pads. Since this function
204+
must be defined in assembly code it does not have an associated language item.
218205

219206
## List of all language items
220207

@@ -247,9 +234,8 @@ the source code.
247234
- `eh_personality`: `libpanic_unwind/emcc.rs` (EMCC)
248235
- `eh_personality`: `libpanic_unwind/gcc.rs` (GNU)
249236
- `eh_personality`: `libpanic_unwind/seh.rs` (SEH)
250-
- `eh_unwind_resume`: `libpanic_unwind/gcc.rs` (GCC)
251-
- `eh_catch_typeinfo`: `libpanic_unwind/seh.rs` (SEH)
252237
- `eh_catch_typeinfo`: `libpanic_unwind/emcc.rs` (EMCC)
238+
- `rust_eh_unwind_resume`: `libpanic_unwind/gcc.rs` (GCC)
253239
- `panic`: `libcore/panicking.rs`
254240
- `panic_bounds_check`: `libcore/panicking.rs`
255241
- `panic_impl`: `libcore/panicking.rs`

Diff for: 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"

Diff for: 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

Diff for: 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
}

Diff for: 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

Diff for: src/libpanic_unwind/gcc.rs

+22-5
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
@@ -331,6 +326,27 @@ unsafe fn find_eh_action(
331326

332327
// See docs in the `unwind` module.
333328
#[cfg(all(
329+
not(bootstrap),
330+
target_os = "windows",
331+
any(target_arch = "x86", target_arch = "x86_64"),
332+
target_env = "gnu"
333+
))]
334+
global_asm! {
335+
r#"
336+
.def _rust_eh_unwind_resume;
337+
.scl 2;
338+
.type 32;
339+
.endef
340+
.globl _rust_eh_unwind_resume
341+
.p2align 4, 0x90
342+
_rust_eh_unwind_resume:
343+
.cfi_startproc
344+
jmp __Unwind_Resume
345+
.cfi_endproc
346+
"#
347+
}
348+
#[cfg(all(
349+
bootstrap,
334350
target_os = "windows",
335351
any(target_arch = "x86", target_arch = "x86_64"),
336352
target_env = "gnu"
@@ -341,6 +357,7 @@ unsafe extern "C" fn rust_eh_unwind_resume(panic_ctx: *mut u8) -> ! {
341357
uw::_Unwind_Resume(panic_ctx as *mut uw::_Unwind_Exception);
342358
}
343359

360+
344361
// Frame unwind info registration
345362
//
346363
// Each module's image contains a frame unwind info section (usually

Diff for: 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() -> !;

Diff for: src/libpanic_unwind/lib.rs

+14-25
Original file line numberDiff line numberDiff line change
@@ -22,20 +22,24 @@
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)]
31+
#![feature(asm)]
32+
#![feature(naked_functions)]
3033
#![panic_runtime]
3134
#![feature(panic_runtime)]
35+
#![feature(global_asm)]
3236

3337
use alloc::boxed::Box;
34-
use core::intrinsics;
35-
use core::mem;
38+
use core::any::Any;
3639
use core::panic::BoxMeUp;
37-
use core::raw;
3840

41+
// If adding to this list, you should also look at the list of TryPayload types
42+
// defined in payload.rs and likely add to there as well.
3943
cfg_if::cfg_if! {
4044
if #[cfg(target_os = "emscripten")] {
4145
#[path = "emcc.rs"]
@@ -61,6 +65,8 @@ cfg_if::cfg_if! {
6165
}
6266
}
6367

68+
include!("payload.rs");
69+
6470
extern "C" {
6571
/// Handler in libstd called when a panic object is dropped outside of
6672
/// `catch_unwind`.
@@ -69,28 +75,11 @@ extern "C" {
6975

7076
mod dwarf;
7177

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.
7878
#[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-
}
79+
pub unsafe extern "C" fn __rust_panic_cleanup(
80+
payload: TryPayload,
81+
) -> *mut (dyn Any + Send + 'static) {
82+
Box::into_raw(imp::cleanup(payload))
9483
}
9584

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

Diff for: 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+
}

0 commit comments

Comments
 (0)