1 //! Helpers used to print a message and abort in case of certain panics and some detected UB.
5 fn codegen_print(fx: &mut FunctionCx<'_, '_, '_>, msg: &str) {
13 call_conv: CallConv::triple_default(fx.triple()),
14 params: vec![AbiParam::new(pointer_ty(fx.tcx))],
15 returns: vec![AbiParam::new(types::I32)],
19 let puts = fx.cx.module.declare_func_in_func(puts, &mut fx.bcx.func);
20 if fx.clif_comments.enabled() {
21 fx.add_comment(puts, "puts");
24 let real_msg = format!("trap at {:?} ({}): {}\0", fx.instance, fx.symbol_name, msg);
25 let msg_ptr = fx.anonymous_str("trap", &real_msg);
26 fx.bcx.ins().call(puts, &[msg_ptr]);
30 pub(crate) fn trap_abort(fx: &mut FunctionCx<'_, '_, '_>, msg: impl AsRef<str>) {
31 codegen_print(fx, msg.as_ref());
32 fx.bcx.ins().trap(TrapCode::User(1));
35 /// Use this for example when a function call should never return. This will fill the current block,
36 /// so you can **not** add instructions to it afterwards.
38 /// Trap code: user65535
39 pub(crate) fn trap_unreachable(fx: &mut FunctionCx<'_, '_, '_>, msg: impl AsRef<str>) {
40 codegen_print(fx, msg.as_ref());
41 fx.bcx.ins().trap(TrapCode::UnreachableCodeReached);
44 /// Like `trap_unreachable` but returns a fake value of the specified type.
46 /// Trap code: user65535
47 pub(crate) fn trap_unreachable_ret_value<'tcx>(
48 fx: &mut FunctionCx<'_, '_, 'tcx>,
49 dest_layout: TyAndLayout<'tcx>,
52 codegen_print(fx, msg.as_ref());
53 let true_ = fx.bcx.ins().iconst(types::I32, 1);
54 fx.bcx.ins().trapnz(true_, TrapCode::UnreachableCodeReached);
55 CValue::by_ref(Pointer::const_addr(fx, 0), dest_layout)
58 /// Use this when something is unimplemented, but `libcore` or `libstd` requires it to codegen.
59 /// Unlike `trap_unreachable` this will not fill the current block, so you **must** add instructions
62 /// Trap code: user65535
63 pub(crate) fn trap_unimplemented(fx: &mut FunctionCx<'_, '_, '_>, msg: impl AsRef<str>) {
64 codegen_print(fx, msg.as_ref());
65 let true_ = fx.bcx.ins().iconst(types::I32, 1);
66 fx.bcx.ins().trapnz(true_, TrapCode::User(!0));
69 /// Like `trap_unimplemented` but returns a fake value of the specified type.
71 /// Trap code: user65535
72 pub(crate) fn trap_unimplemented_ret_value<'tcx>(
73 fx: &mut FunctionCx<'_, '_, 'tcx>,
74 dest_layout: TyAndLayout<'tcx>,
77 trap_unimplemented(fx, msg);
78 CValue::by_ref(Pointer::const_addr(fx, 0), dest_layout)