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