]> git.lizzy.rs Git - rust.git/blob - src/trap.rs
Update cranelift
[rust.git] / src / trap.rs
1 use crate::prelude::*;
2
3 fn codegen_print(fx: &mut FunctionCx<'_, '_, impl cranelift_module::Backend>, msg: &str) {
4     let puts = fx.module.declare_function("puts", Linkage::Import, &Signature {
5         call_conv: CallConv::SystemV,
6         params: vec![AbiParam::new(pointer_ty(fx.tcx))],
7         returns: vec![],
8     }).unwrap();
9     let puts = fx.module.declare_func_in_func(puts, &mut fx.bcx.func);
10
11     let symbol_name = fx.tcx.symbol_name(fx.instance);
12     let msg_bytes = format!("trap at {:?} ({}): {}\0", fx.instance, symbol_name, msg).into_bytes().into_boxed_slice();
13     let mut data_ctx = DataContext::new();
14     data_ctx.define(msg_bytes);
15     let msg_id = fx.module.declare_data(&(symbol_name.as_str().to_string() + msg), Linkage::Local, false, None).unwrap();
16
17     // Ignore DuplicateDefinition error, as the data will be the same
18     let _ = fx.module.define_data(msg_id, &data_ctx);
19
20     let local_msg_id = fx.module.declare_data_in_func(msg_id, fx.bcx.func);
21     let msg_ptr = fx.bcx.ins().global_value(pointer_ty(fx.tcx), local_msg_id);
22     fx.bcx.ins().call(puts, &[msg_ptr]);
23 }
24
25 /// Trap code: user0
26 pub fn trap_panic(fx: &mut FunctionCx<'_, '_, impl cranelift_module::Backend>, msg: impl AsRef<str>) {
27     codegen_print(fx, msg.as_ref());
28     fx.bcx.ins().trap(TrapCode::User(0));
29 }
30
31 /// Trap code: user65535
32 pub fn trap_unreachable(fx: &mut FunctionCx<'_, '_, impl cranelift_module::Backend>, msg: impl AsRef<str>) {
33     codegen_print(fx, msg.as_ref());
34     fx.bcx.ins().trap(TrapCode::User(!0));
35 }
36
37 /// Trap code: user65535
38 pub fn trap_unreachable_ret_value<'tcx>(fx: &mut FunctionCx<'_, 'tcx, impl cranelift_module::Backend>, dest_layout: TyLayout<'tcx>, msg: impl AsRef<str>) -> CValue<'tcx> {
39     codegen_print(fx, msg.as_ref());
40     let true_ = fx.bcx.ins().iconst(types::I32, 1);
41     fx.bcx.ins().trapnz(true_, TrapCode::User(!0));
42     let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
43     CValue::ByRef(zero, dest_layout)
44 }
45
46 /// Trap code: user65535
47 pub fn trap_unreachable_ret_place<'tcx>(fx: &mut FunctionCx<'_, 'tcx, impl cranelift_module::Backend>, dest_layout: TyLayout<'tcx>, msg: impl AsRef<str>) -> CPlace<'tcx> {
48     codegen_print(fx, msg.as_ref());
49     let true_ = fx.bcx.ins().iconst(types::I32, 1);
50     fx.bcx.ins().trapnz(true_, TrapCode::User(!0));
51     let zero = fx.bcx.ins().iconst(fx.pointer_type, 0);
52     CPlace::Addr(zero, None, dest_layout)
53 }