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