Skip to main content

rustc_codegen_ssa/mir/
block.rs

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

    #[warn(clippy :: suspicious_else_formatting)]
    {

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