Skip to main content

rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2use std::ops::Range;
3
4use rustc_abi::{
5    Align, ArmCall, BackendRepr, CanonAbi, ExternAbi, HasDataLayout, Reg, Size, WrappingRange,
6};
7use rustc_ast as ast;
8use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
9use rustc_data_structures::packed::Pu128;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::lang_items::LangItem;
12use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
13use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
14use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
15use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
16use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
17use rustc_middle::{bug, span_bug};
18use rustc_session::config::OptLevel;
19use rustc_span::{Span, Spanned};
20use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, PassMode};
21use tracing::{debug, info};
22
23use super::operand::OperandRef;
24use super::operand::OperandValue::{self, Immediate, Pair, Ref, ZeroSized};
25use super::place::{PlaceRef, PlaceValue};
26use super::{CachedLlbb, FunctionCx, LocalRef};
27use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
28use crate::common::{self, IntPredicate};
29use crate::errors::CompilerBuiltinsCannotCall;
30use crate::mir::IntrinsicResult;
31use crate::traits::*;
32use crate::{MemFlags, meth};
33
34// Indicates if we are in the middle of merging a BB's successor into it. This
35// can happen when BB jumps directly to its successor and the successor has no
36// other predecessors.
37#[derive(#[automatically_derived]
impl ::core::fmt::Debug for MergingSucc {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                MergingSucc::False => "False",
                MergingSucc::True => "True",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for MergingSucc {
    #[inline]
    fn eq(&self, other: &MergingSucc) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
38enum MergingSucc {
39    False,
40    True,
41}
42
43/// Indicates to the call terminator codegen whether a call
44/// is a normal call or an explicit tail call.
45#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CallKind {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CallKind::Normal => "Normal",
                CallKind::Tail => "Tail",
            })
    }
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CallKind {
    #[inline]
    fn eq(&self, other: &CallKind) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr
    }
}PartialEq)]
46enum CallKind {
47    Normal,
48    Tail,
49}
50
51/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
52/// e.g., creating a basic block, calling a function, etc.
53struct TerminatorCodegenHelper<'tcx> {
54    bb: mir::BasicBlock,
55    terminator: &'tcx mir::Terminator<'tcx>,
56}
57
58impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
59    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
60    /// either already previously cached, or newly created, by `landing_pad_for`.
61    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
62        &self,
63        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
64    ) -> Option<&'b Bx::Funclet> {
65        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
66        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
67        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
68        // it has to be now. This may not seem necessary, as RPO should lead
69        // to all the unwind edges being visited (and so to `landing_pad_for`
70        // getting called for them), before building any of the blocks inside
71        // the funclet itself - however, if MIR contains edges that end up not
72        // being needed in the LLVM IR after monomorphization, the funclet may
73        // be unreachable, and we don't have yet a way to skip building it in
74        // such an eventuality (which may be a better solution than this).
75        if fx.funclets[funclet_bb].is_none() {
76            fx.landing_pad_for(funclet_bb);
77        }
78        Some(
79            fx.funclets[funclet_bb]
80                .as_ref()
81                .expect("landing_pad_for didn't also create funclets entry"),
82        )
83    }
84
85    /// Get a basic block (creating it if necessary), possibly with cleanup
86    /// stuff in it or next to it.
87    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
88        &self,
89        fx: &mut FunctionCx<'a, 'tcx, Bx>,
90        target: mir::BasicBlock,
91    ) -> Bx::BasicBlock {
92        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
93        let mut lltarget = fx.llbb(target);
94        if needs_landing_pad {
95            lltarget = fx.landing_pad_for(target);
96        }
97        if is_cleanupret {
98            // Cross-funclet jump - need a trampoline
99            if !base::wants_new_eh_instructions(fx.cx.tcx().sess) {
    ::core::panicking::panic("assertion failed: base::wants_new_eh_instructions(fx.cx.tcx().sess)")
};assert!(base::wants_new_eh_instructions(fx.cx.tcx().sess));
100            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:100",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(100u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("llbb_with_cleanup: creating cleanup trampoline for {0:?}",
                                                    target) as &dyn Value))])
            });
    } else { ; }
};debug!("llbb_with_cleanup: creating cleanup trampoline for {:?}", target);
101            let name = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
                self.bb, target))
    })format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
102            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
103            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
104            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
105            trampoline_llbb
106        } else {
107            lltarget
108        }
109    }
110
111    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
112        &self,
113        fx: &mut FunctionCx<'a, 'tcx, Bx>,
114        target: mir::BasicBlock,
115    ) -> (bool, bool) {
116        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
117            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
118            let target_funclet = cleanup_kinds[target].funclet_bb(target);
119            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
120                (None, None) => (false, false),
121                (None, Some(_)) => (true, false),
122                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
123                (Some(_), None) => {
124                    let span = self.terminator.source_info.span;
125                    ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("{0:?} - jump out of cleanup?", self.terminator));span_bug!(span, "{:?} - jump out of cleanup?", self.terminator);
126                }
127            };
128            (needs_landing_pad, is_cleanupret)
129        } else {
130            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
131            let is_cleanupret = false;
132            (needs_landing_pad, is_cleanupret)
133        }
134    }
135
136    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
137        &self,
138        fx: &mut FunctionCx<'a, 'tcx, Bx>,
139        bx: &mut Bx,
140        target: mir::BasicBlock,
141        mergeable_succ: bool,
142        attributes: &[AttributeKind],
143    ) -> MergingSucc {
144        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
145        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
146            // We can merge the successor into this bb, so no need for a `br`.
147            MergingSucc::True
148        } else {
149            let mut lltarget = fx.llbb(target);
150            if needs_landing_pad {
151                lltarget = fx.landing_pad_for(target);
152            }
153            if is_cleanupret {
154                // micro-optimization: generate a `ret` rather than a jump
155                // to a trampoline.
156                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
157            } else {
158                bx.br_with_attrs(lltarget, attributes);
159            }
160            MergingSucc::False
161        }
162    }
163
164    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
165    /// return destination `destination` and the unwind action `unwind`.
166    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
167        &self,
168        fx: &mut FunctionCx<'a, 'tcx, Bx>,
169        bx: &mut Bx,
170        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
171        fn_ptr: Bx::Value,
172        llargs: &[Bx::Value],
173        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
174        mut unwind: mir::UnwindAction,
175        lifetime_ends_after_call: &[(Bx::Value, Size)],
176        instance: Option<Instance<'tcx>>,
177        kind: CallKind,
178        mergeable_succ: bool,
179    ) -> MergingSucc {
180        let tcx = bx.tcx();
181        if let Some(instance) = instance
182            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
183        {
184            if destination.is_some() {
185                let caller_def = fx.instance.def_id();
186                let e = CompilerBuiltinsCannotCall {
187                    span: tcx.def_span(caller_def),
188                    caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
189                    callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
190                };
191                tcx.dcx().emit_err(e);
192            } else {
193                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:193",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(193u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("compiler_builtins call to diverging function {0:?} replaced with abort",
                                                    instance.def_id()) as &dyn Value))])
            });
    } else { ; }
};info!(
194                    "compiler_builtins call to diverging function {:?} replaced with abort",
195                    instance.def_id()
196                );
197                bx.abort();
198                bx.unreachable();
199                return MergingSucc::False;
200            }
201        }
202
203        // If there is a cleanup block and the function we're calling can unwind, then
204        // do an invoke, otherwise do a call.
205        let fn_ty = bx.fn_decl_backend_type(fn_abi);
206
207        let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
208            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
209        } else {
210            None
211        };
212        let caller_attrs = caller_attrs.as_deref();
213
214        if !fn_abi.can_unwind {
215            unwind = mir::UnwindAction::Unreachable;
216        }
217
218        let unwind_block = match unwind {
219            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
220            mir::UnwindAction::Continue => None,
221            mir::UnwindAction::Unreachable => None,
222            mir::UnwindAction::Terminate(reason) => {
223                if fx.mir[self.bb].is_cleanup && base::wants_wasm_eh(fx.cx.tcx().sess) {
224                    // For wasm, we need to generate a nested `cleanuppad within %outer_pad`
225                    // to catch exceptions during cleanup and call `panic_in_cleanup`.
226                    Some(fx.terminate_block(reason, Some(self.bb)))
227                } else if fx.mir[self.bb].is_cleanup
228                    && base::wants_new_eh_instructions(fx.cx.tcx().sess)
229                {
230                    // MSVC SEH will abort automatically if an exception tries to
231                    // propagate out from cleanup.
232                    None
233                } else {
234                    Some(fx.terminate_block(reason, None))
235                }
236            }
237        };
238
239        if kind == CallKind::Tail {
240            bx.tail_call(fn_ty, caller_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
241            return MergingSucc::False;
242        }
243
244        if let Some(unwind_block) = unwind_block {
245            let ret_llbb = if let Some((_, target)) = destination {
246                self.llbb_with_cleanup(fx, target)
247            } else {
248                fx.unreachable_block()
249            };
250            let invokeret = bx.invoke(
251                fn_ty,
252                caller_attrs,
253                Some(fn_abi),
254                fn_ptr,
255                llargs,
256                ret_llbb,
257                unwind_block,
258                self.funclet(fx),
259                instance,
260            );
261            if fx.mir[self.bb].is_cleanup {
262                bx.apply_attrs_to_cleanup_callsite(invokeret);
263            }
264
265            if let Some((ret_dest, target)) = destination {
266                bx.switch_to_block(fx.llbb(target));
267                fx.set_debug_loc(bx, self.terminator.source_info);
268                for &(tmp, size) in lifetime_ends_after_call {
269                    bx.lifetime_end(tmp, size);
270                }
271                fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
272
273                // If the return value was retagged as it was stored,
274                // then we might be in a different basic block now.
275                // Update the cached block for `target` to point to this new
276                // block, where codegen will continue.
277                fx.cached_llbbs[target] = CachedLlbb::Some(bx.llbb());
278            }
279            MergingSucc::False
280        } else {
281            let llret = bx.call(
282                fn_ty,
283                caller_attrs,
284                Some(fn_abi),
285                fn_ptr,
286                llargs,
287                self.funclet(fx),
288                instance,
289            );
290            if fx.mir[self.bb].is_cleanup {
291                bx.apply_attrs_to_cleanup_callsite(llret);
292            }
293
294            if let Some((ret_dest, target)) = destination {
295                for &(tmp, size) in lifetime_ends_after_call {
296                    bx.lifetime_end(tmp, size);
297                }
298                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
299                self.funclet_br(fx, bx, target, mergeable_succ, &[])
300            } else {
301                bx.unreachable();
302                MergingSucc::False
303            }
304        }
305    }
306
307    /// Generates inline assembly with optional `destination` and `unwind`.
308    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
309        &self,
310        fx: &mut FunctionCx<'a, 'tcx, Bx>,
311        bx: &mut Bx,
312        template: &[InlineAsmTemplatePiece],
313        operands: &[InlineAsmOperandRef<'tcx, Bx>],
314        options: InlineAsmOptions,
315        line_spans: &[Span],
316        destination: Option<mir::BasicBlock>,
317        unwind: mir::UnwindAction,
318        instance: Instance<'_>,
319        mergeable_succ: bool,
320    ) -> MergingSucc {
321        let unwind_target = match unwind {
322            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
323            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
324            mir::UnwindAction::Continue => None,
325            mir::UnwindAction::Unreachable => None,
326        };
327
328        if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
    InlineAsmOperandRef::Label { .. } => true,
    _ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
329            if !unwind_target.is_none() {
    ::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
330            let ret_llbb = if let Some(target) = destination {
331                self.llbb_with_cleanup(fx, target)
332            } else {
333                fx.unreachable_block()
334            };
335
336            bx.codegen_inline_asm(
337                template,
338                operands,
339                options,
340                line_spans,
341                instance,
342                Some(ret_llbb),
343                None,
344            );
345            MergingSucc::False
346        } else if let Some(cleanup) = unwind_target {
347            let ret_llbb = if let Some(target) = destination {
348                self.llbb_with_cleanup(fx, target)
349            } else {
350                fx.unreachable_block()
351            };
352
353            bx.codegen_inline_asm(
354                template,
355                operands,
356                options,
357                line_spans,
358                instance,
359                Some(ret_llbb),
360                Some((cleanup, self.funclet(fx))),
361            );
362            MergingSucc::False
363        } else {
364            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
365
366            if let Some(target) = destination {
367                self.funclet_br(fx, bx, target, mergeable_succ, &[])
368            } else {
369                bx.unreachable();
370                MergingSucc::False
371            }
372        }
373    }
374}
375
376/// Codegen implementations for some terminator variants.
377impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
378    /// Generates code for a `Resume` terminator.
379    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
380        if let Some(funclet) = helper.funclet(self) {
381            bx.cleanup_ret(funclet, None);
382        } else {
383            let slot = self.get_personality_slot(bx);
384            let exn0 = slot.project_field(bx, 0);
385            let exn0 = bx.load_operand(exn0).immediate();
386            let exn1 = slot.project_field(bx, 1);
387            let exn1 = bx.load_operand(exn1).immediate();
388            slot.storage_dead(bx);
389
390            bx.resume(exn0, exn1);
391        }
392    }
393
394    fn codegen_switchint_terminator(
395        &mut self,
396        helper: TerminatorCodegenHelper<'tcx>,
397        bx: &mut Bx,
398        discr: &mir::Operand<'tcx>,
399        targets: &SwitchTargets,
400    ) {
401        let discr = self.codegen_operand(bx, discr);
402        let discr_value = discr.immediate();
403        let switch_ty = discr.layout.ty;
404        // If our discriminant is a constant we can branch directly
405        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
406            let target = targets.target_for_value(const_discr);
407            bx.br(helper.llbb_with_cleanup(self, target));
408            return;
409        };
410
411        let mut target_iter = targets.iter();
412        if target_iter.len() == 1 {
413            // If there are two targets (one conditional, one fallback), emit `br` instead of
414            // `switch`.
415            let (test_value, target) = target_iter.next().unwrap();
416            let otherwise = targets.otherwise();
417            let lltarget = helper.llbb_with_cleanup(self, target);
418            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
419            let target_cold = self.cold_blocks[target];
420            let otherwise_cold = self.cold_blocks[otherwise];
421            // If `target_cold == otherwise_cold`, the branches have the same weight
422            // so there is no expectation. If they differ, the `target` branch is expected
423            // when the `otherwise` branch is cold.
424            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
425            if switch_ty == bx.tcx().types.bool {
426                // Don't generate trivial icmps when switching on bool.
427                match test_value {
428                    0 => {
429                        let expect = expect.map(|e| !e);
430                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
431                    }
432                    1 => {
433                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
434                    }
435                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
436                }
437            } else {
438                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
439                let llval = bx.const_uint_big(switch_llty, test_value);
440                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
441                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
442            }
443        } else if target_iter.len() == 2
444            && self.mir[targets.otherwise()].is_empty_unreachable()
445            && targets.all_values().contains(&Pu128(0))
446            && targets.all_values().contains(&Pu128(1))
447        {
448            // This is the really common case for `bool`, `Option`, etc.
449            // By using `trunc nuw` we communicate that other values are
450            // impossible without needing `switch` or `assume`s.
451            let true_bb = targets.target_for_value(1);
452            let false_bb = targets.target_for_value(0);
453            let true_ll = helper.llbb_with_cleanup(self, true_bb);
454            let false_ll = helper.llbb_with_cleanup(self, false_bb);
455
456            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
457                None
458            } else {
459                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
460                    // Same coldness, no expectation
461                    (true, true) | (false, false) => None,
462                    // Different coldness, expect the non-cold one
463                    (true, false) => Some(false),
464                    (false, true) => Some(true),
465                }
466            };
467
468            let bool_ty = bx.tcx().types.bool;
469            let cond = if switch_ty == bool_ty {
470                discr_value
471            } else {
472                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
473                bx.unchecked_utrunc(discr_value, bool_llty)
474            };
475            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
476        } else if self.cx.sess().opts.optimize == OptLevel::No
477            && target_iter.len() == 2
478            && self.mir[targets.otherwise()].is_empty_unreachable()
479        {
480            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
481            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
482            // BB, which will usually (but not always) be dead code.
483            //
484            // Why only in unoptimized builds?
485            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
486            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
487            //   significant compile time speedups for unoptimized builds.
488            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
489            //   worse generated code because LLVM can no longer tell that the value being switched
490            //   on can only have two values, e.g. 0 and 1.
491            //
492            let (test_value1, target1) = target_iter.next().unwrap();
493            let (_test_value2, target2) = target_iter.next().unwrap();
494            let ll1 = helper.llbb_with_cleanup(self, target1);
495            let ll2 = helper.llbb_with_cleanup(self, target2);
496            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
497            let llval = bx.const_uint_big(switch_llty, test_value1);
498            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
499            bx.cond_br(cmp, ll1, ll2);
500        } else {
501            let otherwise = targets.otherwise();
502            let otherwise_cold = self.cold_blocks[otherwise];
503            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
504            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
505            let none_cold = cold_count == 0;
506            let all_cold = cold_count == targets.iter().len();
507            if (none_cold && (!otherwise_cold || otherwise_unreachable))
508                || (all_cold && (otherwise_cold || otherwise_unreachable))
509            {
510                // All targets have the same weight,
511                // or `otherwise` is unreachable and it's the only target with a different weight.
512                bx.switch(
513                    discr_value,
514                    helper.llbb_with_cleanup(self, targets.otherwise()),
515                    target_iter
516                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
517                );
518            } else {
519                // Targets have different weights
520                bx.switch_with_weights(
521                    discr_value,
522                    helper.llbb_with_cleanup(self, targets.otherwise()),
523                    otherwise_cold,
524                    target_iter.map(|(value, target)| {
525                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
526                    }),
527                );
528            }
529        }
530    }
531
532    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
533        // Explicitly end the lifetime of the VaList if this function is c-variadic. We explicitly
534        // start the lifetime when desugaring `...`. Ending the lifetime meaningfully improves
535        // codegen.
536        if self.fn_abi.c_variadic {
537            // The `VaList` "spoofed" argument is just after all the real arguments.
538            let va_list_arg_idx = self.fn_abi.args.len();
539            match self.locals[mir::Local::arg(va_list_arg_idx)] {
540                LocalRef::Place(va_list) => {
541                    // NOTE: we don't actually call LLVM's va_end here. We know it's a no-op for
542                    // all current targets and hence don't bother
543                    // (as permitted by https://llvm.org/docs/LangRef.html#llvm-va-end-intrinsic).
544
545                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
546                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
547                }
548                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("C-variadic function must have a `VaList` place"))bug!("C-variadic function must have a `VaList` place"),
549            }
550        }
551        if self.fn_abi.ret.layout.is_uninhabited() {
552            // Functions with uninhabited return values are marked `noreturn`,
553            // so we should make sure that we never actually do.
554            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
555            // if that turns out to be helpful.
556            bx.abort();
557            // `abort` does not terminate the block, so we still need to generate
558            // an `unreachable` terminator after it.
559            bx.unreachable();
560            return;
561        }
562        let llval = match &self.fn_abi.ret.mode {
563            PassMode::Ignore | PassMode::Indirect { .. } => {
564                bx.ret_void();
565                return;
566            }
567
568            PassMode::Direct(_) | PassMode::Pair(..) => {
569                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
570                if let Ref(place_val) = op.val {
571                    bx.load_from_place(bx.backend_type(op.layout), place_val)
572                } else {
573                    op.immediate_or_packed_pair(bx)
574                }
575            }
576
577            PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
578                let op = match self.locals[mir::RETURN_PLACE] {
579                    LocalRef::Operand(op) => op,
580                    LocalRef::PendingOperand => ::rustc_middle::util::bug::bug_fmt(format_args!("use of return before def"))bug!("use of return before def"),
581                    LocalRef::Place(cg_place) => OperandRef {
582                        val: Ref(cg_place.val),
583                        layout: cg_place.layout,
584                        move_annotation: None,
585                    },
586                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
587                };
588                let llslot = match op.val {
589                    Immediate(_) | Pair(..) => {
590                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
591                        op.val.store(bx, scratch);
592                        scratch.val.llval
593                    }
594                    Ref(place_val) => {
595                        {
    match (&place_val.align, &op.layout.align.abi) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("return place is unaligned!")));
            }
        }
    }
};assert_eq!(
596                            place_val.align, op.layout.align.abi,
597                            "return place is unaligned!"
598                        );
599                        place_val.llval
600                    }
601                    ZeroSized => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST return value shouldn\'t be in PassMode::Cast"))bug!("ZST return value shouldn't be in PassMode::Cast"),
602                };
603
604                if self.fn_abi.conv == CanonAbi::Arm(ArmCall::CCmseNonSecureEntry) {
605                    // The return value of an `extern "cmse-nonsecure-entry"` function crosses the
606                    // secure boundary. Zero padding bytes so information does not leak.
607                    //
608                    // This only zeroes "guaranteed" padding. There may be more bytes that are
609                    // padding for some but not all variants of this type; those are not zeroed.
610                    //
611                    // Returning a value with value-dependent padding will instead trigger a lint.
612                    let ret_layout = self.fn_abi.ret.layout;
613                    let uninit_ranges = ret_layout.padding_ranges(bx.cx());
614                    self.zero_byte_ranges(bx, llslot, ret_layout.size, &uninit_ranges);
615                }
616
617                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
618            }
619        };
620        bx.ret(llval);
621    }
622
623    #[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("codegen_drop_terminator",
                                    "rustc_codegen_ssa::mir::block", ::tracing::Level::TRACE,
                                    ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                    ::tracing_core::__macro_support::Option::Some(623u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                    ::tracing_core::field::FieldSet::new(&["source_info",
                                                    "location", "target", "unwind", "mergeable_succ"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::TRACE <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                let mut iter = meta.fields().iter();
                                meta.fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&source_info)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&location)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&target)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&::tracing::field::debug(&unwind)
                                                            as &dyn Value)),
                                                (&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                    ::tracing::__macro_support::Option::Some(&mergeable_succ as
                                                            &dyn Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: MergingSucc = loop {};
            return __tracing_attr_fake_return;
        }
        {
            let ty = location.ty(self.mir, bx.tcx()).ty;
            let ty = self.monomorphize(ty);
            let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
            if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) =
                    drop_fn.def {
                return helper.funclet_br(self, bx, target, mergeable_succ,
                        &[]);
            }
            let place = self.codegen_place(bx, location.as_ref());
            let (args1, args2);
            let mut args =
                if let Some(llextra) = place.val.llextra {
                    args2 = [place.val.llval, llextra];
                    &args2[..]
                } else { args1 = [place.val.llval]; &args1[..] };
            let (maybe_null, drop_fn, fn_abi, drop_instance) =
                match ty.kind() {
                    ty::Dynamic(_, _) => {
                        let virtual_drop =
                            Instance {
                                def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0),
                                args: drop_fn.args,
                            };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:672",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(672u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("ty = {0:?}",
                                                                            ty) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:673",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(673u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("drop_fn = {0:?}",
                                                                            drop_fn) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        {
                            use ::tracing::__macro_support::Callsite as _;
                            static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                {
                                    static META: ::tracing::Metadata<'static> =
                                        {
                                            ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:674",
                                                "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                                                ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                                                ::tracing_core::__macro_support::Option::Some(674u32),
                                                ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                                                ::tracing_core::field::FieldSet::new(&["message"],
                                                    ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                ::tracing::metadata::Kind::EVENT)
                                        };
                                    ::tracing::callsite::DefaultCallsite::new(&META)
                                };
                            let enabled =
                                ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                        ::tracing::Level::DEBUG <=
                                            ::tracing::level_filters::LevelFilter::current() &&
                                    {
                                        let interest = __CALLSITE.interest();
                                        !interest.is_never() &&
                                            ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                interest)
                                    };
                            if enabled {
                                (|value_set: ::tracing::field::ValueSet|
                                            {
                                                let meta = __CALLSITE.metadata();
                                                ::tracing::Event::dispatch(meta, &value_set);
                                                ;
                                            })({
                                        #[allow(unused_imports)]
                                        use ::tracing::field::{debug, display, Value};
                                        let mut iter = __CALLSITE.metadata().fields().iter();
                                        __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                                            ::tracing::__macro_support::Option::Some(&format_args!("args = {0:?}",
                                                                            args) as &dyn Value))])
                                    });
                            } else { ; }
                        };
                        let fn_abi =
                            bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
                        let vtable = args[1];
                        args = &args[..1];
                        (true,
                            meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE).get_optional_fn(bx,
                                vtable, ty, fn_abi), fn_abi, virtual_drop)
                    }
                    _ =>
                        (false,
                            bx.get_fn_addr(drop_fn, Some(PacMetadata::default())),
                            bx.fn_abi_of_instance(drop_fn, ty::List::empty()), drop_fn),
                };
            if maybe_null {
                let is_not_null = bx.append_sibling_block("is_not_null");
                let llty = bx.fn_ptr_backend_type(fn_abi);
                let null = bx.const_null(llty);
                let non_null =
                    bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne,
                            false), drop_fn, null);
                bx.cond_br(non_null, is_not_null,
                    helper.llbb_with_cleanup(self, target));
                bx.switch_to_block(is_not_null);
                self.set_debug_loc(bx, *source_info);
            }
            helper.do_call(self, bx, fn_abi, drop_fn, args,
                Some((ReturnDest::Nothing, target)), unwind, &[],
                Some(drop_instance), CallKind::Normal,
                !maybe_null && mergeable_succ)
        }
    }
}#[tracing::instrument(level = "trace", skip(self, helper, bx))]
624    fn codegen_drop_terminator(
625        &mut self,
626        helper: TerminatorCodegenHelper<'tcx>,
627        bx: &mut Bx,
628        source_info: &mir::SourceInfo,
629        location: mir::Place<'tcx>,
630        target: mir::BasicBlock,
631        unwind: mir::UnwindAction,
632        mergeable_succ: bool,
633    ) -> MergingSucc {
634        let ty = location.ty(self.mir, bx.tcx()).ty;
635        let ty = self.monomorphize(ty);
636        let drop_fn = Instance::resolve_drop_glue(bx.tcx(), ty);
637
638        if let ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) = drop_fn.def {
639            // we don't actually need to drop anything.
640            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
641        }
642
643        let place = self.codegen_place(bx, location.as_ref());
644        let (args1, args2);
645        let mut args = if let Some(llextra) = place.val.llextra {
646            args2 = [place.val.llval, llextra];
647            &args2[..]
648        } else {
649            args1 = [place.val.llval];
650            &args1[..]
651        };
652        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
653            // FIXME(eddyb) perhaps move some of this logic into
654            // `Instance::resolve_drop_glue`?
655            ty::Dynamic(_, _) => {
656                // IN THIS ARM, WE HAVE:
657                // ty = *mut (dyn Trait)
658                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
659                //                       args[0]    args[1]
660                //
661                // args = ( Data, Vtable )
662                //                  |
663                //                  v
664                //                /-------\
665                //                | ...   |
666                //                \-------/
667                //
668                let virtual_drop = Instance {
669                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
670                    args: drop_fn.args,
671                };
672                debug!("ty = {:?}", ty);
673                debug!("drop_fn = {:?}", drop_fn);
674                debug!("args = {:?}", args);
675                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
676                let vtable = args[1];
677                // Truncate vtable off of args list
678                args = &args[..1];
679                (
680                    true,
681                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
682                        .get_optional_fn(bx, vtable, ty, fn_abi),
683                    fn_abi,
684                    virtual_drop,
685                )
686            }
687            _ => (
688                false,
689                bx.get_fn_addr(drop_fn, Some(PacMetadata::default())),
690                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
691                drop_fn,
692            ),
693        };
694
695        // We generate a null check for the drop_fn. This saves a bunch of relocations being
696        // generated for no-op drops.
697        if maybe_null {
698            let is_not_null = bx.append_sibling_block("is_not_null");
699            let llty = bx.fn_ptr_backend_type(fn_abi);
700            let null = bx.const_null(llty);
701            let non_null =
702                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
703            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
704            bx.switch_to_block(is_not_null);
705            self.set_debug_loc(bx, *source_info);
706        }
707
708        helper.do_call(
709            self,
710            bx,
711            fn_abi,
712            drop_fn,
713            args,
714            Some((ReturnDest::Nothing, target)),
715            unwind,
716            &[],
717            Some(drop_instance),
718            CallKind::Normal,
719            !maybe_null && mergeable_succ,
720        )
721    }
722
723    fn codegen_assert_terminator(
724        &mut self,
725        helper: TerminatorCodegenHelper<'tcx>,
726        bx: &mut Bx,
727        terminator: &mir::Terminator<'tcx>,
728        cond: &mir::Operand<'tcx>,
729        expected: bool,
730        msg: &mir::AssertMessage<'tcx>,
731        target: mir::BasicBlock,
732        unwind: mir::UnwindAction,
733        mergeable_succ: bool,
734    ) -> MergingSucc {
735        let span = terminator.source_info.span;
736        let cond = self.codegen_operand(bx, cond).immediate();
737        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
738
739        // This case can currently arise only from functions marked
740        // with #[rustc_inherit_overflow_checks] and inlined from
741        // another crate (mostly core::num generic/#[inline] fns),
742        // while the current crate doesn't use overflow checks.
743        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
744            const_cond = Some(expected);
745        }
746
747        // Don't codegen the panic block if success if known.
748        if const_cond == Some(expected) {
749            return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
750        }
751
752        // Because we're branching to a panic block (either a `#[cold]` one
753        // or an inlined abort), there's no need to `expect` it.
754
755        // Create the failure block and the conditional branch to it.
756        let lltarget = helper.llbb_with_cleanup(self, target);
757        let panic_block = bx.append_sibling_block("panic");
758        if expected {
759            bx.cond_br(cond, lltarget, panic_block);
760        } else {
761            bx.cond_br(cond, panic_block, lltarget);
762        }
763
764        // After this point, bx is the block for the call to panic.
765        bx.switch_to_block(panic_block);
766        self.set_debug_loc(bx, terminator.source_info);
767
768        // Get the location information.
769        let location = self.get_caller_location(bx, terminator.source_info).immediate();
770
771        // Put together the arguments to the panic entry point.
772        let (lang_item, args) = match msg {
773            AssertKind::BoundsCheck { len, index } => {
774                let len = self.codegen_operand(bx, len).immediate();
775                let index = self.codegen_operand(bx, index).immediate();
776                // It's `fn panic_bounds_check(index: usize, len: usize)`,
777                // and `#[track_caller]` adds an implicit third argument.
778                (LangItem::PanicBoundsCheck, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [index, len, location]))vec![index, len, location])
779            }
780            AssertKind::MisalignedPointerDereference { required, found } => {
781                let required = self.codegen_operand(bx, required).immediate();
782                let found = self.codegen_operand(bx, found).immediate();
783                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
784                // and `#[track_caller]` adds an implicit third argument.
785                (LangItem::PanicMisalignedPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [required, found, location]))vec![required, found, location])
786            }
787            AssertKind::NullPointerDereference => {
788                // It's `fn panic_null_pointer_dereference()`,
789                // `#[track_caller]` adds an implicit argument.
790                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
791            }
792            AssertKind::InvalidEnumConstruction(source) => {
793                let source = self.codegen_operand(bx, source).immediate();
794                // It's `fn panic_invalid_enum_construction(source: u128)`,
795                // `#[track_caller]` adds an implicit argument.
796                (LangItem::PanicInvalidEnumConstruction, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [source, location]))vec![source, location])
797            }
798            _ => {
799                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
800                (msg.panic_function(), ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
801            }
802        };
803
804        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
805
806        // Codegen the actual panic invoke/call.
807        let merging_succ = helper.do_call(
808            self,
809            bx,
810            fn_abi,
811            llfn,
812            &args,
813            None,
814            unwind,
815            &[],
816            Some(instance),
817            CallKind::Normal,
818            false,
819        );
820        {
    match (&merging_succ, &MergingSucc::False) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(merging_succ, MergingSucc::False);
821        MergingSucc::False
822    }
823
824    fn codegen_terminate_terminator(
825        &mut self,
826        helper: TerminatorCodegenHelper<'tcx>,
827        bx: &mut Bx,
828        terminator: &mir::Terminator<'tcx>,
829        reason: UnwindTerminateReason,
830    ) {
831        let span = terminator.source_info.span;
832        self.set_debug_loc(bx, terminator.source_info);
833
834        // Obtain the panic entry point.
835        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
836
837        // Codegen the actual panic invoke/call.
838        let merging_succ = helper.do_call(
839            self,
840            bx,
841            fn_abi,
842            llfn,
843            &[],
844            None,
845            mir::UnwindAction::Unreachable,
846            &[],
847            Some(instance),
848            CallKind::Normal,
849            false,
850        );
851        {
    match (&merging_succ, &MergingSucc::False) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(merging_succ, MergingSucc::False);
852    }
853
854    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
855    fn codegen_panic_intrinsic(
856        &mut self,
857        helper: &TerminatorCodegenHelper<'tcx>,
858        bx: &mut Bx,
859        intrinsic: ty::IntrinsicDef,
860        instance: Instance<'tcx>,
861        source_info: mir::SourceInfo,
862        target: Option<mir::BasicBlock>,
863        unwind: mir::UnwindAction,
864        mergeable_succ: bool,
865    ) -> Option<MergingSucc> {
866        // Emit a panic or a no-op for `assert_*` intrinsics.
867        // These are intrinsics that compile to panics so that we can get a message
868        // which mentions the offending type, even from a const context.
869        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
870            return None;
871        };
872
873        let ty = instance.args.type_at(0);
874
875        let is_valid = bx
876            .tcx()
877            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
878            .expect("expect to have layout during codegen");
879
880        if is_valid {
881            // a NOP
882            let target = target.unwrap();
883            return Some(helper.funclet_br(self, bx, target, mergeable_succ, &[]));
884        }
885
886        let layout = bx.layout_of(ty);
887
888        let msg_str = {
    let _guard = NoVisibleGuard::new();
    {
        {
            let _guard = NoTrimmedGuard::new();
            {
                if layout.is_uninhabited() {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to instantiate uninhabited type `{0}`",
                                    ty))
                        })
                } else if requirement == ValidityRequirement::Zero {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to zero-initialize type `{0}`, which is invalid",
                                    ty))
                        })
                } else {
                    ::alloc::__export::must_use({
                            ::alloc::fmt::format(format_args!("attempted to leave type `{0}` uninitialized, which is invalid",
                                    ty))
                        })
                }
            }
        }
    }
}with_no_visible_paths!({
889            with_no_trimmed_paths!({
890                if layout.is_uninhabited() {
891                    // Use this error even for the other intrinsics as it is more precise.
892                    format!("attempted to instantiate uninhabited type `{ty}`")
893                } else if requirement == ValidityRequirement::Zero {
894                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
895                } else {
896                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
897                }
898            })
899        });
900        let msg = bx.const_str(&msg_str);
901
902        // Obtain the panic entry point.
903        let (fn_abi, llfn, instance) =
904            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
905
906        // Codegen the actual panic invoke/call.
907        Some(helper.do_call(
908            self,
909            bx,
910            fn_abi,
911            llfn,
912            &[msg.0, msg.1],
913            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
914            unwind,
915            &[],
916            Some(instance),
917            CallKind::Normal,
918            mergeable_succ,
919        ))
920    }
921
922    fn codegen_call_terminator(
923        &mut self,
924        helper: TerminatorCodegenHelper<'tcx>,
925        bx: &mut Bx,
926        terminator: &mir::Terminator<'tcx>,
927        func: &mir::Operand<'tcx>,
928        args: &[Spanned<mir::Operand<'tcx>>],
929        destination: mir::Place<'tcx>,
930        target: Option<mir::BasicBlock>,
931        unwind: mir::UnwindAction,
932        fn_span: Span,
933        kind: CallKind,
934        mergeable_succ: bool,
935    ) -> MergingSucc {
936        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
937
938        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
939        let callee = self.codegen_operand(bx, func);
940
941        let (instance, mut llfn) = match *callee.layout.ty.kind() {
942            ty::FnDef(def_id, generic_args) => {
943                let instance = ty::Instance::expect_resolve(
944                    bx.tcx(),
945                    bx.typing_env(),
946                    def_id,
947                    generic_args,
948                    fn_span,
949                );
950
951                match instance.def {
952                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
953                    // it is `func returning noop future`
954                    ty::InstanceKind::Shim(ty::ShimKind::DropGlue(_, None)) => {
955                        // Empty drop glue; a no-op.
956                        let target = target.unwrap();
957                        return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
958                    }
959                    ty::InstanceKind::Intrinsic(def_id) => {
960                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
961                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
962                            &helper,
963                            bx,
964                            intrinsic,
965                            instance,
966                            source_info,
967                            target,
968                            unwind,
969                            mergeable_succ,
970                        ) {
971                            return merging_succ;
972                        }
973
974                        let result_layout =
975                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
976
977                        let (result_place, store_in_local) =
978                            if let Some(local) = destination.as_local() {
979                                match self.locals[local] {
980                                    LocalRef::Place(dest) => (Some(dest.val), None),
981                                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
982                                    LocalRef::PendingOperand => (None, Some(local)),
983                                    LocalRef::Operand(_) => {
984                                        if result_layout.is_zst() {
985                                            let place = PlaceRef::new_sized(
986                                                bx.const_undef(bx.type_ptr()),
987                                                result_layout,
988                                            );
989                                            (Some(place.val), None)
990                                        } else {
991                                            ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
992                                        }
993                                    }
994                                }
995                            } else {
996                                (Some(self.codegen_place(bx, destination.as_ref()).val), None)
997                            };
998
999                        if let Some(place) = result_place
1000                            && place.align < result_layout.align.abi
1001                        {
1002                            // Currently, MIR code generation does not create calls
1003                            // that store directly to fields of packed structs (in
1004                            // fact, the calls it creates write only to temps).
1005                            //
1006                            // If someone changes that, please update this code path
1007                            // to create a temporary.
1008                            ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
1009                        }
1010
1011                        let args: Vec<_> =
1012                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
1013
1014                        let intrinsic_result = self.codegen_intrinsic_call(
1015                            bx,
1016                            instance,
1017                            &args,
1018                            result_layout,
1019                            result_place,
1020                            source_info,
1021                        );
1022
1023                        if let IntrinsicResult::Operand(op_val) = intrinsic_result {
1024                            match (result_place, store_in_local) {
1025                                (None, Some(local)) => {
1026                                    let op = OperandRef {
1027                                        val: op_val,
1028                                        layout: result_layout,
1029                                        move_annotation: None,
1030                                    };
1031                                    self.overwrite_local(local, LocalRef::Operand(op));
1032                                    self.debug_introduce_local(bx, local);
1033                                }
1034                                (Some(place_val), None) => {
1035                                    let dest = PlaceRef { val: place_val, layout: result_layout };
1036                                    op_val.store(bx, dest);
1037                                }
1038                                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
1039                            }
1040                        }
1041
1042                        match intrinsic_result {
1043                            IntrinsicResult::Operand(_) | IntrinsicResult::WroteIntoPlace => {
1044                                return if let Some(target) = target {
1045                                    helper.funclet_br(self, bx, target, mergeable_succ, &[])
1046                                } else {
1047                                    bx.unreachable();
1048                                    MergingSucc::False
1049                                };
1050                            }
1051                            IntrinsicResult::Err(_) => {
1052                                // Even though we're definitely going to error, we need it initialize
1053                                // the local or `maybe_codegen_consume_direct` might ICE later
1054                                // when it goes to use the result from this intrinsic.
1055                                if let Some(local) = store_in_local {
1056                                    let op = OperandRef {
1057                                        val: OperandValue::poison(bx, result_layout),
1058                                        layout: result_layout,
1059                                        move_annotation: None,
1060                                    };
1061                                    self.overwrite_local(local, LocalRef::Operand(op));
1062                                }
1063                                // Also we need to terminate the block to avoid an LLVM assertion,
1064                                // even though we're not going to actually use the IR.
1065                                bx.abort();
1066                                return MergingSucc::False;
1067                            }
1068                            IntrinsicResult::Fallback(instance) => {
1069                                if intrinsic.must_be_overridden {
1070                                    ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("intrinsic {0} must be overridden by codegen backend, but isn\'t",
        intrinsic.name));span_bug!(
1071                                        fn_span,
1072                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1073                                        intrinsic.name,
1074                                    );
1075                                }
1076                                (Some(instance), None)
1077                            }
1078                        }
1079                    }
1080
1081                    _ if kind == CallKind::Tail
1082                        && instance.def.requires_caller_location(bx.tcx()) =>
1083                    {
1084                        if let Some(hir_id) =
1085                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1086                        {
1087                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1088                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1089                            }));
1090                        }
1091
1092                        let instance = ty::Instance::resolve_for_fn_ptr(
1093                            bx.tcx(),
1094                            bx.typing_env(),
1095                            def_id,
1096                            generic_args,
1097                        )
1098                        .unwrap();
1099
1100                        (None, Some(bx.get_fn_addr(instance, Some(PacMetadata::default()))))
1101                    }
1102                    _ => (Some(instance), None),
1103                }
1104            }
1105            ty::FnPtr(..) => (None, Some(callee.immediate())),
1106            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} is not callable",
        callee.layout.ty))bug!("{} is not callable", callee.layout.ty),
1107        };
1108
1109        if let Some(instance) = instance
1110            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1111            && name.as_str().starts_with("llvm.")
1112            // This is the only LLVM intrinsic we use that unwinds
1113            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1114            // this intrinsic with something else
1115            && name.as_str() != "llvm.wasm.throw"
1116        {
1117            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1118            if !!instance.args.has_escaping_bound_vars() {
    ::core::panicking::panic("assertion failed: !instance.args.has_escaping_bound_vars()")
};assert!(!instance.args.has_escaping_bound_vars());
1119
1120            let result_layout =
1121                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1122
1123            let return_dest = if result_layout.is_zst() {
1124                ReturnDest::Nothing
1125            } else if let Some(index) = destination.as_local() {
1126                match self.locals[index] {
1127                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1128                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
1129                    LocalRef::PendingOperand => {
1130                        // Handle temporary places, specifically `Operand` ones, as
1131                        // they don't have `alloca`s.
1132                        ReturnDest::DirectOperand(index)
1133                    }
1134                    LocalRef::Operand(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"))bug!("place local already assigned to"),
1135                }
1136            } else {
1137                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1138            };
1139
1140            let args =
1141                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1142
1143            self.set_debug_loc(bx, source_info);
1144
1145            let llret =
1146                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1147
1148            if let Some(target) = target {
1149                self.store_return(
1150                    bx,
1151                    return_dest,
1152                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1153                    llret,
1154                );
1155                return helper.funclet_br(self, bx, target, mergeable_succ, &[]);
1156            } else {
1157                bx.unreachable();
1158                return MergingSucc::False;
1159            }
1160        }
1161
1162        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1163        // available - right now `sig` is only needed for getting the `abi`
1164        // and figuring out how many extra args were passed to a C-variadic `fn`.
1165        let sig = callee.layout.ty.fn_sig(bx.tcx());
1166
1167        let extra_args = &args[sig.inputs().skip_binder().len()..];
1168        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1169            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1170            self.monomorphize(op_ty)
1171        }));
1172
1173        let fn_abi = match instance {
1174            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1175            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1176        };
1177
1178        // The arguments we'll be passing. Plus one to account for outptr, if used.
1179        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1180
1181        let mut llargs = Vec::with_capacity(arg_count);
1182
1183        // We still need to call `make_return_dest` even if there's no `target`, since
1184        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1185        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1186        let destination = match kind {
1187            CallKind::Normal => {
1188                let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1189                target.map(|target| (return_dest, target))
1190            }
1191            CallKind::Tail => {
1192                if fn_abi.ret.is_indirect() {
1193                    match self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs) {
1194                        ReturnDest::Nothing => {}
1195                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("tail calls to functions with indirect returns cannot store into a destination"))bug!(
1196                            "tail calls to functions with indirect returns cannot store into a destination"
1197                        ),
1198                    }
1199                }
1200                None
1201            }
1202        };
1203
1204        // Split the rust-call tupled arguments off.
1205        // FIXME(splat): un-tuple splatted arguments in codegen, for performance
1206        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1207            && let Some((tup, args)) = args.split_last()
1208        {
1209            (args, Some(tup))
1210        } else {
1211            (args, None)
1212        };
1213
1214        // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1215        //
1216        // Normally an indirect argument that is allocated in the caller's stack frame
1217        // would be passed as a pointer into the callee's stack frame.
1218        // For tail calls, that would be unsound, because the caller's
1219        // stack frame is overwritten by the callee's stack frame.
1220        //
1221        // Therefore we store the argument for the callee in the corresponding caller's slot.
1222        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1223        // the corresponding slot has the correct type.
1224        //
1225        // To handle cases like the one below, the tail call arguments must first be copied to a
1226        // temporary, and only then copied to the caller's argument slots.
1227        //
1228        // ```
1229        // // A struct big enough that it is not passed via registers.
1230        // pub struct Big([u64; 4]);
1231        //
1232        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1233        //     become swapper_helper(b, a);
1234        // }
1235        // ```
1236        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1237        if kind == CallKind::Tail {
1238            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1239            // Copy the arguments that use `PassMode::Indirect { on_stack: false , ..}`
1240            // to temporary stack allocations. See the comment above.
1241            for (i, arg) in first_args.iter().enumerate() {
1242                if !#[allow(non_exhaustive_omitted_patterns)] match fn_abi.args[i].mode {
    PassMode::Indirect { on_stack: false, .. } => true,
    _ => false,
}matches!(fn_abi.args[i].mode, PassMode::Indirect { on_stack: false, .. }) {
1243                    continue;
1244                }
1245
1246                let op = self.codegen_operand(bx, &arg.node);
1247                let tmp = PlaceRef::alloca(bx, op.layout);
1248                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1249                op.store_with_annotation(bx, tmp);
1250
1251                tail_call_temporaries[i] = Some(tmp);
1252            }
1253        }
1254
1255        // When generating arguments we sometimes introduce temporary allocations with lifetime
1256        // that extend for the duration of a call. Keep track of those allocations and their sizes
1257        // to generate `lifetime_end` when the call returns.
1258        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1259        'make_args: for (i, arg) in first_args.iter().enumerate() {
1260            let mut op = self.codegen_operand(bx, &arg.node);
1261
1262            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1263                match op.val {
1264                    Pair(data_ptr, meta) => {
1265                        // In the case of Rc<Self>, we need to explicitly pass a
1266                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1267                        // that is understood elsewhere in the compiler as a method on
1268                        // `dyn Trait`.
1269                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1270                        // we get a value of a built-in pointer type.
1271                        //
1272                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1273                        // `Pin`.
1274                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1275                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1276                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1277                            );
1278                            op = op.extract_field(self, bx, idx.as_usize());
1279                        }
1280
1281                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1282                        // data pointer and vtable. Look up the method in the vtable, and pass
1283                        // the data pointer as the first argument.
1284                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1285                            bx,
1286                            meta,
1287                            op.layout.ty,
1288                            fn_abi,
1289                        ));
1290                        llargs.push(data_ptr);
1291                        continue 'make_args;
1292                    }
1293                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1294                        // by-value dynamic dispatch
1295                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1296                            bx,
1297                            meta,
1298                            op.layout.ty,
1299                            fn_abi,
1300                        ));
1301                        llargs.push(data_ptr);
1302                        continue;
1303                    }
1304                    _ => {
1305                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("can\'t codegen a virtual call on {0:#?}", op));span_bug!(fn_span, "can't codegen a virtual call on {:#?}", op);
1306                    }
1307                }
1308            }
1309
1310            let by_move = if let PassMode::Indirect { on_stack: false, .. } = fn_abi.args[i].mode
1311                && kind == CallKind::Tail
1312            {
1313                // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1314                //
1315                // Normally an indirect argument that is allocated in the caller's stack frame
1316                // would be passed as a pointer into the callee's stack frame.
1317                // For tail calls, that would be unsound, because the caller's
1318                // stack frame is overwritten by the callee's stack frame.
1319                //
1320                // To handle the case, we introduce `tail_call_temporaries` to copy arguments into
1321                // temporaries, then copy back to the caller's argument slots.
1322                // Finally, we pass the caller's argument slots as arguments.
1323                //
1324                // To do that, the argument must be MUST-by-move value.
1325                let Some(tmp) = tail_call_temporaries[i].take() else {
1326                    ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("missing temporary for indirect tail call argument #{0}", i))span_bug!(fn_span, "missing temporary for indirect tail call argument #{i}")
1327                };
1328
1329                let local = self.mir.args_iter().nth(i).unwrap();
1330
1331                match &self.locals[local] {
1332                    LocalRef::Place(arg) => {
1333                        bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1334                        op.val = Ref(arg.val);
1335                    }
1336                    LocalRef::Operand(arg) => {
1337                        let Ref(place_value) = arg.val else {
1338                            ::rustc_middle::util::bug::bug_fmt(format_args!("only `Ref` should use `PassMode::Indirect`, but got {0:?}",
        arg.val));bug!(
1339                                "only `Ref` should use `PassMode::Indirect`, but got {:?}",
1340                                arg.val
1341                            );
1342                        };
1343                        bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1344                        op.val = arg.val;
1345                    }
1346                    LocalRef::UnsizedPlace(_) => {
1347                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("unsized types are not supported"))span_bug!(fn_span, "unsized types are not supported")
1348                    }
1349                    LocalRef::PendingOperand => {
1350                        ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("argument local should not be pending"))span_bug!(fn_span, "argument local should not be pending")
1351                    }
1352                };
1353
1354                bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1355                true
1356            } else {
1357                #[allow(non_exhaustive_omitted_patterns)] match arg.node {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(arg.node, mir::Operand::Move(_))
1358            };
1359
1360            self.codegen_argument(
1361                bx,
1362                fn_abi.conv,
1363                op,
1364                by_move,
1365                &mut llargs,
1366                &fn_abi.args[i],
1367                &mut lifetime_ends_after_call,
1368            );
1369        }
1370        let num_untupled = untuple.map(|tup| {
1371            self.codegen_arguments_untupled(
1372                bx,
1373                fn_abi.conv,
1374                &tup.node,
1375                &mut llargs,
1376                &fn_abi.args[first_args.len()..],
1377                &mut lifetime_ends_after_call,
1378            )
1379        });
1380
1381        let needs_location =
1382            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1383        if needs_location {
1384            let mir_args = if let Some(num_untupled) = num_untupled {
1385                first_args.len() + num_untupled
1386            } else {
1387                args.len()
1388            };
1389            {
    match (&fn_abi.args.len(), &(mir_args + 1)) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("#[track_caller] fn\'s must have 1 more argument in their ABI than in their MIR: {0:?} {1:?} {2:?}",
                            instance, fn_span, fn_abi)));
            }
        }
    }
};assert_eq!(
1390                fn_abi.args.len(),
1391                mir_args + 1,
1392                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1393            );
1394            let location = self.get_caller_location(bx, source_info);
1395            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1395",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1395u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_call_terminator({0:?}): location={1:?} (fn_span {2:?})",
                                                    terminator, location, fn_span) as &dyn Value))])
            });
    } else { ; }
};debug!(
1396                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1397                terminator, location, fn_span
1398            );
1399
1400            let last_arg = fn_abi.args.last().unwrap();
1401            self.codegen_argument(
1402                bx,
1403                fn_abi.conv,
1404                location,
1405                /* by_move */ false,
1406                &mut llargs,
1407                last_arg,
1408                &mut lifetime_ends_after_call,
1409            );
1410        }
1411
1412        let fn_ptr = match (instance, llfn) {
1413            (Some(instance), None) => bx.get_fn_addr(instance, Some(PacMetadata::default())),
1414            (_, Some(llfn)) => llfn,
1415            _ => ::rustc_middle::util::bug::span_bug_fmt(fn_span,
    format_args!("no instance or llfn for call"))span_bug!(fn_span, "no instance or llfn for call"),
1416        };
1417        self.set_debug_loc(bx, source_info);
1418        helper.do_call(
1419            self,
1420            bx,
1421            fn_abi,
1422            fn_ptr,
1423            &llargs,
1424            destination,
1425            unwind,
1426            &lifetime_ends_after_call,
1427            instance,
1428            kind,
1429            mergeable_succ,
1430        )
1431    }
1432
1433    fn codegen_asm_terminator(
1434        &mut self,
1435        helper: TerminatorCodegenHelper<'tcx>,
1436        bx: &mut Bx,
1437        asm_macro: InlineAsmMacro,
1438        terminator: &mir::Terminator<'tcx>,
1439        template: &[ast::InlineAsmTemplatePiece],
1440        operands: &[mir::InlineAsmOperand<'tcx>],
1441        options: ast::InlineAsmOptions,
1442        line_spans: &[Span],
1443        targets: &[mir::BasicBlock],
1444        unwind: mir::UnwindAction,
1445        instance: Instance<'_>,
1446        mergeable_succ: bool,
1447    ) -> MergingSucc {
1448        let span = terminator.source_info.span;
1449
1450        let operands: Vec<_> = operands
1451            .iter()
1452            .map(|op| match *op {
1453                mir::InlineAsmOperand::In { reg, ref value } => {
1454                    let value = self.codegen_operand(bx, value);
1455                    InlineAsmOperandRef::In { reg, value }
1456                }
1457                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1458                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1459                    InlineAsmOperandRef::Out { reg, late, place }
1460                }
1461                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1462                    let in_value = self.codegen_operand(bx, in_value);
1463                    let out_place =
1464                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1465                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1466                }
1467                mir::InlineAsmOperand::Const { ref value } => {
1468                    let const_value = self.eval_mir_constant(value);
1469                    let string = common::asm_const_to_str(
1470                        bx.tcx(),
1471                        span,
1472                        const_value,
1473                        bx.layout_of(value.ty()),
1474                    );
1475                    InlineAsmOperandRef::Const { string }
1476                }
1477                mir::InlineAsmOperand::SymFn { ref value } => {
1478                    let const_ = self.monomorphize(value.const_);
1479                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1480                        let instance = ty::Instance::resolve_for_fn_ptr(
1481                            bx.tcx(),
1482                            bx.typing_env(),
1483                            def_id,
1484                            args,
1485                        )
1486                        .unwrap();
1487                        InlineAsmOperandRef::SymFn { instance }
1488                    } else {
1489                        ::rustc_middle::util::bug::span_bug_fmt(span,
    format_args!("invalid type for asm sym (fn)"));span_bug!(span, "invalid type for asm sym (fn)");
1490                    }
1491                }
1492                mir::InlineAsmOperand::SymStatic { def_id } => {
1493                    InlineAsmOperandRef::SymStatic { def_id }
1494                }
1495                mir::InlineAsmOperand::Label { target_index } => {
1496                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1497                }
1498            })
1499            .collect();
1500
1501        helper.do_inlineasm(
1502            self,
1503            bx,
1504            template,
1505            &operands,
1506            options,
1507            line_spans,
1508            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1509            unwind,
1510            instance,
1511            mergeable_succ,
1512        )
1513    }
1514
1515    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1516        let llbb = match self.try_llbb(bb) {
1517            Some(llbb) => llbb,
1518            None => return,
1519        };
1520        let bx = &mut Bx::build(self.cx, llbb);
1521        let mir = self.mir;
1522
1523        // MIR basic blocks stop at any function call. This may not be the case
1524        // for the backend's basic blocks, in which case we might be able to
1525        // combine multiple MIR basic blocks into a single backend basic block.
1526        loop {
1527            let data = &mir[bb];
1528
1529            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1529",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1529u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_block({0:?}={1:?})",
                                                    bb, data) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_block({:?}={:?})", bb, data);
1530
1531            for statement in &data.statements {
1532                self.codegen_statement(bx, statement);
1533            }
1534            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1535
1536            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1537            if let MergingSucc::False = merging_succ {
1538                break;
1539            }
1540
1541            // We are merging the successor into the produced backend basic
1542            // block. Record that the successor should be skipped when it is
1543            // reached.
1544            //
1545            // Note: we must not have already generated code for the successor.
1546            // This is implicitly ensured by the reverse postorder traversal,
1547            // and the assertion explicitly guarantees that.
1548            let mut successors = data.terminator().successors();
1549            let succ = successors.next().unwrap();
1550            if !#[allow(non_exhaustive_omitted_patterns)] match self.cached_llbbs[succ] {
            CachedLlbb::None => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(self.cached_llbbs[succ], CachedLlbb::None)")
};assert!(matches!(self.cached_llbbs[succ], CachedLlbb::None));
1551            self.cached_llbbs[succ] = CachedLlbb::Skip;
1552            bb = succ;
1553        }
1554    }
1555
1556    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1557        let llbb = match self.try_llbb(bb) {
1558            Some(llbb) => llbb,
1559            None => return,
1560        };
1561        let bx = &mut Bx::build(self.cx, llbb);
1562        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1562",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1562u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_block_as_unreachable({0:?})",
                                                    bb) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_block_as_unreachable({:?})", bb);
1563        bx.unreachable();
1564    }
1565
1566    fn codegen_terminator(
1567        &mut self,
1568        bx: &mut Bx,
1569        bb: mir::BasicBlock,
1570        terminator: &'tcx mir::Terminator<'tcx>,
1571    ) -> MergingSucc {
1572        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/mir/block.rs:1572",
                        "rustc_codegen_ssa::mir::block", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/mir/block.rs"),
                        ::tracing_core::__macro_support::Option::Some(1572u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir::block"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("codegen_terminator: {0:?}",
                                                    terminator) as &dyn Value))])
            });
    } else { ; }
};debug!("codegen_terminator: {:?}", terminator);
1573
1574        let helper = TerminatorCodegenHelper { bb, terminator };
1575
1576        let mergeable_succ = || {
1577            // Note: any call to `switch_to_block` will invalidate a `true` value
1578            // of `mergeable_succ`.
1579            let mut successors = terminator.successors();
1580            if let Some(succ) = successors.next()
1581                && successors.next().is_none()
1582                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1583            {
1584                // bb has a single successor, and bb is its only predecessor. This
1585                // makes it a candidate for merging.
1586                {
    match (&succ_pred, &bb) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(succ_pred, bb);
1587                true
1588            } else {
1589                false
1590            }
1591        };
1592
1593        self.set_debug_loc(bx, terminator.source_info);
1594        match terminator.kind {
1595            mir::TerminatorKind::UnwindResume => {
1596                self.codegen_resume_terminator(helper, bx);
1597                MergingSucc::False
1598            }
1599
1600            mir::TerminatorKind::UnwindTerminate(reason) => {
1601                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1602                MergingSucc::False
1603            }
1604
1605            mir::TerminatorKind::Goto { target } => {
1606                helper.funclet_br(self, bx, target, mergeable_succ(), &terminator.attributes)
1607            }
1608
1609            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1610                self.codegen_switchint_terminator(helper, bx, discr, targets);
1611                MergingSucc::False
1612            }
1613
1614            mir::TerminatorKind::Return => {
1615                self.codegen_return_terminator(bx);
1616                MergingSucc::False
1617            }
1618
1619            mir::TerminatorKind::Unreachable => {
1620                bx.unreachable();
1621                MergingSucc::False
1622            }
1623
1624            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop } => {
1625                if !drop.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1626                    drop.is_none(),
1627                    "Async Drop must be expanded or reset to sync before codegen"
1628                );
1629                self.codegen_drop_terminator(
1630                    helper,
1631                    bx,
1632                    &terminator.source_info,
1633                    place,
1634                    target,
1635                    unwind,
1636                    mergeable_succ(),
1637                )
1638            }
1639
1640            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1641                .codegen_assert_terminator(
1642                    helper,
1643                    bx,
1644                    terminator,
1645                    cond,
1646                    expected,
1647                    msg,
1648                    target,
1649                    unwind,
1650                    mergeable_succ(),
1651                ),
1652
1653            mir::TerminatorKind::Call {
1654                ref func,
1655                ref args,
1656                destination,
1657                target,
1658                unwind,
1659                call_source: _,
1660                fn_span,
1661            } => self.codegen_call_terminator(
1662                helper,
1663                bx,
1664                terminator,
1665                func,
1666                args,
1667                destination,
1668                target,
1669                unwind,
1670                fn_span,
1671                CallKind::Normal,
1672                mergeable_succ(),
1673            ),
1674            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1675                .codegen_call_terminator(
1676                    helper,
1677                    bx,
1678                    terminator,
1679                    func,
1680                    args,
1681                    mir::Place::from(mir::RETURN_PLACE),
1682                    None,
1683                    mir::UnwindAction::Unreachable,
1684                    fn_span,
1685                    CallKind::Tail,
1686                    mergeable_succ(),
1687                ),
1688            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1689                ::rustc_middle::util::bug::bug_fmt(format_args!("coroutine ops in codegen"))bug!("coroutine ops in codegen")
1690            }
1691            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1692                ::rustc_middle::util::bug::bug_fmt(format_args!("borrowck false edges in codegen"))bug!("borrowck false edges in codegen")
1693            }
1694
1695            mir::TerminatorKind::InlineAsm {
1696                asm_macro,
1697                template,
1698                ref operands,
1699                options,
1700                line_spans,
1701                ref targets,
1702                unwind,
1703            } => self.codegen_asm_terminator(
1704                helper,
1705                bx,
1706                asm_macro,
1707                terminator,
1708                template,
1709                operands,
1710                options,
1711                line_spans,
1712                targets,
1713                unwind,
1714                self.instance,
1715                mergeable_succ(),
1716            ),
1717        }
1718    }
1719
1720    fn zero_byte_ranges(
1721        &mut self,
1722        bx: &mut Bx,
1723        ptr: Bx::Value,
1724        limit: Size,
1725        ranges: &[Range<Size>],
1726    ) {
1727        let zero = bx.const_u8(0);
1728
1729        for range in ranges {
1730            let end = cmp::min(range.end, limit);
1731            if range.start >= end {
1732                continue;
1733            }
1734            let offset = bx.const_usize(range.start.bytes());
1735            let len = bx.const_usize((end - range.start).bytes());
1736            let ptr = bx.inbounds_ptradd(ptr, offset);
1737            bx.memset(ptr, zero, len, Align::ONE, MemFlags::empty());
1738        }
1739    }
1740
1741    fn codegen_argument(
1742        &mut self,
1743        bx: &mut Bx,
1744        conv: CanonAbi,
1745        op: OperandRef<'tcx, Bx::Value>,
1746        by_move: bool,
1747        llargs: &mut Vec<Bx::Value>,
1748        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1749        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1750    ) {
1751        match arg.mode {
1752            PassMode::Ignore => return,
1753            PassMode::Cast { pad_i32: true, .. } => {
1754                // Fill padding with undef value, where applicable.
1755                llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1756            }
1757            PassMode::Pair(..) => match op.val {
1758                Pair(a, b) => {
1759                    llargs.push(a);
1760                    llargs.push(b);
1761                    return;
1762                }
1763                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for pair argument",
        op))bug!("codegen_argument: {:?} invalid for pair argument", op),
1764            },
1765            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1766                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1767                    llargs.push(a);
1768                    llargs.push(b);
1769                    return;
1770                }
1771                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for unsized indirect argument",
        op))bug!("codegen_argument: {:?} invalid for unsized indirect argument", op),
1772            },
1773            _ => {}
1774        }
1775
1776        // Force by-ref if we have to load through a cast pointer.
1777        let (mut llval, align, by_ref) = match op.val {
1778            Immediate(_) | Pair(..) => match arg.mode {
1779                PassMode::Indirect { attrs, .. } => {
1780                    // Indirect argument may have higher alignment requirements than the type's
1781                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
1782                    // on the stack on x86.
1783                    let required_align = match attrs.pointee_align {
1784                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1785                        None => arg.layout.align.abi,
1786                    };
1787                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1788                    bx.lifetime_start(scratch.llval, arg.layout.size);
1789                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
1790                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1791                    (scratch.llval, scratch.align, true)
1792                }
1793                PassMode::Cast { .. } => {
1794                    let scratch = PlaceRef::alloca(bx, arg.layout);
1795                    op.store_with_annotation(bx, scratch);
1796                    (scratch.val.llval, scratch.val.align, true)
1797                }
1798                PassMode::Direct(_) => (op.immediate(), arg.layout.align.abi, false),
1799                PassMode::Ignore | PassMode::Pair(..) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("handled above")));
}unreachable!("handled above"),
1800            },
1801            Ref(op_place_val) => match arg.mode {
1802                PassMode::Indirect { attrs, on_stack, .. } => {
1803                    // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
1804                    // alignment requirements may be higher than the type's alignment, so copy
1805                    // to a higher-aligned alloca.
1806                    let required_align = match attrs.pointee_align {
1807                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1808                        None => arg.layout.align.abi,
1809                    };
1810                    // Copy to an alloca when the argument is neither by-val nor by-move.
1811                    if op_place_val.align < required_align || (!on_stack && !by_move) {
1812                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1813                        bx.lifetime_start(scratch.llval, arg.layout.size);
1814                        op.store_with_annotation(bx, scratch.with_type(arg.layout));
1815                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1816                        (scratch.llval, scratch.align, true)
1817                    } else {
1818                        (op_place_val.llval, op_place_val.align, true)
1819                    }
1820                }
1821                _ => (op_place_val.llval, op_place_val.align, true),
1822            },
1823            ZeroSized => match arg.mode {
1824                PassMode::Indirect { on_stack, .. } => {
1825                    if on_stack {
1826                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
1827                        // is here to replace a would-be untested codepath.
1828                        ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} passed on stack with abi {1:?}",
        op, arg));bug!("ZST {op:?} passed on stack with abi {arg:?}");
1829                    }
1830                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
1831                    // a pointer for `repr(C)` structs even when empty, so get
1832                    // one from an `alloca` (which can be left uninitialized).
1833                    let scratch = PlaceRef::alloca(bx, arg.layout);
1834                    (scratch.val.llval, scratch.val.align, true)
1835                }
1836                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("ZST {0:?} wasn\'t ignored, but was passed with abi {1:?}",
        op, arg))bug!("ZST {op:?} wasn't ignored, but was passed with abi {arg:?}"),
1837            },
1838        };
1839
1840        if by_ref && !arg.is_indirect() {
1841            // Have to load the argument, maybe while casting it.
1842            if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1843                // The ABI mandates that the value is passed as a different struct representation.
1844                // Spill and reload it from the stack to convert from the Rust representation to
1845                // the ABI representation.
1846                let scratch_size = cast.size(bx);
1847                let scratch_align = cast.align(bx);
1848                // Note that the ABI type may be either larger or smaller than the Rust type,
1849                // due to the presence or absence of trailing padding. For example:
1850                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
1851                //   when passed by value, making it smaller.
1852                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
1853                //   when passed by value, making it larger.
1854                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1855                // Allocate some scratch space...
1856                let llscratch = bx.alloca(scratch_size, scratch_align);
1857                bx.lifetime_start(llscratch, scratch_size);
1858                // ...memcpy the value...
1859                bx.memcpy(
1860                    llscratch,
1861                    scratch_align,
1862                    llval,
1863                    align,
1864                    bx.const_usize(copy_bytes),
1865                    MemFlags::empty(),
1866                    None,
1867                );
1868
1869                // The arguments of an `extern "cmse-nonsecure-call"` function cross the secure
1870                // boundary. Zero padding bytes so information does not leak.
1871                //
1872                // This only zeroes "guaranteed" padding. There may be more bytes that are
1873                // padding for some but not all variants of this type; those are not zeroed.
1874                //
1875                // Passing an argument with value-dependent padding will instead trigger a lint.
1876                if conv == CanonAbi::Arm(ArmCall::CCmseNonSecureCall) {
1877                    self.zero_byte_ranges(
1878                        bx,
1879                        llscratch,
1880                        Size::from_bytes(copy_bytes),
1881                        &arg.layout.padding_ranges(bx.cx()),
1882                    );
1883                }
1884
1885                // ...and then load it with the ABI type.
1886                llval = load_cast(bx, cast, llscratch, scratch_align);
1887                bx.lifetime_end(llscratch, scratch_size);
1888            } else {
1889                // We can't use `PlaceRef::load` here because the argument
1890                // may have a type we don't treat as immediate, but the ABI
1891                // used for this call is passing it by-value. In that case,
1892                // the load would just produce `OperandValue::Ref` instead
1893                // of the `OperandValue::Immediate` we need for the call.
1894                llval = bx.load(bx.backend_type(arg.layout), llval, align);
1895                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1896                    if scalar.is_bool() {
1897                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1898                    }
1899                    // We store bools as `i8` so we need to truncate to `i1`.
1900                    llval = bx.to_immediate_scalar(llval, scalar);
1901                }
1902            }
1903        }
1904
1905        llargs.push(llval);
1906    }
1907
1908    fn codegen_arguments_untupled(
1909        &mut self,
1910        bx: &mut Bx,
1911        conv: CanonAbi,
1912        operand: &mir::Operand<'tcx>,
1913        llargs: &mut Vec<Bx::Value>,
1914        args: &[ArgAbi<'tcx, Ty<'tcx>>],
1915        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1916    ) -> usize {
1917        let tuple = self.codegen_operand(bx, operand);
1918        let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(operand, mir::Operand::Move(_));
1919
1920        // Handle both by-ref and immediate tuples.
1921        if let Ref(place_val) = tuple.val {
1922            if place_val.llextra.is_some() {
1923                ::rustc_middle::util::bug::bug_fmt(format_args!("closure arguments must be sized"));bug!("closure arguments must be sized");
1924            }
1925            let tuple_ptr = place_val.with_type(tuple.layout);
1926            for i in 0..tuple.layout.fields.count() {
1927                let field_ptr = tuple_ptr.project_field(bx, i);
1928                let field = bx.load_operand(field_ptr);
1929                self.codegen_argument(
1930                    bx,
1931                    conv,
1932                    field,
1933                    by_move,
1934                    llargs,
1935                    &args[i],
1936                    lifetime_ends_after_call,
1937                );
1938            }
1939        } else {
1940            // If the tuple is immediate, the elements are as well.
1941            for i in 0..tuple.layout.fields.count() {
1942                let op = tuple.extract_field(self, bx, i);
1943                self.codegen_argument(
1944                    bx,
1945                    conv,
1946                    op,
1947                    by_move,
1948                    llargs,
1949                    &args[i],
1950                    lifetime_ends_after_call,
1951                );
1952            }
1953        }
1954        tuple.layout.fields.count()
1955    }
1956
1957    pub(super) fn get_caller_location(
1958        &mut self,
1959        bx: &mut Bx,
1960        source_info: mir::SourceInfo,
1961    ) -> OperandRef<'tcx, Bx::Value> {
1962        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1963            let const_loc = bx.tcx().span_as_caller_location(span);
1964            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1965        })
1966    }
1967
1968    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1969        let cx = bx.cx();
1970        if let Some(slot) = self.personality_slot {
1971            slot
1972        } else {
1973            let layout = cx.layout_of(Ty::new_tup(
1974                cx.tcx(),
1975                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1976            ));
1977            let slot = PlaceRef::alloca(bx, layout);
1978            self.personality_slot = Some(slot);
1979            slot
1980        }
1981    }
1982
1983    /// Returns the landing/cleanup pad wrapper around the given basic block.
1984    // FIXME(eddyb) rename this to `eh_pad_for`.
1985    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1986        if let Some(landing_pad) = self.landing_pads[bb] {
1987            return landing_pad;
1988        }
1989
1990        let landing_pad = self.landing_pad_for_uncached(bb);
1991        self.landing_pads[bb] = Some(landing_pad);
1992        landing_pad
1993    }
1994
1995    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1996    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1997        let llbb = self.llbb(bb);
1998        if base::wants_new_eh_instructions(self.cx.sess()) {
1999            let cleanup_bb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("funclet_{0:?}", bb))
    })format!("funclet_{bb:?}"));
2000            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
2001            let funclet = cleanup_bx.cleanup_pad(None, &[]);
2002            cleanup_bx.br(llbb);
2003            self.funclets[bb] = Some(funclet);
2004            cleanup_bb
2005        } else {
2006            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
2007            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
2008
2009            let llpersonality = self.cx.eh_personality();
2010            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
2011
2012            let slot = self.get_personality_slot(&mut cleanup_bx);
2013            slot.storage_live(&mut cleanup_bx);
2014            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
2015
2016            cleanup_bx.br(llbb);
2017            cleanup_llbb
2018        }
2019    }
2020
2021    fn unreachable_block(&mut self) -> Bx::BasicBlock {
2022        self.unreachable_block.unwrap_or_else(|| {
2023            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
2024            let mut bx = Bx::build(self.cx, llbb);
2025            bx.unreachable();
2026            self.unreachable_block = Some(llbb);
2027            llbb
2028        })
2029    }
2030
2031    fn terminate_block(
2032        &mut self,
2033        reason: UnwindTerminateReason,
2034        outer_catchpad_bb: Option<mir::BasicBlock>,
2035    ) -> Bx::BasicBlock {
2036        // mb_funclet_bb should be present if and only if the target is wasm and
2037        // we're terminating because of an unwind in a cleanup block. In that
2038        // case we have nested funclets and the inner catch_switch needs to know
2039        // what outer catch_pad it is contained in.
2040        if true {
    if !(outer_catchpad_bb.is_some() ==
                (base::wants_wasm_eh(self.cx.tcx().sess) &&
                        reason == UnwindTerminateReason::InCleanup)) {
        ::core::panicking::panic("assertion failed: outer_catchpad_bb.is_some() ==\n    (base::wants_wasm_eh(self.cx.tcx().sess) &&\n            reason == UnwindTerminateReason::InCleanup)")
    };
};debug_assert!(
2041            outer_catchpad_bb.is_some()
2042                == (base::wants_wasm_eh(self.cx.tcx().sess)
2043                    && reason == UnwindTerminateReason::InCleanup)
2044        );
2045
2046        // When we aren't in a wasm InCleanup block, there's only one terminate
2047        // block needed so we cache at START_BLOCK index.
2048        let mut cache_bb = mir::START_BLOCK;
2049        // In wasm eh InCleanup, use the outer funclet's cleanup BB as the cache
2050        // key.
2051        if let Some(outer_bb) = outer_catchpad_bb {
2052            let cleanup_kinds =
2053                self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
2054            cache_bb = cleanup_kinds[outer_bb]
2055                .funclet_bb(outer_bb)
2056                .expect("funclet_bb should be in a funclet");
2057
2058            // Ensure the outer funclet is created first
2059            if self.funclets[cache_bb].is_none() {
2060                self.landing_pad_for(cache_bb);
2061            }
2062        }
2063        if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
2064            && reason == cached_reason
2065        {
2066            return cached_bb;
2067        }
2068
2069        let funclet;
2070        let llbb;
2071        let mut bx;
2072        if base::wants_new_eh_instructions(self.cx.sess()) {
2073            // This is a basic block that we're aborting the program for,
2074            // notably in an `extern` function. These basic blocks are inserted
2075            // so that we assert that `extern` functions do indeed not panic,
2076            // and if they do we abort the process.
2077            //
2078            // On MSVC these are tricky though (where we're doing funclets). If
2079            // we were to do a cleanuppad (like below) the normal functions like
2080            // `longjmp` would trigger the abort logic, terminating the
2081            // program. Instead we insert the equivalent of `catch(...)` for C++
2082            // which magically doesn't trigger when `longjmp` files over this
2083            // frame.
2084            //
2085            // Lots more discussion can be found on #48251 but this codegen is
2086            // modeled after clang's for:
2087            //
2088            //      try {
2089            //          foo();
2090            //      } catch (...) {
2091            //          bar();
2092            //      }
2093            //
2094            // which creates an IR snippet like
2095            //
2096            //      cs_terminate:
2097            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
2098            //      cp_terminate:
2099            //         %cp = catchpad within %cs [null, i32 64, null]
2100            //         ...
2101            //
2102            // By contrast, on WebAssembly targets, we specifically _do_ want to
2103            // catch foreign exceptions. The situation with MSVC is a
2104            // regrettable hack which we don't want to extend to other targets
2105            // unless necessary. For WebAssembly, to generate catch(...) and
2106            // catch only C++ exception instead of generating a catch_all, we
2107            // need to call the intrinsics @llvm.wasm.get.exception and
2108            // @llvm.wasm.get.ehselector in the catch pad. Since we don't do
2109            // this, we generate a catch_all. We originally got this behavior
2110            // by accident but it luckily matches our intention.
2111
2112            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
2113
2114            let mut cs_bx = Bx::build(self.cx, llbb);
2115
2116            // For wasm InCleanup blocks, our catch_switch is nested within the
2117            // outer catchpad, so we need to provide it as the parent value to
2118            // catch_switch.
2119            let mut outer_cleanuppad = None;
2120            if outer_catchpad_bb.is_some() {
2121                // Get the outer funclet's catchpad
2122                let outer_funclet = self.funclets[cache_bb]
2123                    .as_ref()
2124                    .expect("landing_pad_for didn't create funclet");
2125                outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2126            }
2127            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2128            let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2129            drop(cs_bx);
2130
2131            bx = Bx::build(self.cx, cp_llbb);
2132            let null =
2133                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2134
2135            // The `null` in first argument here is actually a RTTI type
2136            // descriptor for the C++ personality function, but `catch (...)`
2137            // has no type so it's null.
2138            let args = if base::wants_msvc_seh(self.cx.sess()) {
2139                // This bitmask is a single `HT_IsStdDotDot` flag, which
2140                // represents that this is a C++-style `catch (...)` block that
2141                // only captures programmatic exceptions, not all SEH
2142                // exceptions. The second `null` points to a non-existent
2143                // `alloca` instruction, which an LLVM pass would inline into
2144                // the initial SEH frame allocation.
2145                let adjectives = bx.const_i32(0x40);
2146                &[null, adjectives, null] as &[_]
2147            } else {
2148                // Specifying more arguments than necessary usually doesn't
2149                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
2150                // anything other than a single `null` as a `catch_all` block,
2151                // leading to problems down the line during instruction
2152                // selection.
2153                &[null] as &[_]
2154            };
2155
2156            funclet = Some(bx.catch_pad(cs, args));
2157            // On wasm, if we wanted to generate a catch(...) and only catch C++
2158            // exceptions, we'd call @llvm.wasm.get.exception and
2159            // @llvm.wasm.get.ehselector selectors here. We want a catch_all so
2160            // we leave them out. This is intentionally diverging from the MSVC
2161            // behavior.
2162        } else {
2163            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2164            bx = Bx::build(self.cx, llbb);
2165
2166            let llpersonality = self.cx.eh_personality();
2167            bx.filter_landing_pad(llpersonality);
2168
2169            funclet = None;
2170        }
2171
2172        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2173
2174        let (fn_abi, fn_ptr, instance) =
2175            common::build_langcall(&bx, self.mir.span, reason.lang_item());
2176        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2177            bx.abort();
2178        } else {
2179            let fn_ty = bx.fn_decl_backend_type(fn_abi);
2180
2181            let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
2182            bx.apply_attrs_to_cleanup_callsite(llret);
2183        }
2184
2185        bx.unreachable();
2186
2187        self.terminate_blocks[cache_bb] = Some((llbb, reason));
2188        llbb
2189    }
2190
2191    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2192    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2193    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2194    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2195    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2196        self.try_llbb(bb).unwrap()
2197    }
2198
2199    /// Like `llbb`, but may fail if the basic block should be skipped.
2200    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2201        match self.cached_llbbs[bb] {
2202            CachedLlbb::None => {
2203                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2204                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2205                Some(llbb)
2206            }
2207            CachedLlbb::Some(llbb) => Some(llbb),
2208            CachedLlbb::Skip => None,
2209        }
2210    }
2211
2212    fn make_return_dest(
2213        &mut self,
2214        bx: &mut Bx,
2215        dest: mir::Place<'tcx>,
2216        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2217        llargs: &mut Vec<Bx::Value>,
2218    ) -> ReturnDest<'tcx, Bx::Value> {
2219        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2220        if fn_ret.is_ignore() {
2221            return ReturnDest::Nothing;
2222        }
2223        let dest = if let Some(index) = dest.as_local() {
2224            match self.locals[index] {
2225                LocalRef::Place(dest) => dest,
2226                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
2227                LocalRef::PendingOperand => {
2228                    // Handle temporary places, specifically `Operand` ones, as
2229                    // they don't have `alloca`s.
2230                    return if fn_ret.is_indirect() {
2231                        // Odd, but possible, case, we have an operand temporary,
2232                        // but the calling convention has an indirect return.
2233                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2234                        tmp.storage_live(bx);
2235                        llargs.push(tmp.val.llval);
2236                        ReturnDest::IndirectOperand(tmp, index)
2237                    } else {
2238                        ReturnDest::DirectOperand(index)
2239                    };
2240                }
2241                LocalRef::Operand(_) => {
2242                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
2243                }
2244            }
2245        } else {
2246            self.codegen_place(bx, dest.as_ref())
2247        };
2248        if fn_ret.is_indirect() {
2249            if dest.val.align < dest.layout.align.abi {
2250                // Currently, MIR code generation does not create calls
2251                // that store directly to fields of packed structs (in
2252                // fact, the calls it creates write only to temps).
2253                //
2254                // If someone changes that, please update this code path
2255                // to create a temporary.
2256                ::rustc_middle::util::bug::span_bug_fmt(self.mir.span,
    format_args!("can\'t directly store to unaligned value"));span_bug!(self.mir.span, "can't directly store to unaligned value");
2257            }
2258            llargs.push(dest.val.llval);
2259            ReturnDest::Nothing
2260        } else {
2261            ReturnDest::Store(dest)
2262        }
2263    }
2264
2265    // Stores the return value of a function call into it's final location.
2266    fn store_return(
2267        &mut self,
2268        bx: &mut Bx,
2269        dest: ReturnDest<'tcx, Bx::Value>,
2270        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2271        llval: Bx::Value,
2272    ) {
2273        use self::ReturnDest::*;
2274        let retags_enabled = bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some();
2275        match dest {
2276            Nothing => (),
2277            Store(dst) => {
2278                bx.store_arg(ret_abi, llval, dst);
2279                if retags_enabled {
2280                    self.codegen_retag_place(bx, dst, false);
2281                }
2282            }
2283            IndirectOperand(tmp, index) => {
2284                let mut op = bx.load_operand(tmp);
2285                tmp.storage_dead(bx);
2286                if retags_enabled {
2287                    op = self.codegen_retag_operand(bx, op, false);
2288                }
2289                self.overwrite_local(index, LocalRef::Operand(op));
2290                self.debug_introduce_local(bx, index);
2291            }
2292            DirectOperand(index) => {
2293                // If there is a cast, we have to store and reload.
2294                let mut op = if let PassMode::Cast { .. } = ret_abi.mode {
2295                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2296                    tmp.storage_live(bx);
2297                    bx.store_arg(ret_abi, llval, tmp);
2298                    let op = bx.load_operand(tmp);
2299                    tmp.storage_dead(bx);
2300                    op
2301                } else {
2302                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2303                };
2304                if retags_enabled {
2305                    op = self.codegen_retag_operand(bx, op, false);
2306                }
2307                self.overwrite_local(index, LocalRef::Operand(op));
2308                self.debug_introduce_local(bx, index);
2309            }
2310        }
2311    }
2312}
2313
2314enum ReturnDest<'tcx, V> {
2315    /// Do nothing; the return value is indirect or ignored.
2316    Nothing,
2317    /// Store the return value to the pointer.
2318    Store(PlaceRef<'tcx, V>),
2319    /// Store an indirect return value to an operand local place.
2320    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2321    /// Store a direct return value to an operand local place.
2322    DirectOperand(mir::Local),
2323}
2324
2325fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2326    bx: &mut Bx,
2327    cast: &CastTarget,
2328    ptr: Bx::Value,
2329    align: Align,
2330) -> Bx::Value {
2331    let cast_ty = bx.cast_backend_type(cast);
2332    if let Some(offset_from_start) = cast.rest_offset {
2333        {
    match (&cast.prefix.len(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.prefix.len(), 1);
2334        {
    match (&cast.rest.unit.size, &cast.rest.total) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.rest.unit.size, cast.rest.total);
2335        let first_ty = bx.reg_backend_type(&cast.prefix[0]);
2336        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2337        let first = bx.load(first_ty, ptr, align);
2338        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2339        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2340        let res = bx.cx().const_poison(cast_ty);
2341        let res = bx.insert_value(res, first, 0);
2342        bx.insert_value(res, second, 1)
2343    } else {
2344        bx.load(cast_ty, ptr, align)
2345    }
2346}
2347
2348pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2349    bx: &mut Bx,
2350    cast: &CastTarget,
2351    value: Bx::Value,
2352    ptr: Bx::Value,
2353    align: Align,
2354) {
2355    if let Some(offset_from_start) = cast.rest_offset {
2356        {
    match (&cast.prefix.len(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.prefix.len(), 1);
2357        {
    match (&cast.rest.unit.size, &cast.rest.total) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(cast.rest.unit.size, cast.rest.total);
2358        let first = bx.extract_value(value, 0);
2359        let second = bx.extract_value(value, 1);
2360        bx.store(first, ptr, align);
2361        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2362        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2363    } else {
2364        bx.store(value, ptr, align);
2365    };
2366}