Skip to main content

rustc_codegen_ssa/mir/
block.rs

1use std::cmp;
2
3use rustc_abi::{Align, BackendRepr, ExternAbi, HasDataLayout, Reg, Size, WrappingRange};
4use rustc_ast as ast;
5use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
6use rustc_data_structures::packed::Pu128;
7use rustc_hir::lang_items::LangItem;
8use rustc_lint_defs::builtin::TAIL_CALL_TRACK_CALLER;
9use rustc_middle::mir::{self, AssertKind, InlineAsmMacro, SwitchTargets, UnwindTerminateReason};
10use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, ValidityRequirement};
11use rustc_middle::ty::print::{with_no_trimmed_paths, with_no_visible_paths};
12use rustc_middle::ty::{self, Instance, Ty, TypeVisitableExt};
13use rustc_middle::{bug, span_bug};
14use rustc_session::config::OptLevel;
15use rustc_span::{Span, Spanned};
16use rustc_target::callconv::{ArgAbi, ArgAttributes, CastTarget, FnAbi, PassMode};
17use tracing::{debug, info};
18
19use super::operand::OperandRef;
20use super::operand::OperandValue::{Immediate, Pair, Ref, ZeroSized};
21use super::place::{PlaceRef, PlaceValue};
22use super::{CachedLlbb, FunctionCx, LocalRef};
23use crate::base::{self, is_call_from_compiler_builtins_to_upstream_monomorphization};
24use crate::common::{self, IntPredicate};
25use crate::errors::CompilerBuiltinsCannotCall;
26use crate::traits::*;
27use crate::{MemFlags, meth};
28
29// Indicates if we are in the middle of merging a BB's successor into it. This
30// can happen when BB jumps directly to its successor and the successor has no
31// other predecessors.
32#[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)]
33enum MergingSucc {
34    False,
35    True,
36}
37
38/// Indicates to the call terminator codegen whether a call
39/// is a normal call or an explicit tail call.
40#[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)]
41enum CallKind {
42    Normal,
43    Tail,
44}
45
46/// Used by `FunctionCx::codegen_terminator` for emitting common patterns
47/// e.g., creating a basic block, calling a function, etc.
48struct TerminatorCodegenHelper<'tcx> {
49    bb: mir::BasicBlock,
50    terminator: &'tcx mir::Terminator<'tcx>,
51}
52
53impl<'a, 'tcx> TerminatorCodegenHelper<'tcx> {
54    /// Returns the appropriate `Funclet` for the current funclet, if on MSVC,
55    /// either already previously cached, or newly created, by `landing_pad_for`.
56    fn funclet<'b, Bx: BuilderMethods<'a, 'tcx>>(
57        &self,
58        fx: &'b mut FunctionCx<'a, 'tcx, Bx>,
59    ) -> Option<&'b Bx::Funclet> {
60        let cleanup_kinds = fx.cleanup_kinds.as_ref()?;
61        let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb)?;
62        // If `landing_pad_for` hasn't been called yet to create the `Funclet`,
63        // it has to be now. This may not seem necessary, as RPO should lead
64        // to all the unwind edges being visited (and so to `landing_pad_for`
65        // getting called for them), before building any of the blocks inside
66        // the funclet itself - however, if MIR contains edges that end up not
67        // being needed in the LLVM IR after monomorphization, the funclet may
68        // be unreachable, and we don't have yet a way to skip building it in
69        // such an eventuality (which may be a better solution than this).
70        if fx.funclets[funclet_bb].is_none() {
71            fx.landing_pad_for(funclet_bb);
72        }
73        Some(
74            fx.funclets[funclet_bb]
75                .as_ref()
76                .expect("landing_pad_for didn't also create funclets entry"),
77        )
78    }
79
80    /// Get a basic block (creating it if necessary), possibly with cleanup
81    /// stuff in it or next to it.
82    fn llbb_with_cleanup<Bx: BuilderMethods<'a, 'tcx>>(
83        &self,
84        fx: &mut FunctionCx<'a, 'tcx, Bx>,
85        target: mir::BasicBlock,
86    ) -> Bx::BasicBlock {
87        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
88        let mut lltarget = fx.llbb(target);
89        if needs_landing_pad {
90            lltarget = fx.landing_pad_for(target);
91        }
92        if is_cleanupret {
93            // Cross-funclet jump - need a trampoline
94            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));
95            {
    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:95",
                        "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(95u32),
                        ::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);
96            let name = &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}_cleanup_trampoline_{1:?}",
                self.bb, target))
    })format!("{:?}_cleanup_trampoline_{:?}", self.bb, target);
97            let trampoline_llbb = Bx::append_block(fx.cx, fx.llfn, name);
98            let mut trampoline_bx = Bx::build(fx.cx, trampoline_llbb);
99            trampoline_bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
100            trampoline_llbb
101        } else {
102            lltarget
103        }
104    }
105
106    fn llbb_characteristics<Bx: BuilderMethods<'a, 'tcx>>(
107        &self,
108        fx: &mut FunctionCx<'a, 'tcx, Bx>,
109        target: mir::BasicBlock,
110    ) -> (bool, bool) {
111        if let Some(ref cleanup_kinds) = fx.cleanup_kinds {
112            let funclet_bb = cleanup_kinds[self.bb].funclet_bb(self.bb);
113            let target_funclet = cleanup_kinds[target].funclet_bb(target);
114            let (needs_landing_pad, is_cleanupret) = match (funclet_bb, target_funclet) {
115                (None, None) => (false, false),
116                (None, Some(_)) => (true, false),
117                (Some(f), Some(t_f)) => (f != t_f, f != t_f),
118                (Some(_), None) => {
119                    let span = self.terminator.source_info.span;
120                    ::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);
121                }
122            };
123            (needs_landing_pad, is_cleanupret)
124        } else {
125            let needs_landing_pad = !fx.mir[self.bb].is_cleanup && fx.mir[target].is_cleanup;
126            let is_cleanupret = false;
127            (needs_landing_pad, is_cleanupret)
128        }
129    }
130
131    fn funclet_br<Bx: BuilderMethods<'a, 'tcx>>(
132        &self,
133        fx: &mut FunctionCx<'a, 'tcx, Bx>,
134        bx: &mut Bx,
135        target: mir::BasicBlock,
136        mergeable_succ: bool,
137    ) -> MergingSucc {
138        let (needs_landing_pad, is_cleanupret) = self.llbb_characteristics(fx, target);
139        if mergeable_succ && !needs_landing_pad && !is_cleanupret {
140            // We can merge the successor into this bb, so no need for a `br`.
141            MergingSucc::True
142        } else {
143            let mut lltarget = fx.llbb(target);
144            if needs_landing_pad {
145                lltarget = fx.landing_pad_for(target);
146            }
147            if is_cleanupret {
148                // micro-optimization: generate a `ret` rather than a jump
149                // to a trampoline.
150                bx.cleanup_ret(self.funclet(fx).unwrap(), Some(lltarget));
151            } else {
152                bx.br(lltarget);
153            }
154            MergingSucc::False
155        }
156    }
157
158    /// Call `fn_ptr` of `fn_abi` with the arguments `llargs`, the optional
159    /// return destination `destination` and the unwind action `unwind`.
160    fn do_call<Bx: BuilderMethods<'a, 'tcx>>(
161        &self,
162        fx: &mut FunctionCx<'a, 'tcx, Bx>,
163        bx: &mut Bx,
164        fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
165        fn_ptr: Bx::Value,
166        llargs: &[Bx::Value],
167        destination: Option<(ReturnDest<'tcx, Bx::Value>, mir::BasicBlock)>,
168        mut unwind: mir::UnwindAction,
169        lifetime_ends_after_call: &[(Bx::Value, Size)],
170        instance: Option<Instance<'tcx>>,
171        kind: CallKind,
172        mergeable_succ: bool,
173    ) -> MergingSucc {
174        let tcx = bx.tcx();
175        if let Some(instance) = instance
176            && is_call_from_compiler_builtins_to_upstream_monomorphization(tcx, instance)
177        {
178            if destination.is_some() {
179                let caller_def = fx.instance.def_id();
180                let e = CompilerBuiltinsCannotCall {
181                    span: tcx.def_span(caller_def),
182                    caller: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(caller_def) }with_no_trimmed_paths!(tcx.def_path_str(caller_def)),
183                    callee: { let _guard = NoTrimmedGuard::new(); tcx.def_path_str(instance.def_id()) }with_no_trimmed_paths!(tcx.def_path_str(instance.def_id())),
184                };
185                tcx.dcx().emit_err(e);
186            } else {
187                {
    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:187",
                        "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(187u32),
                        ::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!(
188                    "compiler_builtins call to diverging function {:?} replaced with abort",
189                    instance.def_id()
190                );
191                bx.abort();
192                bx.unreachable();
193                return MergingSucc::False;
194            }
195        }
196
197        // If there is a cleanup block and the function we're calling can unwind, then
198        // do an invoke, otherwise do a call.
199        let fn_ty = bx.fn_decl_backend_type(fn_abi);
200
201        let caller_attrs = if bx.tcx().def_kind(fx.instance.def_id()).has_codegen_attrs() {
202            Some(bx.tcx().codegen_instance_attrs(fx.instance.def))
203        } else {
204            None
205        };
206        let caller_attrs = caller_attrs.as_deref();
207
208        if !fn_abi.can_unwind {
209            unwind = mir::UnwindAction::Unreachable;
210        }
211
212        let unwind_block = match unwind {
213            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
214            mir::UnwindAction::Continue => None,
215            mir::UnwindAction::Unreachable => None,
216            mir::UnwindAction::Terminate(reason) => {
217                if fx.mir[self.bb].is_cleanup && base::wants_wasm_eh(fx.cx.tcx().sess) {
218                    // For wasm, we need to generate a nested `cleanuppad within %outer_pad`
219                    // to catch exceptions during cleanup and call `panic_in_cleanup`.
220                    Some(fx.terminate_block(reason, Some(self.bb)))
221                } else if fx.mir[self.bb].is_cleanup
222                    && base::wants_new_eh_instructions(fx.cx.tcx().sess)
223                {
224                    // MSVC SEH will abort automatically if an exception tries to
225                    // propagate out from cleanup.
226                    None
227                } else {
228                    Some(fx.terminate_block(reason, None))
229                }
230            }
231        };
232
233        if kind == CallKind::Tail {
234            bx.tail_call(fn_ty, caller_attrs, fn_abi, fn_ptr, llargs, self.funclet(fx), instance);
235            return MergingSucc::False;
236        }
237
238        if let Some(unwind_block) = unwind_block {
239            let ret_llbb = if let Some((_, target)) = destination {
240                self.llbb_with_cleanup(fx, target)
241            } else {
242                fx.unreachable_block()
243            };
244            let invokeret = bx.invoke(
245                fn_ty,
246                caller_attrs,
247                Some(fn_abi),
248                fn_ptr,
249                llargs,
250                ret_llbb,
251                unwind_block,
252                self.funclet(fx),
253                instance,
254            );
255            if fx.mir[self.bb].is_cleanup {
256                bx.apply_attrs_to_cleanup_callsite(invokeret);
257            }
258
259            if let Some((ret_dest, target)) = destination {
260                bx.switch_to_block(fx.llbb(target));
261                fx.set_debug_loc(bx, self.terminator.source_info);
262                for &(tmp, size) in lifetime_ends_after_call {
263                    bx.lifetime_end(tmp, size);
264                }
265                fx.store_return(bx, ret_dest, &fn_abi.ret, invokeret);
266            }
267            MergingSucc::False
268        } else {
269            let llret = bx.call(
270                fn_ty,
271                caller_attrs,
272                Some(fn_abi),
273                fn_ptr,
274                llargs,
275                self.funclet(fx),
276                instance,
277            );
278            if fx.mir[self.bb].is_cleanup {
279                bx.apply_attrs_to_cleanup_callsite(llret);
280            }
281
282            if let Some((ret_dest, target)) = destination {
283                for &(tmp, size) in lifetime_ends_after_call {
284                    bx.lifetime_end(tmp, size);
285                }
286                fx.store_return(bx, ret_dest, &fn_abi.ret, llret);
287                self.funclet_br(fx, bx, target, mergeable_succ)
288            } else {
289                bx.unreachable();
290                MergingSucc::False
291            }
292        }
293    }
294
295    /// Generates inline assembly with optional `destination` and `unwind`.
296    fn do_inlineasm<Bx: BuilderMethods<'a, 'tcx>>(
297        &self,
298        fx: &mut FunctionCx<'a, 'tcx, Bx>,
299        bx: &mut Bx,
300        template: &[InlineAsmTemplatePiece],
301        operands: &[InlineAsmOperandRef<'tcx, Bx>],
302        options: InlineAsmOptions,
303        line_spans: &[Span],
304        destination: Option<mir::BasicBlock>,
305        unwind: mir::UnwindAction,
306        instance: Instance<'_>,
307        mergeable_succ: bool,
308    ) -> MergingSucc {
309        let unwind_target = match unwind {
310            mir::UnwindAction::Cleanup(cleanup) => Some(self.llbb_with_cleanup(fx, cleanup)),
311            mir::UnwindAction::Terminate(reason) => Some(fx.terminate_block(reason, None)),
312            mir::UnwindAction::Continue => None,
313            mir::UnwindAction::Unreachable => None,
314        };
315
316        if operands.iter().any(|x| #[allow(non_exhaustive_omitted_patterns)] match x {
    InlineAsmOperandRef::Label { .. } => true,
    _ => false,
}matches!(x, InlineAsmOperandRef::Label { .. })) {
317            if !unwind_target.is_none() {
    ::core::panicking::panic("assertion failed: unwind_target.is_none()")
};assert!(unwind_target.is_none());
318            let ret_llbb = if let Some(target) = destination {
319                self.llbb_with_cleanup(fx, target)
320            } else {
321                fx.unreachable_block()
322            };
323
324            bx.codegen_inline_asm(
325                template,
326                operands,
327                options,
328                line_spans,
329                instance,
330                Some(ret_llbb),
331                None,
332            );
333            MergingSucc::False
334        } else if let Some(cleanup) = unwind_target {
335            let ret_llbb = if let Some(target) = destination {
336                self.llbb_with_cleanup(fx, target)
337            } else {
338                fx.unreachable_block()
339            };
340
341            bx.codegen_inline_asm(
342                template,
343                operands,
344                options,
345                line_spans,
346                instance,
347                Some(ret_llbb),
348                Some((cleanup, self.funclet(fx))),
349            );
350            MergingSucc::False
351        } else {
352            bx.codegen_inline_asm(template, operands, options, line_spans, instance, None, None);
353
354            if let Some(target) = destination {
355                self.funclet_br(fx, bx, target, mergeable_succ)
356            } else {
357                bx.unreachable();
358                MergingSucc::False
359            }
360        }
361    }
362}
363
364/// Codegen implementations for some terminator variants.
365impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
366    /// Generates code for a `Resume` terminator.
367    fn codegen_resume_terminator(&mut self, helper: TerminatorCodegenHelper<'tcx>, bx: &mut Bx) {
368        if let Some(funclet) = helper.funclet(self) {
369            bx.cleanup_ret(funclet, None);
370        } else {
371            let slot = self.get_personality_slot(bx);
372            let exn0 = slot.project_field(bx, 0);
373            let exn0 = bx.load_operand(exn0).immediate();
374            let exn1 = slot.project_field(bx, 1);
375            let exn1 = bx.load_operand(exn1).immediate();
376            slot.storage_dead(bx);
377
378            bx.resume(exn0, exn1);
379        }
380    }
381
382    fn codegen_switchint_terminator(
383        &mut self,
384        helper: TerminatorCodegenHelper<'tcx>,
385        bx: &mut Bx,
386        discr: &mir::Operand<'tcx>,
387        targets: &SwitchTargets,
388    ) {
389        let discr = self.codegen_operand(bx, discr);
390        let discr_value = discr.immediate();
391        let switch_ty = discr.layout.ty;
392        // If our discriminant is a constant we can branch directly
393        if let Some(const_discr) = bx.const_to_opt_u128(discr_value, false) {
394            let target = targets.target_for_value(const_discr);
395            bx.br(helper.llbb_with_cleanup(self, target));
396            return;
397        };
398
399        let mut target_iter = targets.iter();
400        if target_iter.len() == 1 {
401            // If there are two targets (one conditional, one fallback), emit `br` instead of
402            // `switch`.
403            let (test_value, target) = target_iter.next().unwrap();
404            let otherwise = targets.otherwise();
405            let lltarget = helper.llbb_with_cleanup(self, target);
406            let llotherwise = helper.llbb_with_cleanup(self, otherwise);
407            let target_cold = self.cold_blocks[target];
408            let otherwise_cold = self.cold_blocks[otherwise];
409            // If `target_cold == otherwise_cold`, the branches have the same weight
410            // so there is no expectation. If they differ, the `target` branch is expected
411            // when the `otherwise` branch is cold.
412            let expect = if target_cold == otherwise_cold { None } else { Some(otherwise_cold) };
413            if switch_ty == bx.tcx().types.bool {
414                // Don't generate trivial icmps when switching on bool.
415                match test_value {
416                    0 => {
417                        let expect = expect.map(|e| !e);
418                        bx.cond_br_with_expect(discr_value, llotherwise, lltarget, expect);
419                    }
420                    1 => {
421                        bx.cond_br_with_expect(discr_value, lltarget, llotherwise, expect);
422                    }
423                    _ => ::rustc_middle::util::bug::bug_fmt(format_args!("impossible case reached"))bug!(),
424                }
425            } else {
426                let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
427                let llval = bx.const_uint_big(switch_llty, test_value);
428                let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
429                bx.cond_br_with_expect(cmp, lltarget, llotherwise, expect);
430            }
431        } else if target_iter.len() == 2
432            && self.mir[targets.otherwise()].is_empty_unreachable()
433            && targets.all_values().contains(&Pu128(0))
434            && targets.all_values().contains(&Pu128(1))
435        {
436            // This is the really common case for `bool`, `Option`, etc.
437            // By using `trunc nuw` we communicate that other values are
438            // impossible without needing `switch` or `assume`s.
439            let true_bb = targets.target_for_value(1);
440            let false_bb = targets.target_for_value(0);
441            let true_ll = helper.llbb_with_cleanup(self, true_bb);
442            let false_ll = helper.llbb_with_cleanup(self, false_bb);
443
444            let expected_cond_value = if self.cx.sess().opts.optimize == OptLevel::No {
445                None
446            } else {
447                match (self.cold_blocks[true_bb], self.cold_blocks[false_bb]) {
448                    // Same coldness, no expectation
449                    (true, true) | (false, false) => None,
450                    // Different coldness, expect the non-cold one
451                    (true, false) => Some(false),
452                    (false, true) => Some(true),
453                }
454            };
455
456            let bool_ty = bx.tcx().types.bool;
457            let cond = if switch_ty == bool_ty {
458                discr_value
459            } else {
460                let bool_llty = bx.immediate_backend_type(bx.layout_of(bool_ty));
461                bx.unchecked_utrunc(discr_value, bool_llty)
462            };
463            bx.cond_br_with_expect(cond, true_ll, false_ll, expected_cond_value);
464        } else if self.cx.sess().opts.optimize == OptLevel::No
465            && target_iter.len() == 2
466            && self.mir[targets.otherwise()].is_empty_unreachable()
467        {
468            // In unoptimized builds, if there are two normal targets and the `otherwise` target is
469            // an unreachable BB, emit `br` instead of `switch`. This leaves behind the unreachable
470            // BB, which will usually (but not always) be dead code.
471            //
472            // Why only in unoptimized builds?
473            // - In unoptimized builds LLVM uses FastISel which does not support switches, so it
474            //   must fall back to the slower SelectionDAG isel. Therefore, using `br` gives
475            //   significant compile time speedups for unoptimized builds.
476            // - In optimized builds the above doesn't hold, and using `br` sometimes results in
477            //   worse generated code because LLVM can no longer tell that the value being switched
478            //   on can only have two values, e.g. 0 and 1.
479            //
480            let (test_value1, target1) = target_iter.next().unwrap();
481            let (_test_value2, target2) = target_iter.next().unwrap();
482            let ll1 = helper.llbb_with_cleanup(self, target1);
483            let ll2 = helper.llbb_with_cleanup(self, target2);
484            let switch_llty = bx.immediate_backend_type(bx.layout_of(switch_ty));
485            let llval = bx.const_uint_big(switch_llty, test_value1);
486            let cmp = bx.icmp(IntPredicate::IntEQ, discr_value, llval);
487            bx.cond_br(cmp, ll1, ll2);
488        } else {
489            let otherwise = targets.otherwise();
490            let otherwise_cold = self.cold_blocks[otherwise];
491            let otherwise_unreachable = self.mir[otherwise].is_empty_unreachable();
492            let cold_count = targets.iter().filter(|(_, target)| self.cold_blocks[*target]).count();
493            let none_cold = cold_count == 0;
494            let all_cold = cold_count == targets.iter().len();
495            if (none_cold && (!otherwise_cold || otherwise_unreachable))
496                || (all_cold && (otherwise_cold || otherwise_unreachable))
497            {
498                // All targets have the same weight,
499                // or `otherwise` is unreachable and it's the only target with a different weight.
500                bx.switch(
501                    discr_value,
502                    helper.llbb_with_cleanup(self, targets.otherwise()),
503                    target_iter
504                        .map(|(value, target)| (value, helper.llbb_with_cleanup(self, target))),
505                );
506            } else {
507                // Targets have different weights
508                bx.switch_with_weights(
509                    discr_value,
510                    helper.llbb_with_cleanup(self, targets.otherwise()),
511                    otherwise_cold,
512                    target_iter.map(|(value, target)| {
513                        (value, helper.llbb_with_cleanup(self, target), self.cold_blocks[target])
514                    }),
515                );
516            }
517        }
518    }
519
520    fn codegen_return_terminator(&mut self, bx: &mut Bx) {
521        // Call `va_end` if this is the definition of a C-variadic function.
522        if self.fn_abi.c_variadic {
523            // The `VaList` "spoofed" argument is just after all the real arguments.
524            let va_list_arg_idx = self.fn_abi.args.len();
525            match self.locals[mir::Local::arg(va_list_arg_idx)] {
526                LocalRef::Place(va_list) => {
527                    bx.va_end(va_list.val.llval);
528
529                    // Explicitly end the lifetime of the `va_list`, improves LLVM codegen.
530                    bx.lifetime_end(va_list.val.llval, va_list.layout.size);
531                }
532                _ => ::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"),
533            }
534        }
535        if self.fn_abi.ret.layout.is_uninhabited() {
536            // Functions with uninhabited return values are marked `noreturn`,
537            // so we should make sure that we never actually do.
538            // We play it safe by using a well-defined `abort`, but we could go for immediate UB
539            // if that turns out to be helpful.
540            bx.abort();
541            // `abort` does not terminate the block, so we still need to generate
542            // an `unreachable` terminator after it.
543            bx.unreachable();
544            return;
545        }
546        let llval = match &self.fn_abi.ret.mode {
547            PassMode::Ignore | PassMode::Indirect { .. } => {
548                bx.ret_void();
549                return;
550            }
551
552            PassMode::Direct(_) | PassMode::Pair(..) => {
553                let op = self.codegen_consume(bx, mir::Place::return_place().as_ref());
554                if let Ref(place_val) = op.val {
555                    bx.load_from_place(bx.backend_type(op.layout), place_val)
556                } else {
557                    op.immediate_or_packed_pair(bx)
558                }
559            }
560
561            PassMode::Cast { cast: cast_ty, pad_i32: _ } => {
562                let op = match self.locals[mir::RETURN_PLACE] {
563                    LocalRef::Operand(op) => op,
564                    LocalRef::PendingOperand => ::rustc_middle::util::bug::bug_fmt(format_args!("use of return before def"))bug!("use of return before def"),
565                    LocalRef::Place(cg_place) => OperandRef {
566                        val: Ref(cg_place.val),
567                        layout: cg_place.layout,
568                        move_annotation: None,
569                    },
570                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
571                };
572                let llslot = match op.val {
573                    Immediate(_) | Pair(..) => {
574                        let scratch = PlaceRef::alloca(bx, self.fn_abi.ret.layout);
575                        op.val.store(bx, scratch);
576                        scratch.val.llval
577                    }
578                    Ref(place_val) => {
579                        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!(
580                            place_val.align, op.layout.align.abi,
581                            "return place is unaligned!"
582                        );
583                        place_val.llval
584                    }
585                    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"),
586                };
587                load_cast(bx, cast_ty, llslot, self.fn_abi.ret.layout.align.abi)
588            }
589        };
590        bx.ret(llval);
591    }
592
593    #[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(593u32),
                                    ::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_in_place(bx.tcx(), ty);
            if let ty::InstanceKind::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:642",
                                                "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(642u32),
                                                ::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:643",
                                                "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(643u32),
                                                ::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:644",
                                                "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(644u32),
                                                ::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),
                            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))]
594    fn codegen_drop_terminator(
595        &mut self,
596        helper: TerminatorCodegenHelper<'tcx>,
597        bx: &mut Bx,
598        source_info: &mir::SourceInfo,
599        location: mir::Place<'tcx>,
600        target: mir::BasicBlock,
601        unwind: mir::UnwindAction,
602        mergeable_succ: bool,
603    ) -> MergingSucc {
604        let ty = location.ty(self.mir, bx.tcx()).ty;
605        let ty = self.monomorphize(ty);
606        let drop_fn = Instance::resolve_drop_in_place(bx.tcx(), ty);
607
608        if let ty::InstanceKind::DropGlue(_, None) = drop_fn.def {
609            // we don't actually need to drop anything.
610            return helper.funclet_br(self, bx, target, mergeable_succ);
611        }
612
613        let place = self.codegen_place(bx, location.as_ref());
614        let (args1, args2);
615        let mut args = if let Some(llextra) = place.val.llextra {
616            args2 = [place.val.llval, llextra];
617            &args2[..]
618        } else {
619            args1 = [place.val.llval];
620            &args1[..]
621        };
622        let (maybe_null, drop_fn, fn_abi, drop_instance) = match ty.kind() {
623            // FIXME(eddyb) perhaps move some of this logic into
624            // `Instance::resolve_drop_in_place`?
625            ty::Dynamic(_, _) => {
626                // IN THIS ARM, WE HAVE:
627                // ty = *mut (dyn Trait)
628                // which is: exists<T> ( *mut T,    Vtable<T: Trait> )
629                //                       args[0]    args[1]
630                //
631                // args = ( Data, Vtable )
632                //                  |
633                //                  v
634                //                /-------\
635                //                | ...   |
636                //                \-------/
637                //
638                let virtual_drop = Instance {
639                    def: ty::InstanceKind::Virtual(drop_fn.def_id(), 0), // idx 0: the drop function
640                    args: drop_fn.args,
641                };
642                debug!("ty = {:?}", ty);
643                debug!("drop_fn = {:?}", drop_fn);
644                debug!("args = {:?}", args);
645                let fn_abi = bx.fn_abi_of_instance(virtual_drop, ty::List::empty());
646                let vtable = args[1];
647                // Truncate vtable off of args list
648                args = &args[..1];
649                (
650                    true,
651                    meth::VirtualIndex::from_index(ty::COMMON_VTABLE_ENTRIES_DROPINPLACE)
652                        .get_optional_fn(bx, vtable, ty, fn_abi),
653                    fn_abi,
654                    virtual_drop,
655                )
656            }
657            _ => (
658                false,
659                bx.get_fn_addr(drop_fn),
660                bx.fn_abi_of_instance(drop_fn, ty::List::empty()),
661                drop_fn,
662            ),
663        };
664
665        // We generate a null check for the drop_fn. This saves a bunch of relocations being
666        // generated for no-op drops.
667        if maybe_null {
668            let is_not_null = bx.append_sibling_block("is_not_null");
669            let llty = bx.fn_ptr_backend_type(fn_abi);
670            let null = bx.const_null(llty);
671            let non_null =
672                bx.icmp(base::bin_op_to_icmp_predicate(mir::BinOp::Ne, false), drop_fn, null);
673            bx.cond_br(non_null, is_not_null, helper.llbb_with_cleanup(self, target));
674            bx.switch_to_block(is_not_null);
675            self.set_debug_loc(bx, *source_info);
676        }
677
678        helper.do_call(
679            self,
680            bx,
681            fn_abi,
682            drop_fn,
683            args,
684            Some((ReturnDest::Nothing, target)),
685            unwind,
686            &[],
687            Some(drop_instance),
688            CallKind::Normal,
689            !maybe_null && mergeable_succ,
690        )
691    }
692
693    fn codegen_assert_terminator(
694        &mut self,
695        helper: TerminatorCodegenHelper<'tcx>,
696        bx: &mut Bx,
697        terminator: &mir::Terminator<'tcx>,
698        cond: &mir::Operand<'tcx>,
699        expected: bool,
700        msg: &mir::AssertMessage<'tcx>,
701        target: mir::BasicBlock,
702        unwind: mir::UnwindAction,
703        mergeable_succ: bool,
704    ) -> MergingSucc {
705        let span = terminator.source_info.span;
706        let cond = self.codegen_operand(bx, cond).immediate();
707        let mut const_cond = bx.const_to_opt_u128(cond, false).map(|c| c == 1);
708
709        // This case can currently arise only from functions marked
710        // with #[rustc_inherit_overflow_checks] and inlined from
711        // another crate (mostly core::num generic/#[inline] fns),
712        // while the current crate doesn't use overflow checks.
713        if !bx.sess().overflow_checks() && msg.is_optional_overflow_check() {
714            const_cond = Some(expected);
715        }
716
717        // Don't codegen the panic block if success if known.
718        if const_cond == Some(expected) {
719            return helper.funclet_br(self, bx, target, mergeable_succ);
720        }
721
722        // Because we're branching to a panic block (either a `#[cold]` one
723        // or an inlined abort), there's no need to `expect` it.
724
725        // Create the failure block and the conditional branch to it.
726        let lltarget = helper.llbb_with_cleanup(self, target);
727        let panic_block = bx.append_sibling_block("panic");
728        if expected {
729            bx.cond_br(cond, lltarget, panic_block);
730        } else {
731            bx.cond_br(cond, panic_block, lltarget);
732        }
733
734        // After this point, bx is the block for the call to panic.
735        bx.switch_to_block(panic_block);
736        self.set_debug_loc(bx, terminator.source_info);
737
738        // Get the location information.
739        let location = self.get_caller_location(bx, terminator.source_info).immediate();
740
741        // Put together the arguments to the panic entry point.
742        let (lang_item, args) = match msg {
743            AssertKind::BoundsCheck { len, index } => {
744                let len = self.codegen_operand(bx, len).immediate();
745                let index = self.codegen_operand(bx, index).immediate();
746                // It's `fn panic_bounds_check(index: usize, len: usize)`,
747                // and `#[track_caller]` adds an implicit third argument.
748                (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])
749            }
750            AssertKind::MisalignedPointerDereference { required, found } => {
751                let required = self.codegen_operand(bx, required).immediate();
752                let found = self.codegen_operand(bx, found).immediate();
753                // It's `fn panic_misaligned_pointer_dereference(required: usize, found: usize)`,
754                // and `#[track_caller]` adds an implicit third argument.
755                (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])
756            }
757            AssertKind::NullPointerDereference => {
758                // It's `fn panic_null_pointer_dereference()`,
759                // `#[track_caller]` adds an implicit argument.
760                (LangItem::PanicNullPointerDereference, ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [location]))vec![location])
761            }
762            AssertKind::InvalidEnumConstruction(source) => {
763                let source = self.codegen_operand(bx, source).immediate();
764                // It's `fn panic_invalid_enum_construction(source: u128)`,
765                // `#[track_caller]` adds an implicit argument.
766                (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])
767            }
768            _ => {
769                // It's `pub fn panic_...()` and `#[track_caller]` adds an implicit argument.
770                (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])
771            }
772        };
773
774        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, lang_item);
775
776        // Codegen the actual panic invoke/call.
777        let merging_succ = helper.do_call(
778            self,
779            bx,
780            fn_abi,
781            llfn,
782            &args,
783            None,
784            unwind,
785            &[],
786            Some(instance),
787            CallKind::Normal,
788            false,
789        );
790        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);
791        MergingSucc::False
792    }
793
794    fn codegen_terminate_terminator(
795        &mut self,
796        helper: TerminatorCodegenHelper<'tcx>,
797        bx: &mut Bx,
798        terminator: &mir::Terminator<'tcx>,
799        reason: UnwindTerminateReason,
800    ) {
801        let span = terminator.source_info.span;
802        self.set_debug_loc(bx, terminator.source_info);
803
804        // Obtain the panic entry point.
805        let (fn_abi, llfn, instance) = common::build_langcall(bx, span, reason.lang_item());
806
807        // Codegen the actual panic invoke/call.
808        let merging_succ = helper.do_call(
809            self,
810            bx,
811            fn_abi,
812            llfn,
813            &[],
814            None,
815            mir::UnwindAction::Unreachable,
816            &[],
817            Some(instance),
818            CallKind::Normal,
819            false,
820        );
821        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);
822    }
823
824    /// Returns `Some` if this is indeed a panic intrinsic and codegen is done.
825    fn codegen_panic_intrinsic(
826        &mut self,
827        helper: &TerminatorCodegenHelper<'tcx>,
828        bx: &mut Bx,
829        intrinsic: ty::IntrinsicDef,
830        instance: Instance<'tcx>,
831        source_info: mir::SourceInfo,
832        target: Option<mir::BasicBlock>,
833        unwind: mir::UnwindAction,
834        mergeable_succ: bool,
835    ) -> Option<MergingSucc> {
836        // Emit a panic or a no-op for `assert_*` intrinsics.
837        // These are intrinsics that compile to panics so that we can get a message
838        // which mentions the offending type, even from a const context.
839        let Some(requirement) = ValidityRequirement::from_intrinsic(intrinsic.name) else {
840            return None;
841        };
842
843        let ty = instance.args.type_at(0);
844
845        let is_valid = bx
846            .tcx()
847            .check_validity_requirement((requirement, bx.typing_env().as_query_input(ty)))
848            .expect("expect to have layout during codegen");
849
850        if is_valid {
851            // a NOP
852            let target = target.unwrap();
853            return Some(helper.funclet_br(self, bx, target, mergeable_succ));
854        }
855
856        let layout = bx.layout_of(ty);
857
858        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!({
859            with_no_trimmed_paths!({
860                if layout.is_uninhabited() {
861                    // Use this error even for the other intrinsics as it is more precise.
862                    format!("attempted to instantiate uninhabited type `{ty}`")
863                } else if requirement == ValidityRequirement::Zero {
864                    format!("attempted to zero-initialize type `{ty}`, which is invalid")
865                } else {
866                    format!("attempted to leave type `{ty}` uninitialized, which is invalid")
867                }
868            })
869        });
870        let msg = bx.const_str(&msg_str);
871
872        // Obtain the panic entry point.
873        let (fn_abi, llfn, instance) =
874            common::build_langcall(bx, source_info.span, LangItem::PanicNounwind);
875
876        // Codegen the actual panic invoke/call.
877        Some(helper.do_call(
878            self,
879            bx,
880            fn_abi,
881            llfn,
882            &[msg.0, msg.1],
883            target.as_ref().map(|bb| (ReturnDest::Nothing, *bb)),
884            unwind,
885            &[],
886            Some(instance),
887            CallKind::Normal,
888            mergeable_succ,
889        ))
890    }
891
892    fn codegen_call_terminator(
893        &mut self,
894        helper: TerminatorCodegenHelper<'tcx>,
895        bx: &mut Bx,
896        terminator: &mir::Terminator<'tcx>,
897        func: &mir::Operand<'tcx>,
898        args: &[Spanned<mir::Operand<'tcx>>],
899        destination: mir::Place<'tcx>,
900        target: Option<mir::BasicBlock>,
901        unwind: mir::UnwindAction,
902        fn_span: Span,
903        kind: CallKind,
904        mergeable_succ: bool,
905    ) -> MergingSucc {
906        let source_info = mir::SourceInfo { span: fn_span, ..terminator.source_info };
907
908        // Create the callee. This is a fn ptr or zero-sized and hence a kind of scalar.
909        let callee = self.codegen_operand(bx, func);
910
911        let (instance, mut llfn) = match *callee.layout.ty.kind() {
912            ty::FnDef(def_id, generic_args) => {
913                let instance = ty::Instance::expect_resolve(
914                    bx.tcx(),
915                    bx.typing_env(),
916                    def_id,
917                    generic_args,
918                    fn_span,
919                );
920
921                match instance.def {
922                    // We don't need AsyncDropGlueCtorShim here because it is not `noop func`,
923                    // it is `func returning noop future`
924                    ty::InstanceKind::DropGlue(_, None) => {
925                        // Empty drop glue; a no-op.
926                        let target = target.unwrap();
927                        return helper.funclet_br(self, bx, target, mergeable_succ);
928                    }
929                    ty::InstanceKind::Intrinsic(def_id) => {
930                        let intrinsic = bx.tcx().intrinsic(def_id).unwrap();
931                        if let Some(merging_succ) = self.codegen_panic_intrinsic(
932                            &helper,
933                            bx,
934                            intrinsic,
935                            instance,
936                            source_info,
937                            target,
938                            unwind,
939                            mergeable_succ,
940                        ) {
941                            return merging_succ;
942                        }
943
944                        let result_layout =
945                            self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
946
947                        let (result, store_in_local) = if result_layout.is_zst() {
948                            (
949                                PlaceRef::new_sized(bx.const_undef(bx.type_ptr()), result_layout),
950                                None,
951                            )
952                        } else if let Some(local) = destination.as_local() {
953                            match self.locals[local] {
954                                LocalRef::Place(dest) => (dest, None),
955                                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
956                                LocalRef::PendingOperand => {
957                                    // Currently, intrinsics always need a location to store
958                                    // the result, so we create a temporary `alloca` for the
959                                    // result.
960                                    let tmp = PlaceRef::alloca(bx, result_layout);
961                                    tmp.storage_live(bx);
962                                    (tmp, Some(local))
963                                }
964                                LocalRef::Operand(_) => {
965                                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
966                                }
967                            }
968                        } else {
969                            (self.codegen_place(bx, destination.as_ref()), None)
970                        };
971
972                        if result.val.align < result.layout.align.abi {
973                            // Currently, MIR code generation does not create calls
974                            // that store directly to fields of packed structs (in
975                            // fact, the calls it creates write only to temps).
976                            //
977                            // If someone changes that, please update this code path
978                            // to create a temporary.
979                            ::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");
980                        }
981
982                        let args: Vec<_> =
983                            args.iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect();
984
985                        match self.codegen_intrinsic_call(bx, instance, &args, result, source_info)
986                        {
987                            Ok(()) => {
988                                if let Some(local) = store_in_local {
989                                    let op = bx.load_operand(result);
990                                    result.storage_dead(bx);
991                                    self.overwrite_local(local, LocalRef::Operand(op));
992                                    self.debug_introduce_local(bx, local);
993                                }
994
995                                return if let Some(target) = target {
996                                    helper.funclet_br(self, bx, target, mergeable_succ)
997                                } else {
998                                    bx.unreachable();
999                                    MergingSucc::False
1000                                };
1001                            }
1002                            Err(instance) => {
1003                                if intrinsic.must_be_overridden {
1004                                    ::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!(
1005                                        fn_span,
1006                                        "intrinsic {} must be overridden by codegen backend, but isn't",
1007                                        intrinsic.name,
1008                                    );
1009                                }
1010                                (Some(instance), None)
1011                            }
1012                        }
1013                    }
1014
1015                    _ if kind == CallKind::Tail
1016                        && instance.def.requires_caller_location(bx.tcx()) =>
1017                    {
1018                        if let Some(hir_id) =
1019                            terminator.source_info.scope.lint_root(&self.mir.source_scopes)
1020                        {
1021                            bx.tcx().emit_node_lint(TAIL_CALL_TRACK_CALLER, hir_id, rustc_errors::DiagDecorator(|d| {
1022                                _ = d.primary_message("tail calling a function marked with `#[track_caller]` has no special effect").span(fn_span)
1023                            }));
1024                        }
1025
1026                        let instance = ty::Instance::resolve_for_fn_ptr(
1027                            bx.tcx(),
1028                            bx.typing_env(),
1029                            def_id,
1030                            generic_args,
1031                        )
1032                        .unwrap();
1033
1034                        (None, Some(bx.get_fn_addr(instance)))
1035                    }
1036                    _ => (Some(instance), None),
1037                }
1038            }
1039            ty::FnPtr(..) => (None, Some(callee.immediate())),
1040            _ => ::rustc_middle::util::bug::bug_fmt(format_args!("{0} is not callable",
        callee.layout.ty))bug!("{} is not callable", callee.layout.ty),
1041        };
1042
1043        if let Some(instance) = instance
1044            && let Some(name) = bx.tcx().codegen_fn_attrs(instance.def_id()).symbol_name
1045            && name.as_str().starts_with("llvm.")
1046            // This is the only LLVM intrinsic we use that unwinds
1047            // FIXME either add unwind support to codegen_llvm_intrinsic_call or replace usage of
1048            // this intrinsic with something else
1049            && name.as_str() != "llvm.wasm.throw"
1050        {
1051            if !!instance.args.has_infer() {
    ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
};assert!(!instance.args.has_infer());
1052            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());
1053
1054            let result_layout =
1055                self.cx.layout_of(self.monomorphized_place_ty(destination.as_ref()));
1056
1057            let return_dest = if result_layout.is_zst() {
1058                ReturnDest::Nothing
1059            } else if let Some(index) = destination.as_local() {
1060                match self.locals[index] {
1061                    LocalRef::Place(dest) => ReturnDest::Store(dest),
1062                    LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
1063                    LocalRef::PendingOperand => {
1064                        // Handle temporary places, specifically `Operand` ones, as
1065                        // they don't have `alloca`s.
1066                        ReturnDest::DirectOperand(index)
1067                    }
1068                    LocalRef::Operand(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"))bug!("place local already assigned to"),
1069                }
1070            } else {
1071                ReturnDest::Store(self.codegen_place(bx, destination.as_ref()))
1072            };
1073
1074            let args =
1075                args.into_iter().map(|arg| self.codegen_operand(bx, &arg.node)).collect::<Vec<_>>();
1076
1077            self.set_debug_loc(bx, source_info);
1078
1079            let llret =
1080                bx.codegen_llvm_intrinsic_call(instance, &args, self.mir[helper.bb].is_cleanup);
1081
1082            if let Some(target) = target {
1083                self.store_return(
1084                    bx,
1085                    return_dest,
1086                    &ArgAbi { layout: result_layout, mode: PassMode::Direct(ArgAttributes::new()) },
1087                    llret,
1088                );
1089                return helper.funclet_br(self, bx, target, mergeable_succ);
1090            } else {
1091                bx.unreachable();
1092                return MergingSucc::False;
1093            }
1094        }
1095
1096        // FIXME(eddyb) avoid computing this if possible, when `instance` is
1097        // available - right now `sig` is only needed for getting the `abi`
1098        // and figuring out how many extra args were passed to a C-variadic `fn`.
1099        let sig = callee.layout.ty.fn_sig(bx.tcx());
1100
1101        let extra_args = &args[sig.inputs().skip_binder().len()..];
1102        let extra_args = bx.tcx().mk_type_list_from_iter(extra_args.iter().map(|op_arg| {
1103            let op_ty = op_arg.node.ty(self.mir, bx.tcx());
1104            self.monomorphize(op_ty)
1105        }));
1106
1107        let fn_abi = match instance {
1108            Some(instance) => bx.fn_abi_of_instance(instance, extra_args),
1109            None => bx.fn_abi_of_fn_ptr(sig, extra_args),
1110        };
1111
1112        // The arguments we'll be passing. Plus one to account for outptr, if used.
1113        let arg_count = fn_abi.args.len() + fn_abi.ret.is_indirect() as usize;
1114
1115        let mut llargs = Vec::with_capacity(arg_count);
1116
1117        // We still need to call `make_return_dest` even if there's no `target`, since
1118        // `fn_abi.ret` could be `PassMode::Indirect`, even if it is uninhabited,
1119        // and `make_return_dest` adds the return-place indirect pointer to `llargs`.
1120        let destination = match kind {
1121            CallKind::Normal => {
1122                let return_dest = self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs);
1123                target.map(|target| (return_dest, target))
1124            }
1125            CallKind::Tail => {
1126                if fn_abi.ret.is_indirect() {
1127                    match self.make_return_dest(bx, destination, &fn_abi.ret, &mut llargs) {
1128                        ReturnDest::Nothing => {}
1129                        _ => ::rustc_middle::util::bug::bug_fmt(format_args!("tail calls to functions with indirect returns cannot store into a destination"))bug!(
1130                            "tail calls to functions with indirect returns cannot store into a destination"
1131                        ),
1132                    }
1133                }
1134                None
1135            }
1136        };
1137
1138        // Split the rust-call tupled arguments off.
1139        let (first_args, untuple) = if sig.abi() == ExternAbi::RustCall
1140            && let Some((tup, args)) = args.split_last()
1141        {
1142            (args, Some(tup))
1143        } else {
1144            (args, None)
1145        };
1146
1147        // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1148        //
1149        // Normally an indirect argument that is allocated in the caller's stack frame
1150        // would be passed as a pointer into the callee's stack frame.
1151        // For tail calls, that would be unsound, because the caller's
1152        // stack frame is overwritten by the callee's stack frame.
1153        //
1154        // Therefore we store the argument for the callee in the corresponding caller's slot.
1155        // Because guaranteed tail calls demand that the caller's signature matches the callee's,
1156        // the corresponding slot has the correct type.
1157        //
1158        // To handle cases like the one below, the tail call arguments must first be copied to a
1159        // temporary, and only then copied to the caller's argument slots.
1160        //
1161        // ```
1162        // // A struct big enough that it is not passed via registers.
1163        // pub struct Big([u64; 4]);
1164        //
1165        // fn swapper(a: Big, b: Big) -> (Big, Big) {
1166        //     become swapper_helper(b, a);
1167        // }
1168        // ```
1169        let mut tail_call_temporaries = ::alloc::vec::Vec::new()vec![];
1170        if kind == CallKind::Tail {
1171            tail_call_temporaries = ::alloc::vec::from_elem(None, first_args.len())vec![None; first_args.len()];
1172            // Copy the arguments that use `PassMode::Indirect { on_stack: false , ..}`
1173            // to temporary stack allocations. See the comment above.
1174            for (i, arg) in first_args.iter().enumerate() {
1175                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, .. }) {
1176                    continue;
1177                }
1178
1179                let op = self.codegen_operand(bx, &arg.node);
1180                let tmp = PlaceRef::alloca(bx, op.layout);
1181                bx.lifetime_start(tmp.val.llval, tmp.layout.size);
1182                op.store_with_annotation(bx, tmp);
1183
1184                tail_call_temporaries[i] = Some(tmp);
1185            }
1186        }
1187
1188        // When generating arguments we sometimes introduce temporary allocations with lifetime
1189        // that extend for the duration of a call. Keep track of those allocations and their sizes
1190        // to generate `lifetime_end` when the call returns.
1191        let mut lifetime_ends_after_call: Vec<(Bx::Value, Size)> = Vec::new();
1192        'make_args: for (i, arg) in first_args.iter().enumerate() {
1193            let mut op = self.codegen_operand(bx, &arg.node);
1194
1195            if let (0, Some(ty::InstanceKind::Virtual(_, idx))) = (i, instance.map(|i| i.def)) {
1196                match op.val {
1197                    Pair(data_ptr, meta) => {
1198                        // In the case of Rc<Self>, we need to explicitly pass a
1199                        // *mut RcInner<Self> with a Scalar (not ScalarPair) ABI. This is a hack
1200                        // that is understood elsewhere in the compiler as a method on
1201                        // `dyn Trait`.
1202                        // To get a `*mut RcInner<Self>`, we just keep unwrapping newtypes until
1203                        // we get a value of a built-in pointer type.
1204                        //
1205                        // This is also relevant for `Pin<&mut Self>`, where we need to peel the
1206                        // `Pin`.
1207                        while !op.layout.ty.is_raw_ptr() && !op.layout.ty.is_ref() {
1208                            let (idx, _) = op.layout.non_1zst_field(bx).expect(
1209                                "not exactly one non-1-ZST field in a `DispatchFromDyn` type",
1210                            );
1211                            op = op.extract_field(self, bx, idx.as_usize());
1212                        }
1213
1214                        // Now that we have `*dyn Trait` or `&dyn Trait`, split it up into its
1215                        // data pointer and vtable. Look up the method in the vtable, and pass
1216                        // the data pointer as the first argument.
1217                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1218                            bx,
1219                            meta,
1220                            op.layout.ty,
1221                            fn_abi,
1222                        ));
1223                        llargs.push(data_ptr);
1224                        continue 'make_args;
1225                    }
1226                    Ref(PlaceValue { llval: data_ptr, llextra: Some(meta), .. }) => {
1227                        // by-value dynamic dispatch
1228                        llfn = Some(meth::VirtualIndex::from_index(idx).get_fn(
1229                            bx,
1230                            meta,
1231                            op.layout.ty,
1232                            fn_abi,
1233                        ));
1234                        llargs.push(data_ptr);
1235                        continue;
1236                    }
1237                    _ => {
1238                        ::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);
1239                    }
1240                }
1241            }
1242
1243            let by_move = if let PassMode::Indirect { on_stack: false, .. } = fn_abi.args[i].mode
1244                && kind == CallKind::Tail
1245            {
1246                // Special logic for tail calls with `PassMode::Indirect { on_stack: false, .. }` arguments.
1247                //
1248                // Normally an indirect argument that is allocated in the caller's stack frame
1249                // would be passed as a pointer into the callee's stack frame.
1250                // For tail calls, that would be unsound, because the caller's
1251                // stack frame is overwritten by the callee's stack frame.
1252                //
1253                // To handle the case, we introduce `tail_call_temporaries` to copy arguments into
1254                // temporaries, then copy back to the caller's argument slots.
1255                // Finally, we pass the caller's argument slots as arguments.
1256                //
1257                // To do that, the argument must be MUST-by-move value.
1258                let Some(tmp) = tail_call_temporaries[i].take() else {
1259                    ::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}")
1260                };
1261
1262                let local = self.mir.args_iter().nth(i).unwrap();
1263
1264                match &self.locals[local] {
1265                    LocalRef::Place(arg) => {
1266                        bx.typed_place_copy(arg.val, tmp.val, fn_abi.args[i].layout);
1267                        op.val = Ref(arg.val);
1268                    }
1269                    LocalRef::Operand(arg) => {
1270                        let Ref(place_value) = arg.val else {
1271                            ::rustc_middle::util::bug::bug_fmt(format_args!("only `Ref` should use `PassMode::Indirect`"));bug!("only `Ref` should use `PassMode::Indirect`");
1272                        };
1273                        bx.typed_place_copy(place_value, tmp.val, fn_abi.args[i].layout);
1274                        op.val = arg.val;
1275                    }
1276                    LocalRef::UnsizedPlace(_) => {
1277                        ::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")
1278                    }
1279                    LocalRef::PendingOperand => {
1280                        ::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")
1281                    }
1282                };
1283
1284                bx.lifetime_end(tmp.val.llval, tmp.layout.size);
1285                true
1286            } else {
1287                #[allow(non_exhaustive_omitted_patterns)] match arg.node {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(arg.node, mir::Operand::Move(_))
1288            };
1289
1290            self.codegen_argument(
1291                bx,
1292                op,
1293                by_move,
1294                &mut llargs,
1295                &fn_abi.args[i],
1296                &mut lifetime_ends_after_call,
1297            );
1298        }
1299        let num_untupled = untuple.map(|tup| {
1300            self.codegen_arguments_untupled(
1301                bx,
1302                &tup.node,
1303                &mut llargs,
1304                &fn_abi.args[first_args.len()..],
1305                &mut lifetime_ends_after_call,
1306            )
1307        });
1308
1309        let needs_location =
1310            instance.is_some_and(|i| i.def.requires_caller_location(self.cx.tcx()));
1311        if needs_location {
1312            let mir_args = if let Some(num_untupled) = num_untupled {
1313                first_args.len() + num_untupled
1314            } else {
1315                args.len()
1316            };
1317            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!(
1318                fn_abi.args.len(),
1319                mir_args + 1,
1320                "#[track_caller] fn's must have 1 more argument in their ABI than in their MIR: {instance:?} {fn_span:?} {fn_abi:?}",
1321            );
1322            let location = self.get_caller_location(bx, source_info);
1323            {
    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:1323",
                        "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(1323u32),
                        ::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!(
1324                "codegen_call_terminator({:?}): location={:?} (fn_span {:?})",
1325                terminator, location, fn_span
1326            );
1327
1328            let last_arg = fn_abi.args.last().unwrap();
1329            self.codegen_argument(
1330                bx,
1331                location,
1332                /* by_move */ false,
1333                &mut llargs,
1334                last_arg,
1335                &mut lifetime_ends_after_call,
1336            );
1337        }
1338
1339        let fn_ptr = match (instance, llfn) {
1340            (Some(instance), None) => bx.get_fn_addr(instance),
1341            (_, Some(llfn)) => llfn,
1342            _ => ::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"),
1343        };
1344        self.set_debug_loc(bx, source_info);
1345        helper.do_call(
1346            self,
1347            bx,
1348            fn_abi,
1349            fn_ptr,
1350            &llargs,
1351            destination,
1352            unwind,
1353            &lifetime_ends_after_call,
1354            instance,
1355            kind,
1356            mergeable_succ,
1357        )
1358    }
1359
1360    fn codegen_asm_terminator(
1361        &mut self,
1362        helper: TerminatorCodegenHelper<'tcx>,
1363        bx: &mut Bx,
1364        asm_macro: InlineAsmMacro,
1365        terminator: &mir::Terminator<'tcx>,
1366        template: &[ast::InlineAsmTemplatePiece],
1367        operands: &[mir::InlineAsmOperand<'tcx>],
1368        options: ast::InlineAsmOptions,
1369        line_spans: &[Span],
1370        targets: &[mir::BasicBlock],
1371        unwind: mir::UnwindAction,
1372        instance: Instance<'_>,
1373        mergeable_succ: bool,
1374    ) -> MergingSucc {
1375        let span = terminator.source_info.span;
1376
1377        let operands: Vec<_> = operands
1378            .iter()
1379            .map(|op| match *op {
1380                mir::InlineAsmOperand::In { reg, ref value } => {
1381                    let value = self.codegen_operand(bx, value);
1382                    InlineAsmOperandRef::In { reg, value }
1383                }
1384                mir::InlineAsmOperand::Out { reg, late, ref place } => {
1385                    let place = place.map(|place| self.codegen_place(bx, place.as_ref()));
1386                    InlineAsmOperandRef::Out { reg, late, place }
1387                }
1388                mir::InlineAsmOperand::InOut { reg, late, ref in_value, ref out_place } => {
1389                    let in_value = self.codegen_operand(bx, in_value);
1390                    let out_place =
1391                        out_place.map(|out_place| self.codegen_place(bx, out_place.as_ref()));
1392                    InlineAsmOperandRef::InOut { reg, late, in_value, out_place }
1393                }
1394                mir::InlineAsmOperand::Const { ref value } => {
1395                    let const_value = self.eval_mir_constant(value);
1396                    let string = common::asm_const_to_str(
1397                        bx.tcx(),
1398                        span,
1399                        const_value,
1400                        bx.layout_of(value.ty()),
1401                    );
1402                    InlineAsmOperandRef::Const { string }
1403                }
1404                mir::InlineAsmOperand::SymFn { ref value } => {
1405                    let const_ = self.monomorphize(value.const_);
1406                    if let ty::FnDef(def_id, args) = *const_.ty().kind() {
1407                        let instance = ty::Instance::resolve_for_fn_ptr(
1408                            bx.tcx(),
1409                            bx.typing_env(),
1410                            def_id,
1411                            args,
1412                        )
1413                        .unwrap();
1414                        InlineAsmOperandRef::SymFn { instance }
1415                    } else {
1416                        ::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)");
1417                    }
1418                }
1419                mir::InlineAsmOperand::SymStatic { def_id } => {
1420                    InlineAsmOperandRef::SymStatic { def_id }
1421                }
1422                mir::InlineAsmOperand::Label { target_index } => {
1423                    InlineAsmOperandRef::Label { label: self.llbb(targets[target_index]) }
1424                }
1425            })
1426            .collect();
1427
1428        helper.do_inlineasm(
1429            self,
1430            bx,
1431            template,
1432            &operands,
1433            options,
1434            line_spans,
1435            if asm_macro.diverges(options) { None } else { targets.get(0).copied() },
1436            unwind,
1437            instance,
1438            mergeable_succ,
1439        )
1440    }
1441
1442    pub(crate) fn codegen_block(&mut self, mut bb: mir::BasicBlock) {
1443        let llbb = match self.try_llbb(bb) {
1444            Some(llbb) => llbb,
1445            None => return,
1446        };
1447        let bx = &mut Bx::build(self.cx, llbb);
1448        let mir = self.mir;
1449
1450        // MIR basic blocks stop at any function call. This may not be the case
1451        // for the backend's basic blocks, in which case we might be able to
1452        // combine multiple MIR basic blocks into a single backend basic block.
1453        loop {
1454            let data = &mir[bb];
1455
1456            {
    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:1456",
                        "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(1456u32),
                        ::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);
1457
1458            for statement in &data.statements {
1459                self.codegen_statement(bx, statement);
1460            }
1461            self.codegen_stmt_debuginfos(bx, &data.after_last_stmt_debuginfos);
1462
1463            let merging_succ = self.codegen_terminator(bx, bb, data.terminator());
1464            if let MergingSucc::False = merging_succ {
1465                break;
1466            }
1467
1468            // We are merging the successor into the produced backend basic
1469            // block. Record that the successor should be skipped when it is
1470            // reached.
1471            //
1472            // Note: we must not have already generated code for the successor.
1473            // This is implicitly ensured by the reverse postorder traversal,
1474            // and the assertion explicitly guarantees that.
1475            let mut successors = data.terminator().successors();
1476            let succ = successors.next().unwrap();
1477            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));
1478            self.cached_llbbs[succ] = CachedLlbb::Skip;
1479            bb = succ;
1480        }
1481    }
1482
1483    pub(crate) fn codegen_block_as_unreachable(&mut self, bb: mir::BasicBlock) {
1484        let llbb = match self.try_llbb(bb) {
1485            Some(llbb) => llbb,
1486            None => return,
1487        };
1488        let bx = &mut Bx::build(self.cx, llbb);
1489        {
    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:1489",
                        "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(1489u32),
                        ::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);
1490        bx.unreachable();
1491    }
1492
1493    fn codegen_terminator(
1494        &mut self,
1495        bx: &mut Bx,
1496        bb: mir::BasicBlock,
1497        terminator: &'tcx mir::Terminator<'tcx>,
1498    ) -> MergingSucc {
1499        {
    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:1499",
                        "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(1499u32),
                        ::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);
1500
1501        let helper = TerminatorCodegenHelper { bb, terminator };
1502
1503        let mergeable_succ = || {
1504            // Note: any call to `switch_to_block` will invalidate a `true` value
1505            // of `mergeable_succ`.
1506            let mut successors = terminator.successors();
1507            if let Some(succ) = successors.next()
1508                && successors.next().is_none()
1509                && let &[succ_pred] = self.mir.basic_blocks.predecessors()[succ].as_slice()
1510            {
1511                // bb has a single successor, and bb is its only predecessor. This
1512                // makes it a candidate for merging.
1513                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);
1514                true
1515            } else {
1516                false
1517            }
1518        };
1519
1520        self.set_debug_loc(bx, terminator.source_info);
1521        match terminator.kind {
1522            mir::TerminatorKind::UnwindResume => {
1523                self.codegen_resume_terminator(helper, bx);
1524                MergingSucc::False
1525            }
1526
1527            mir::TerminatorKind::UnwindTerminate(reason) => {
1528                self.codegen_terminate_terminator(helper, bx, terminator, reason);
1529                MergingSucc::False
1530            }
1531
1532            mir::TerminatorKind::Goto { target } => {
1533                helper.funclet_br(self, bx, target, mergeable_succ())
1534            }
1535
1536            mir::TerminatorKind::SwitchInt { ref discr, ref targets } => {
1537                self.codegen_switchint_terminator(helper, bx, discr, targets);
1538                MergingSucc::False
1539            }
1540
1541            mir::TerminatorKind::Return => {
1542                self.codegen_return_terminator(bx);
1543                MergingSucc::False
1544            }
1545
1546            mir::TerminatorKind::Unreachable => {
1547                bx.unreachable();
1548                MergingSucc::False
1549            }
1550
1551            mir::TerminatorKind::Drop { place, target, unwind, replace: _, drop, async_fut } => {
1552                if !(async_fut.is_none() && drop.is_none()) {
    {
        ::core::panicking::panic_fmt(format_args!("Async Drop must be expanded or reset to sync before codegen"));
    }
};assert!(
1553                    async_fut.is_none() && drop.is_none(),
1554                    "Async Drop must be expanded or reset to sync before codegen"
1555                );
1556                self.codegen_drop_terminator(
1557                    helper,
1558                    bx,
1559                    &terminator.source_info,
1560                    place,
1561                    target,
1562                    unwind,
1563                    mergeable_succ(),
1564                )
1565            }
1566
1567            mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, unwind } => self
1568                .codegen_assert_terminator(
1569                    helper,
1570                    bx,
1571                    terminator,
1572                    cond,
1573                    expected,
1574                    msg,
1575                    target,
1576                    unwind,
1577                    mergeable_succ(),
1578                ),
1579
1580            mir::TerminatorKind::Call {
1581                ref func,
1582                ref args,
1583                destination,
1584                target,
1585                unwind,
1586                call_source: _,
1587                fn_span,
1588            } => self.codegen_call_terminator(
1589                helper,
1590                bx,
1591                terminator,
1592                func,
1593                args,
1594                destination,
1595                target,
1596                unwind,
1597                fn_span,
1598                CallKind::Normal,
1599                mergeable_succ(),
1600            ),
1601            mir::TerminatorKind::TailCall { ref func, ref args, fn_span } => self
1602                .codegen_call_terminator(
1603                    helper,
1604                    bx,
1605                    terminator,
1606                    func,
1607                    args,
1608                    mir::Place::from(mir::RETURN_PLACE),
1609                    None,
1610                    mir::UnwindAction::Unreachable,
1611                    fn_span,
1612                    CallKind::Tail,
1613                    mergeable_succ(),
1614                ),
1615            mir::TerminatorKind::CoroutineDrop | mir::TerminatorKind::Yield { .. } => {
1616                ::rustc_middle::util::bug::bug_fmt(format_args!("coroutine ops in codegen"))bug!("coroutine ops in codegen")
1617            }
1618            mir::TerminatorKind::FalseEdge { .. } | mir::TerminatorKind::FalseUnwind { .. } => {
1619                ::rustc_middle::util::bug::bug_fmt(format_args!("borrowck false edges in codegen"))bug!("borrowck false edges in codegen")
1620            }
1621
1622            mir::TerminatorKind::InlineAsm {
1623                asm_macro,
1624                template,
1625                ref operands,
1626                options,
1627                line_spans,
1628                ref targets,
1629                unwind,
1630            } => self.codegen_asm_terminator(
1631                helper,
1632                bx,
1633                asm_macro,
1634                terminator,
1635                template,
1636                operands,
1637                options,
1638                line_spans,
1639                targets,
1640                unwind,
1641                self.instance,
1642                mergeable_succ(),
1643            ),
1644        }
1645    }
1646
1647    fn codegen_argument(
1648        &mut self,
1649        bx: &mut Bx,
1650        op: OperandRef<'tcx, Bx::Value>,
1651        by_move: bool,
1652        llargs: &mut Vec<Bx::Value>,
1653        arg: &ArgAbi<'tcx, Ty<'tcx>>,
1654        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1655    ) {
1656        match arg.mode {
1657            PassMode::Ignore => return,
1658            PassMode::Cast { pad_i32: true, .. } => {
1659                // Fill padding with undef value, where applicable.
1660                llargs.push(bx.const_undef(bx.reg_backend_type(&Reg::i32())));
1661            }
1662            PassMode::Pair(..) => match op.val {
1663                Pair(a, b) => {
1664                    llargs.push(a);
1665                    llargs.push(b);
1666                    return;
1667                }
1668                _ => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen_argument: {0:?} invalid for pair argument",
        op))bug!("codegen_argument: {:?} invalid for pair argument", op),
1669            },
1670            PassMode::Indirect { attrs: _, meta_attrs: Some(_), on_stack: _ } => match op.val {
1671                Ref(PlaceValue { llval: a, llextra: Some(b), .. }) => {
1672                    llargs.push(a);
1673                    llargs.push(b);
1674                    return;
1675                }
1676                _ => ::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),
1677            },
1678            _ => {}
1679        }
1680
1681        // Force by-ref if we have to load through a cast pointer.
1682        let (mut llval, align, by_ref) = match op.val {
1683            Immediate(_) | Pair(..) => match arg.mode {
1684                PassMode::Indirect { attrs, .. } => {
1685                    // Indirect argument may have higher alignment requirements than the type's
1686                    // alignment. This can happen, e.g. when passing types with <4 byte alignment
1687                    // on the stack on x86.
1688                    let required_align = match attrs.pointee_align {
1689                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1690                        None => arg.layout.align.abi,
1691                    };
1692                    let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1693                    bx.lifetime_start(scratch.llval, arg.layout.size);
1694                    op.store_with_annotation(bx, scratch.with_type(arg.layout));
1695                    lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1696                    (scratch.llval, scratch.align, true)
1697                }
1698                PassMode::Cast { .. } => {
1699                    let scratch = PlaceRef::alloca(bx, arg.layout);
1700                    op.store_with_annotation(bx, scratch);
1701                    (scratch.val.llval, scratch.val.align, true)
1702                }
1703                _ => (op.immediate_or_packed_pair(bx), arg.layout.align.abi, false),
1704            },
1705            Ref(op_place_val) => match arg.mode {
1706                PassMode::Indirect { attrs, on_stack, .. } => {
1707                    // For `foo(packed.large_field)`, and types with <4 byte alignment on x86,
1708                    // alignment requirements may be higher than the type's alignment, so copy
1709                    // to a higher-aligned alloca.
1710                    let required_align = match attrs.pointee_align {
1711                        Some(pointee_align) => cmp::max(pointee_align, arg.layout.align.abi),
1712                        None => arg.layout.align.abi,
1713                    };
1714                    // Copy to an alloca when the argument is neither by-val nor by-move.
1715                    if op_place_val.align < required_align || (!on_stack && !by_move) {
1716                        let scratch = PlaceValue::alloca(bx, arg.layout.size, required_align);
1717                        bx.lifetime_start(scratch.llval, arg.layout.size);
1718                        op.store_with_annotation(bx, scratch.with_type(arg.layout));
1719                        lifetime_ends_after_call.push((scratch.llval, arg.layout.size));
1720                        (scratch.llval, scratch.align, true)
1721                    } else {
1722                        (op_place_val.llval, op_place_val.align, true)
1723                    }
1724                }
1725                _ => (op_place_val.llval, op_place_val.align, true),
1726            },
1727            ZeroSized => match arg.mode {
1728                PassMode::Indirect { on_stack, .. } => {
1729                    if on_stack {
1730                        // It doesn't seem like any target can have `byval` ZSTs, so this assert
1731                        // is here to replace a would-be untested codepath.
1732                        ::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:?}");
1733                    }
1734                    // Though `extern "Rust"` doesn't pass ZSTs, some ABIs pass
1735                    // a pointer for `repr(C)` structs even when empty, so get
1736                    // one from an `alloca` (which can be left uninitialized).
1737                    let scratch = PlaceRef::alloca(bx, arg.layout);
1738                    (scratch.val.llval, scratch.val.align, true)
1739                }
1740                _ => ::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:?}"),
1741            },
1742        };
1743
1744        if by_ref && !arg.is_indirect() {
1745            // Have to load the argument, maybe while casting it.
1746            if let PassMode::Cast { cast, pad_i32: _ } = &arg.mode {
1747                // The ABI mandates that the value is passed as a different struct representation.
1748                // Spill and reload it from the stack to convert from the Rust representation to
1749                // the ABI representation.
1750                let scratch_size = cast.size(bx);
1751                let scratch_align = cast.align(bx);
1752                // Note that the ABI type may be either larger or smaller than the Rust type,
1753                // due to the presence or absence of trailing padding. For example:
1754                // - On some ABIs, the Rust layout { f64, f32, <f32 padding> } may omit padding
1755                //   when passed by value, making it smaller.
1756                // - On some ABIs, the Rust layout { u16, u16, u16 } may be padded up to 8 bytes
1757                //   when passed by value, making it larger.
1758                let copy_bytes = cmp::min(cast.unaligned_size(bx).bytes(), arg.layout.size.bytes());
1759                // Allocate some scratch space...
1760                let llscratch = bx.alloca(scratch_size, scratch_align);
1761                bx.lifetime_start(llscratch, scratch_size);
1762                // ...memcpy the value...
1763                bx.memcpy(
1764                    llscratch,
1765                    scratch_align,
1766                    llval,
1767                    align,
1768                    bx.const_usize(copy_bytes),
1769                    MemFlags::empty(),
1770                    None,
1771                );
1772                // ...and then load it with the ABI type.
1773                llval = load_cast(bx, cast, llscratch, scratch_align);
1774                bx.lifetime_end(llscratch, scratch_size);
1775            } else {
1776                // We can't use `PlaceRef::load` here because the argument
1777                // may have a type we don't treat as immediate, but the ABI
1778                // used for this call is passing it by-value. In that case,
1779                // the load would just produce `OperandValue::Ref` instead
1780                // of the `OperandValue::Immediate` we need for the call.
1781                llval = bx.load(bx.backend_type(arg.layout), llval, align);
1782                if let BackendRepr::Scalar(scalar) = arg.layout.backend_repr {
1783                    if scalar.is_bool() {
1784                        bx.range_metadata(llval, WrappingRange { start: 0, end: 1 });
1785                    }
1786                    // We store bools as `i8` so we need to truncate to `i1`.
1787                    llval = bx.to_immediate_scalar(llval, scalar);
1788                }
1789            }
1790        }
1791
1792        llargs.push(llval);
1793    }
1794
1795    fn codegen_arguments_untupled(
1796        &mut self,
1797        bx: &mut Bx,
1798        operand: &mir::Operand<'tcx>,
1799        llargs: &mut Vec<Bx::Value>,
1800        args: &[ArgAbi<'tcx, Ty<'tcx>>],
1801        lifetime_ends_after_call: &mut Vec<(Bx::Value, Size)>,
1802    ) -> usize {
1803        let tuple = self.codegen_operand(bx, operand);
1804        let by_move = #[allow(non_exhaustive_omitted_patterns)] match operand {
    mir::Operand::Move(_) => true,
    _ => false,
}matches!(operand, mir::Operand::Move(_));
1805
1806        // Handle both by-ref and immediate tuples.
1807        if let Ref(place_val) = tuple.val {
1808            if place_val.llextra.is_some() {
1809                ::rustc_middle::util::bug::bug_fmt(format_args!("closure arguments must be sized"));bug!("closure arguments must be sized");
1810            }
1811            let tuple_ptr = place_val.with_type(tuple.layout);
1812            for i in 0..tuple.layout.fields.count() {
1813                let field_ptr = tuple_ptr.project_field(bx, i);
1814                let field = bx.load_operand(field_ptr);
1815                self.codegen_argument(
1816                    bx,
1817                    field,
1818                    by_move,
1819                    llargs,
1820                    &args[i],
1821                    lifetime_ends_after_call,
1822                );
1823            }
1824        } else {
1825            // If the tuple is immediate, the elements are as well.
1826            for i in 0..tuple.layout.fields.count() {
1827                let op = tuple.extract_field(self, bx, i);
1828                self.codegen_argument(bx, op, by_move, llargs, &args[i], lifetime_ends_after_call);
1829            }
1830        }
1831        tuple.layout.fields.count()
1832    }
1833
1834    pub(super) fn get_caller_location(
1835        &mut self,
1836        bx: &mut Bx,
1837        source_info: mir::SourceInfo,
1838    ) -> OperandRef<'tcx, Bx::Value> {
1839        self.mir.caller_location_span(source_info, self.caller_location, bx.tcx(), |span: Span| {
1840            let const_loc = bx.tcx().span_as_caller_location(span);
1841            OperandRef::from_const(bx, const_loc, bx.tcx().caller_location_ty())
1842        })
1843    }
1844
1845    fn get_personality_slot(&mut self, bx: &mut Bx) -> PlaceRef<'tcx, Bx::Value> {
1846        let cx = bx.cx();
1847        if let Some(slot) = self.personality_slot {
1848            slot
1849        } else {
1850            let layout = cx.layout_of(Ty::new_tup(
1851                cx.tcx(),
1852                &[Ty::new_mut_ptr(cx.tcx(), cx.tcx().types.u8), cx.tcx().types.i32],
1853            ));
1854            let slot = PlaceRef::alloca(bx, layout);
1855            self.personality_slot = Some(slot);
1856            slot
1857        }
1858    }
1859
1860    /// Returns the landing/cleanup pad wrapper around the given basic block.
1861    // FIXME(eddyb) rename this to `eh_pad_for`.
1862    fn landing_pad_for(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1863        if let Some(landing_pad) = self.landing_pads[bb] {
1864            return landing_pad;
1865        }
1866
1867        let landing_pad = self.landing_pad_for_uncached(bb);
1868        self.landing_pads[bb] = Some(landing_pad);
1869        landing_pad
1870    }
1871
1872    // FIXME(eddyb) rename this to `eh_pad_for_uncached`.
1873    fn landing_pad_for_uncached(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
1874        let llbb = self.llbb(bb);
1875        if base::wants_new_eh_instructions(self.cx.sess()) {
1876            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:?}"));
1877            let mut cleanup_bx = Bx::build(self.cx, cleanup_bb);
1878            let funclet = cleanup_bx.cleanup_pad(None, &[]);
1879            cleanup_bx.br(llbb);
1880            self.funclets[bb] = Some(funclet);
1881            cleanup_bb
1882        } else {
1883            let cleanup_llbb = Bx::append_block(self.cx, self.llfn, "cleanup");
1884            let mut cleanup_bx = Bx::build(self.cx, cleanup_llbb);
1885
1886            let llpersonality = self.cx.eh_personality();
1887            let (exn0, exn1) = cleanup_bx.cleanup_landing_pad(llpersonality);
1888
1889            let slot = self.get_personality_slot(&mut cleanup_bx);
1890            slot.storage_live(&mut cleanup_bx);
1891            Pair(exn0, exn1).store(&mut cleanup_bx, slot);
1892
1893            cleanup_bx.br(llbb);
1894            cleanup_llbb
1895        }
1896    }
1897
1898    fn unreachable_block(&mut self) -> Bx::BasicBlock {
1899        self.unreachable_block.unwrap_or_else(|| {
1900            let llbb = Bx::append_block(self.cx, self.llfn, "unreachable");
1901            let mut bx = Bx::build(self.cx, llbb);
1902            bx.unreachable();
1903            self.unreachable_block = Some(llbb);
1904            llbb
1905        })
1906    }
1907
1908    fn terminate_block(
1909        &mut self,
1910        reason: UnwindTerminateReason,
1911        outer_catchpad_bb: Option<mir::BasicBlock>,
1912    ) -> Bx::BasicBlock {
1913        // mb_funclet_bb should be present if and only if the target is wasm and
1914        // we're terminating because of an unwind in a cleanup block. In that
1915        // case we have nested funclets and the inner catch_switch needs to know
1916        // what outer catch_pad it is contained in.
1917        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!(
1918            outer_catchpad_bb.is_some()
1919                == (base::wants_wasm_eh(self.cx.tcx().sess)
1920                    && reason == UnwindTerminateReason::InCleanup)
1921        );
1922
1923        // When we aren't in a wasm InCleanup block, there's only one terminate
1924        // block needed so we cache at START_BLOCK index.
1925        let mut cache_bb = mir::START_BLOCK;
1926        // In wasm eh InCleanup, use the outer funclet's cleanup BB as the cache
1927        // key.
1928        if let Some(outer_bb) = outer_catchpad_bb {
1929            let cleanup_kinds =
1930                self.cleanup_kinds.as_ref().expect("cleanup_kinds required for funclets");
1931            cache_bb = cleanup_kinds[outer_bb]
1932                .funclet_bb(outer_bb)
1933                .expect("funclet_bb should be in a funclet");
1934
1935            // Ensure the outer funclet is created first
1936            if self.funclets[cache_bb].is_none() {
1937                self.landing_pad_for(cache_bb);
1938            }
1939        }
1940        if let Some((cached_bb, cached_reason)) = self.terminate_blocks[cache_bb]
1941            && reason == cached_reason
1942        {
1943            return cached_bb;
1944        }
1945
1946        let funclet;
1947        let llbb;
1948        let mut bx;
1949        if base::wants_new_eh_instructions(self.cx.sess()) {
1950            // This is a basic block that we're aborting the program for,
1951            // notably in an `extern` function. These basic blocks are inserted
1952            // so that we assert that `extern` functions do indeed not panic,
1953            // and if they do we abort the process.
1954            //
1955            // On MSVC these are tricky though (where we're doing funclets). If
1956            // we were to do a cleanuppad (like below) the normal functions like
1957            // `longjmp` would trigger the abort logic, terminating the
1958            // program. Instead we insert the equivalent of `catch(...)` for C++
1959            // which magically doesn't trigger when `longjmp` files over this
1960            // frame.
1961            //
1962            // Lots more discussion can be found on #48251 but this codegen is
1963            // modeled after clang's for:
1964            //
1965            //      try {
1966            //          foo();
1967            //      } catch (...) {
1968            //          bar();
1969            //      }
1970            //
1971            // which creates an IR snippet like
1972            //
1973            //      cs_terminate:
1974            //         %cs = catchswitch within none [%cp_terminate] unwind to caller
1975            //      cp_terminate:
1976            //         %cp = catchpad within %cs [null, i32 64, null]
1977            //         ...
1978            //
1979            // By contrast, on WebAssembly targets, we specifically _do_ want to
1980            // catch foreign exceptions. The situation with MSVC is a
1981            // regrettable hack which we don't want to extend to other targets
1982            // unless necessary. For WebAssembly, to generate catch(...) and
1983            // catch only C++ exception instead of generating a catch_all, we
1984            // need to call the intrinsics @llvm.wasm.get.exception and
1985            // @llvm.wasm.get.ehselector in the catch pad. Since we don't do
1986            // this, we generate a catch_all. We originally got this behavior
1987            // by accident but it luckily matches our intention.
1988
1989            llbb = Bx::append_block(self.cx, self.llfn, "cs_terminate");
1990
1991            let mut cs_bx = Bx::build(self.cx, llbb);
1992
1993            // For wasm InCleanup blocks, our catch_switch is nested within the
1994            // outer catchpad, so we need to provide it as the parent value to
1995            // catch_switch.
1996            let mut outer_cleanuppad = None;
1997            if outer_catchpad_bb.is_some() {
1998                // Get the outer funclet's catchpad
1999                let outer_funclet = self.funclets[cache_bb]
2000                    .as_ref()
2001                    .expect("landing_pad_for didn't create funclet");
2002                outer_cleanuppad = Some(cs_bx.get_funclet_cleanuppad(outer_funclet));
2003            }
2004            let cp_llbb = Bx::append_block(self.cx, self.llfn, "cp_terminate");
2005            let cs = cs_bx.catch_switch(outer_cleanuppad, None, &[cp_llbb]);
2006            drop(cs_bx);
2007
2008            bx = Bx::build(self.cx, cp_llbb);
2009            let null =
2010                bx.const_null(bx.type_ptr_ext(bx.cx().data_layout().instruction_address_space));
2011
2012            // The `null` in first argument here is actually a RTTI type
2013            // descriptor for the C++ personality function, but `catch (...)`
2014            // has no type so it's null.
2015            let args = if base::wants_msvc_seh(self.cx.sess()) {
2016                // This bitmask is a single `HT_IsStdDotDot` flag, which
2017                // represents that this is a C++-style `catch (...)` block that
2018                // only captures programmatic exceptions, not all SEH
2019                // exceptions. The second `null` points to a non-existent
2020                // `alloca` instruction, which an LLVM pass would inline into
2021                // the initial SEH frame allocation.
2022                let adjectives = bx.const_i32(0x40);
2023                &[null, adjectives, null] as &[_]
2024            } else {
2025                // Specifying more arguments than necessary usually doesn't
2026                // hurt, but the `WasmEHPrepare` LLVM pass does not recognize
2027                // anything other than a single `null` as a `catch_all` block,
2028                // leading to problems down the line during instruction
2029                // selection.
2030                &[null] as &[_]
2031            };
2032
2033            funclet = Some(bx.catch_pad(cs, args));
2034            // On wasm, if we wanted to generate a catch(...) and only catch C++
2035            // exceptions, we'd call @llvm.wasm.get.exception and
2036            // @llvm.wasm.get.ehselector selectors here. We want a catch_all so
2037            // we leave them out. This is intentionally diverging from the MSVC
2038            // behavior.
2039        } else {
2040            llbb = Bx::append_block(self.cx, self.llfn, "terminate");
2041            bx = Bx::build(self.cx, llbb);
2042
2043            let llpersonality = self.cx.eh_personality();
2044            bx.filter_landing_pad(llpersonality);
2045
2046            funclet = None;
2047        }
2048
2049        self.set_debug_loc(&mut bx, mir::SourceInfo::outermost(self.mir.span));
2050
2051        let (fn_abi, fn_ptr, instance) =
2052            common::build_langcall(&bx, self.mir.span, reason.lang_item());
2053        if is_call_from_compiler_builtins_to_upstream_monomorphization(bx.tcx(), instance) {
2054            bx.abort();
2055        } else {
2056            let fn_ty = bx.fn_decl_backend_type(fn_abi);
2057
2058            let llret = bx.call(fn_ty, None, Some(fn_abi), fn_ptr, &[], funclet.as_ref(), None);
2059            bx.apply_attrs_to_cleanup_callsite(llret);
2060        }
2061
2062        bx.unreachable();
2063
2064        self.terminate_blocks[cache_bb] = Some((llbb, reason));
2065        llbb
2066    }
2067
2068    /// Get the backend `BasicBlock` for a MIR `BasicBlock`, either already
2069    /// cached in `self.cached_llbbs`, or created on demand (and cached).
2070    // FIXME(eddyb) rename `llbb` and other `ll`-prefixed things to use a
2071    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbb`).
2072    pub fn llbb(&mut self, bb: mir::BasicBlock) -> Bx::BasicBlock {
2073        self.try_llbb(bb).unwrap()
2074    }
2075
2076    /// Like `llbb`, but may fail if the basic block should be skipped.
2077    pub(crate) fn try_llbb(&mut self, bb: mir::BasicBlock) -> Option<Bx::BasicBlock> {
2078        match self.cached_llbbs[bb] {
2079            CachedLlbb::None => {
2080                let llbb = Bx::append_block(self.cx, self.llfn, &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bb))
    })format!("{bb:?}"));
2081                self.cached_llbbs[bb] = CachedLlbb::Some(llbb);
2082                Some(llbb)
2083            }
2084            CachedLlbb::Some(llbb) => Some(llbb),
2085            CachedLlbb::Skip => None,
2086        }
2087    }
2088
2089    fn make_return_dest(
2090        &mut self,
2091        bx: &mut Bx,
2092        dest: mir::Place<'tcx>,
2093        fn_ret: &ArgAbi<'tcx, Ty<'tcx>>,
2094        llargs: &mut Vec<Bx::Value>,
2095    ) -> ReturnDest<'tcx, Bx::Value> {
2096        // If the return is ignored, we can just return a do-nothing `ReturnDest`.
2097        if fn_ret.is_ignore() {
2098            return ReturnDest::Nothing;
2099        }
2100        let dest = if let Some(index) = dest.as_local() {
2101            match self.locals[index] {
2102                LocalRef::Place(dest) => dest,
2103                LocalRef::UnsizedPlace(_) => ::rustc_middle::util::bug::bug_fmt(format_args!("return type must be sized"))bug!("return type must be sized"),
2104                LocalRef::PendingOperand => {
2105                    // Handle temporary places, specifically `Operand` ones, as
2106                    // they don't have `alloca`s.
2107                    return if fn_ret.is_indirect() {
2108                        // Odd, but possible, case, we have an operand temporary,
2109                        // but the calling convention has an indirect return.
2110                        let tmp = PlaceRef::alloca(bx, fn_ret.layout);
2111                        tmp.storage_live(bx);
2112                        llargs.push(tmp.val.llval);
2113                        ReturnDest::IndirectOperand(tmp, index)
2114                    } else {
2115                        ReturnDest::DirectOperand(index)
2116                    };
2117                }
2118                LocalRef::Operand(_) => {
2119                    ::rustc_middle::util::bug::bug_fmt(format_args!("place local already assigned to"));bug!("place local already assigned to");
2120                }
2121            }
2122        } else {
2123            self.codegen_place(bx, dest.as_ref())
2124        };
2125        if fn_ret.is_indirect() {
2126            if dest.val.align < dest.layout.align.abi {
2127                // Currently, MIR code generation does not create calls
2128                // that store directly to fields of packed structs (in
2129                // fact, the calls it creates write only to temps).
2130                //
2131                // If someone changes that, please update this code path
2132                // to create a temporary.
2133                ::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");
2134            }
2135            llargs.push(dest.val.llval);
2136            ReturnDest::Nothing
2137        } else {
2138            ReturnDest::Store(dest)
2139        }
2140    }
2141
2142    // Stores the return value of a function call into it's final location.
2143    fn store_return(
2144        &mut self,
2145        bx: &mut Bx,
2146        dest: ReturnDest<'tcx, Bx::Value>,
2147        ret_abi: &ArgAbi<'tcx, Ty<'tcx>>,
2148        llval: Bx::Value,
2149    ) {
2150        use self::ReturnDest::*;
2151
2152        match dest {
2153            Nothing => (),
2154            Store(dst) => bx.store_arg(ret_abi, llval, dst),
2155            IndirectOperand(tmp, index) => {
2156                let op = bx.load_operand(tmp);
2157                tmp.storage_dead(bx);
2158                self.overwrite_local(index, LocalRef::Operand(op));
2159                self.debug_introduce_local(bx, index);
2160            }
2161            DirectOperand(index) => {
2162                // If there is a cast, we have to store and reload.
2163                let op = if let PassMode::Cast { .. } = ret_abi.mode {
2164                    let tmp = PlaceRef::alloca(bx, ret_abi.layout);
2165                    tmp.storage_live(bx);
2166                    bx.store_arg(ret_abi, llval, tmp);
2167                    let op = bx.load_operand(tmp);
2168                    tmp.storage_dead(bx);
2169                    op
2170                } else {
2171                    OperandRef::from_immediate_or_packed_pair(bx, llval, ret_abi.layout)
2172                };
2173                self.overwrite_local(index, LocalRef::Operand(op));
2174                self.debug_introduce_local(bx, index);
2175            }
2176        }
2177    }
2178}
2179
2180enum ReturnDest<'tcx, V> {
2181    /// Do nothing; the return value is indirect or ignored.
2182    Nothing,
2183    /// Store the return value to the pointer.
2184    Store(PlaceRef<'tcx, V>),
2185    /// Store an indirect return value to an operand local place.
2186    IndirectOperand(PlaceRef<'tcx, V>, mir::Local),
2187    /// Store a direct return value to an operand local place.
2188    DirectOperand(mir::Local),
2189}
2190
2191fn load_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2192    bx: &mut Bx,
2193    cast: &CastTarget,
2194    ptr: Bx::Value,
2195    align: Align,
2196) -> Bx::Value {
2197    let cast_ty = bx.cast_backend_type(cast);
2198    if let Some(offset_from_start) = cast.rest_offset {
2199        if !cast.prefix[1..].iter().all(|p| p.is_none()) {
    ::core::panicking::panic("assertion failed: cast.prefix[1..].iter().all(|p| p.is_none())")
};assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
2200        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);
2201        let first_ty = bx.reg_backend_type(&cast.prefix[0].unwrap());
2202        let second_ty = bx.reg_backend_type(&cast.rest.unit);
2203        let first = bx.load(first_ty, ptr, align);
2204        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2205        let second = bx.load(second_ty, second_ptr, align.restrict_for_offset(offset_from_start));
2206        let res = bx.cx().const_poison(cast_ty);
2207        let res = bx.insert_value(res, first, 0);
2208        bx.insert_value(res, second, 1)
2209    } else {
2210        bx.load(cast_ty, ptr, align)
2211    }
2212}
2213
2214pub fn store_cast<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
2215    bx: &mut Bx,
2216    cast: &CastTarget,
2217    value: Bx::Value,
2218    ptr: Bx::Value,
2219    align: Align,
2220) {
2221    if let Some(offset_from_start) = cast.rest_offset {
2222        if !cast.prefix[1..].iter().all(|p| p.is_none()) {
    ::core::panicking::panic("assertion failed: cast.prefix[1..].iter().all(|p| p.is_none())")
};assert!(cast.prefix[1..].iter().all(|p| p.is_none()));
2223        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);
2224        if !cast.prefix[0].is_some() {
    ::core::panicking::panic("assertion failed: cast.prefix[0].is_some()")
};assert!(cast.prefix[0].is_some());
2225        let first = bx.extract_value(value, 0);
2226        let second = bx.extract_value(value, 1);
2227        bx.store(first, ptr, align);
2228        let second_ptr = bx.inbounds_ptradd(ptr, bx.const_usize(offset_from_start.bytes()));
2229        bx.store(second, second_ptr, align.restrict_for_offset(offset_from_start));
2230    } else {
2231        bx.store(value, ptr, align);
2232    };
2233}