Skip to main content

rustc_codegen_ssa/mir/
block.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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