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