Skip to main content

rustc_codegen_ssa/mir/
mod.rs

1use std::iter;
2
3use rustc_index::IndexVec;
4use rustc_index::bit_set::DenseBitSet;
5use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
6use rustc_middle::mir;
7use rustc_middle::mir::{Body, Local, UnwindTerminateReason, traversal};
8use rustc_middle::ty::layout::{FnAbiOf, HasTyCtxt, HasTypingEnv, TyAndLayout};
9use rustc_middle::ty::{self, Instance, Ty, TyCtxt, TypeFoldable, TypeVisitableExt};
10use rustc_span::{ErrorGuaranteed, bug, span_bug};
11use rustc_target::callconv::{FnAbi, IndirectMode, PassMode};
12use tracing::{debug, instrument};
13
14use crate::base;
15use crate::traits::*;
16
17mod analyze;
18mod block;
19mod constant;
20mod coverageinfo;
21pub mod debuginfo;
22mod intrinsic;
23mod locals;
24pub mod naked_asm;
25pub mod operand;
26pub mod place;
27mod retag;
28mod rvalue;
29mod statement;
30
31pub use self::block::store_cast;
32use self::debuginfo::{FunctionDebugContext, PerLocalVarDebugInfo};
33use self::operand::{OperandRef, OperandValue};
34use self::place::PlaceRef;
35
36// Used for tracking the state of generated basic blocks.
37enum CachedLlbb<T> {
38    /// Nothing created yet.
39    None,
40
41    /// Has been created.
42    Some(T),
43
44    /// Nothing created yet, and nothing should be.
45    Skip,
46}
47
48type PerLocalVarDebugInfoIndexVec<'tcx, V> =
49    IndexVec<mir::Local, Vec<PerLocalVarDebugInfo<'tcx, V>>>;
50
51/// Master context for codegenning from MIR.
52pub struct FunctionCx<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> {
53    instance: Instance<'tcx>,
54
55    mir: &'tcx mir::Body<'tcx>,
56
57    debug_context: Option<FunctionDebugContext<'tcx, Bx::DIScope, Bx::DILocation>>,
58
59    llfn: Bx::Function,
60
61    cx: &'a Bx::CodegenCx,
62
63    fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
64
65    /// When unwinding is initiated, we have to store this personality
66    /// value somewhere so that we can load it and re-use it in the
67    /// resume instruction. The personality is (afaik) some kind of
68    /// value used for C++ unwinding, which must filter by type: we
69    /// don't really care about it very much. Anyway, this value
70    /// contains an alloca into which the personality is stored and
71    /// then later loaded when generating the DIVERGE_BLOCK.
72    personality_slot: Option<PlaceRef<'tcx, Bx::Value>>,
73
74    /// A backend `BasicBlock` for each MIR `BasicBlock`, created lazily
75    /// as-needed (e.g. RPO reaching it or another block branching to it).
76    // FIXME(eddyb) rename `llbbs` and other `ll`-prefixed things to use a
77    // more backend-agnostic prefix such as `cg` (i.e. this would be `cgbbs`).
78    cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>>,
79
80    /// The funclet status of each basic block
81    cleanup_kinds: Option<IndexVec<mir::BasicBlock, analyze::CleanupKind>>,
82
83    /// When targeting MSVC, this stores the cleanup info for each funclet BB.
84    /// This is initialized at the same time as the `landing_pads` entry for the
85    /// funclets' head block, i.e. when needed by an unwind / `cleanup_ret` edge.
86    funclets: IndexVec<mir::BasicBlock, Option<Bx::Funclet>>,
87
88    /// This stores the cached landing/cleanup pad block for a given BB.
89    // FIXME(eddyb) rename this to `eh_pads`.
90    landing_pads: IndexVec<mir::BasicBlock, Option<Bx::BasicBlock>>,
91
92    /// Cached unreachable block
93    unreachable_block: Option<Bx::BasicBlock>,
94
95    /// Cached terminate upon unwinding block and its reason. For non-wasm
96    /// targets, there is at most one such block per function, stored at index
97    /// `START_BLOCK`. For wasm targets, each funclet needs its own terminate
98    /// block, indexed by the cleanup block that is the funclet's head.
99    terminate_blocks: IndexVec<mir::BasicBlock, Option<(Bx::BasicBlock, UnwindTerminateReason)>>,
100
101    /// A bool flag for each basic block indicating whether it is a cold block.
102    /// A cold block is a block that is unlikely to be executed at runtime.
103    cold_blocks: IndexVec<mir::BasicBlock, bool>,
104
105    nop_landing_pads: DenseBitSet<mir::BasicBlock>,
106
107    /// The location where each MIR arg/var/tmp/ret is stored. This is
108    /// usually an `PlaceRef` representing an alloca, but not always:
109    /// sometimes we can skip the alloca and just store the value
110    /// directly using an `OperandRef`, which makes for tighter LLVM
111    /// IR. The conditions for using an `OperandRef` are as follows:
112    ///
113    /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
114    /// - the operand must never be referenced indirectly
115    ///     - we should not take its address using the `&` operator
116    ///     - nor should it appear in a place path like `tmp.a`
117    /// - the operand must be defined by an rvalue that can generate immediate
118    ///   values
119    ///
120    /// Avoiding allocs can also be important for certain intrinsics,
121    /// notably `expect`.
122    locals: locals::Locals<'tcx, Bx::Value>,
123
124    /// All `VarDebugInfo` from the MIR body, partitioned by `Local`.
125    /// This is `None` if no variable debuginfo/names are needed.
126    per_local_var_debug_info: Option<PerLocalVarDebugInfoIndexVec<'tcx, Bx::DIVariable>>,
127
128    /// Caller location propagated if this function has `#[track_caller]`.
129    caller_location: Option<OperandRef<'tcx, Bx::Value>>,
130}
131
132impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
133    pub fn monomorphize<T>(&self, value: T) -> T
134    where
135        T: Copy + TypeFoldable<TyCtxt<'tcx>>,
136    {
137        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs:137",
                        "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                        ::tracing_core::__macro_support::Option::Some(137u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("monomorphize: self.instance={0:?}",
                                                    self.instance) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("monomorphize: self.instance={:?}", self.instance);
138        self.instance.instantiate_mir_and_normalize_erasing_regions(
139            self.cx.tcx(),
140            self.cx.typing_env(),
141            ty::EarlyBinder::bind(self.cx.tcx(), value),
142        )
143    }
144}
145
146enum LocalRef<'tcx, V> {
147    Place(PlaceRef<'tcx, V>),
148    /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
149    /// `*p` is the wide pointer that references the actual unsized place.
150    ///
151    /// MIR only supports unsized args, not dynamically-sized locals, so
152    /// new unsized temps don't exist and we must reuse the referred-to place.
153    ///
154    /// FIXME: Since the removal of unsized locals in <https://github.com/rust-lang/rust/pull/142911>,
155    /// can we maybe use `Place` here? Or refactor it in another way? There are quite a few
156    /// `UnsizedPlace => bug` branches now.
157    UnsizedPlace(PlaceRef<'tcx, V>),
158    /// The backend [`OperandValue`] has already been generated.
159    Operand(OperandRef<'tcx, V>),
160    /// Will be a `Self::Operand` once we get to its definition.
161    PendingOperand,
162}
163
164pub enum IntrinsicResult<'tcx, V> {
165    /// This intrinsic created an operand without using the `result_place` argument.
166    ///
167    /// `codegen_call_terminator` will handle writing the result into the place,
168    /// if doing so is needed.
169    ///
170    /// The vast majority of intrinsics can do this, see MCP#970
171    Operand(OperandValue<V>),
172
173    /// The intrinsic wrote its result into the `result_place` argument.
174    ///
175    /// Most things don't need to do this, but there are some: `volatile_load`
176    /// of a non-scalar type, for example, has to.
177    WroteIntoPlace,
178
179    /// Another instance should be called instead. This is used to invoke intrinsic
180    /// default bodies in case an intrinsic is not implemented by the backend.
181    Fallback(ty::Instance<'tcx>),
182
183    /// Arguably this shouldn't exist, per MCP#620, but a bunch do it.
184    Err(ErrorGuaranteed),
185}
186
187impl<'tcx, V: CodegenObject> LocalRef<'tcx, V> {
188    fn new_operand(layout: TyAndLayout<'tcx>) -> LocalRef<'tcx, V> {
189        if layout.is_zst() {
190            // Zero-size temporaries aren't always initialized, which
191            // doesn't matter because they don't contain data, but
192            // we need something sufficiently aligned in the operand.
193            LocalRef::Operand(OperandRef::zero_sized(layout))
194        } else {
195            LocalRef::PendingOperand
196        }
197    }
198}
199
200///////////////////////////////////////////////////////////////////////////
201
202{}
#[allow(clippy :: suspicious_else_formatting)]
{
    let __tracing_attr_span;
    let __tracing_attr_guard;
    if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() ||
            { false } {
        __tracing_attr_span =
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("codegen_mir",
                                    "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(202u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                                    ::tracing_core::field::FieldSet::new(&[{
                                                        const NAME:
                                                            ::tracing::__macro_support::FieldName<{
                                                                ::tracing::__macro_support::FieldName::len("instance")
                                                            }> =
                                                            ::tracing::__macro_support::FieldName::new("instance");
                                                        NAME.as_str()
                                                    }], ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::SPAN)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let mut interest = ::tracing::subscriber::Interest::never();
                if ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                ::tracing::Level::DEBUG <=
                                    ::tracing::level_filters::LevelFilter::current() &&
                            { interest = __CALLSITE.interest(); !interest.is_never() }
                        &&
                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                            interest) {
                    let meta = __CALLSITE.metadata();
                    ::tracing::Span::new(meta,
                        &{
                                #[allow(unused_imports)]
                                use ::tracing::field::{debug, display, Value};
                                meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&instance)
                                                            as &dyn ::tracing::field::Value))])
                            })
                } else {
                    let span =
                        ::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
                    {};
                    span
                }
            };
        __tracing_attr_guard = __tracing_attr_span.enter();
    }

    #[warn(clippy :: suspicious_else_formatting)]
    {

        #[allow(unknown_lints, unreachable_code, clippy ::
        diverging_sub_expression, clippy :: empty_loop, clippy ::
        let_unit_value, clippy :: let_with_type_underscore, clippy ::
        needless_return, clippy :: unreachable)]
        if false {
            let __tracing_attr_fake_return: () = loop {};
            return __tracing_attr_fake_return;
        }
        {
            if !!instance.args.has_infer() {
                ::core::panicking::panic("assertion failed: !instance.args.has_infer()")
            };
            let tcx = cx.tcx();
            let llfn = cx.get_fn(instance);
            let mut mir = tcx.instance_mir(instance.def);
            let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
            {
                use ::tracing::__macro_support::Callsite as _;
                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                    {
                        static META: ::tracing::Metadata<'static> =
                            {
                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs:218",
                                    "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                                    ::tracing_core::__macro_support::Option::Some(218u32),
                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                                    ::tracing_core::field::FieldSet::new(&["message"],
                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                    ::tracing::metadata::Kind::EVENT)
                            };
                        ::tracing::callsite::DefaultCallsite::new(&META)
                    };
                let enabled =
                    ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                            ::tracing::Level::DEBUG <=
                                ::tracing::level_filters::LevelFilter::current() &&
                        {
                            let interest = __CALLSITE.interest();
                            !interest.is_never() &&
                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                    interest)
                        };
                if enabled {
                    (|value_set: ::tracing::field::ValueSet|
                                {
                                    let meta = __CALLSITE.metadata();
                                    ::tracing::Event::dispatch(meta, &value_set);
                                    ;
                                })({
                            #[allow(unused_imports)]
                            use ::tracing::field::{debug, display, Value};
                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("fn_abi: {0:?}",
                                                                fn_abi) as &dyn ::tracing::field::Value))])
                        });
                } else { ; }
            };
            let nop_landing_pads =
                tcx.find_noop_landing_pads_for_instance(mir, instance,
                    cx.typing_env());
            if tcx.features().ergonomic_clones() {
                let monomorphized_mir =
                    instance.instantiate_mir_and_normalize_erasing_regions(tcx,
                        cx.typing_env(), ty::EarlyBinder::bind(tcx, mir.clone()));
                mir =
                    tcx.arena.alloc(optimize_use_clone::<Bx>(cx,
                            monomorphized_mir));
            }
            let start_llbb = Bx::append_block(cx, llfn, "start");
            let mut start_bx = Bx::build(cx, start_llbb);
            if mir::traversal::mono_reachable(&mir, tcx,
                        instance).any(|(bb, block)|
                        {
                            (block.is_cleanup && !nop_landing_pads.contains(bb)) ||
                                #[allow(non_exhaustive_omitted_patterns)] match block.terminator().unwind()
                                    {
                                    Some(mir::UnwindAction::Terminate(_)) => true,
                                    _ => false,
                                }
                        }) {
                start_bx.set_personality_fn(cx.eh_personality());
            }
            let cleanup_kinds =
                base::wants_new_eh_instructions(&tcx.sess.target).then(||
                        analyze::cleanup_kinds(&mir, &nop_landing_pads));
            let cached_llbbs:
                    IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
                mir.basic_blocks.indices().map(|bb|
                            {
                                if bb == mir::START_BLOCK {
                                    CachedLlbb::Some(start_llbb)
                                } else { CachedLlbb::None }
                            }).collect();
            let mut fx =
                FunctionCx {
                    instance,
                    mir,
                    llfn,
                    fn_abi,
                    cx,
                    personality_slot: None,
                    cached_llbbs,
                    unreachable_block: None,
                    terminate_blocks: IndexVec::from_elem(None,
                        &mir.basic_blocks),
                    cleanup_kinds,
                    landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
                    funclets: IndexVec::from_fn_n(|_| None,
                        mir.basic_blocks.len()),
                    cold_blocks: find_cold_blocks(tcx, mir),
                    locals: locals::Locals::empty(),
                    debug_context: None,
                    per_local_var_debug_info: None,
                    caller_location: None,
                    nop_landing_pads,
                };
            fx.fill_function_debug_context(&mut start_bx);
            let (per_local_var_debug_info, consts_debug_info) =
                fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
            fx.per_local_var_debug_info = per_local_var_debug_info;
            let mut traversal_order =
                traversal::mono_reachable_reverse_postorder(mir, tcx,
                    instance);
            {
                let mut reachable =
                    DenseBitSet::new_empty(mir.basic_blocks.len());
                let mut to_visit =
                    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
                            [mir::START_BLOCK]));
                while let Some(next) = to_visit.pop() {
                    if !reachable.insert(next) { continue; }
                    let block = &mir.basic_blocks[next];
                    let successors = block.mono_successors(tcx, instance);
                    if let Some(mir::UnwindAction::Cleanup(target)) =
                                block.terminator().unwind() &&
                            fx.nop_landing_pads.contains(*target) {
                        to_visit.extend(successors.filter(|s| s != target));
                    } else { to_visit.extend(successors); }
                }
                traversal_order.retain(|bb| reachable.contains(*bb));
            }
            let memory_locals =
                analyze::non_ssa_locals(&fx, &traversal_order);
            let local_values =
                {
                    let args =
                        arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
                    let mut allocate_local =
                        |local: Local|
                            {
                                let decl = &mir.local_decls[local];
                                let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
                                if !!layout.ty.has_erasable_regions() {
                                    ::core::panicking::panic("assertion failed: !layout.ty.has_erasable_regions()")
                                };
                                if local == mir::RETURN_PLACE {
                                    match fx.fn_abi.ret.mode {
                                        PassMode::Indirect { .. } => {
                                            {
                                                use ::tracing::__macro_support::Callsite as _;
                                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                    {
                                                        static META: ::tracing::Metadata<'static> =
                                                            {
                                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs:330",
                                                                    "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                                                                    ::tracing_core::__macro_support::Option::Some(330u32),
                                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                    ::tracing::metadata::Kind::EVENT)
                                                            };
                                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                                    };
                                                let enabled =
                                                    ::tracing::Level::DEBUG <=
                                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                            ::tracing::Level::DEBUG <=
                                                                ::tracing::level_filters::LevelFilter::current() &&
                                                        {
                                                            let interest = __CALLSITE.interest();
                                                            !interest.is_never() &&
                                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                    interest)
                                                        };
                                                if enabled {
                                                    (|value_set: ::tracing::field::ValueSet|
                                                                {
                                                                    let meta = __CALLSITE.metadata();
                                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                                    ;
                                                                })({
                                                            #[allow(unused_imports)]
                                                            use ::tracing::field::{debug, display, Value};
                                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} (return place) -> place",
                                                                                                local) as &dyn ::tracing::field::Value))])
                                                        });
                                                } else { ; }
                                            };
                                            let llretptr = start_bx.get_param(0);
                                            return LocalRef::Place(PlaceRef::new_sized(llretptr,
                                                        layout));
                                        }
                                        PassMode::Cast { ref cast, .. } => {
                                            {
                                                use ::tracing::__macro_support::Callsite as _;
                                                static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                                    {
                                                        static META: ::tracing::Metadata<'static> =
                                                            {
                                                                ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs:335",
                                                                    "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                                                                    ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                                                                    ::tracing_core::__macro_support::Option::Some(335u32),
                                                                    ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                                                                    ::tracing_core::field::FieldSet::new(&["message"],
                                                                        ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                                    ::tracing::metadata::Kind::EVENT)
                                                            };
                                                        ::tracing::callsite::DefaultCallsite::new(&META)
                                                    };
                                                let enabled =
                                                    ::tracing::Level::DEBUG <=
                                                                ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                            ::tracing::Level::DEBUG <=
                                                                ::tracing::level_filters::LevelFilter::current() &&
                                                        {
                                                            let interest = __CALLSITE.interest();
                                                            !interest.is_never() &&
                                                                ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                                    interest)
                                                        };
                                                if enabled {
                                                    (|value_set: ::tracing::field::ValueSet|
                                                                {
                                                                    let meta = __CALLSITE.metadata();
                                                                    ::tracing::Event::dispatch(meta, &value_set);
                                                                    ;
                                                                })({
                                                            #[allow(unused_imports)]
                                                            use ::tracing::field::{debug, display, Value};
                                                            __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} (return place) -> place",
                                                                                                local) as &dyn ::tracing::field::Value))])
                                                        });
                                                } else { ; }
                                            };
                                            let size = cast.size(&start_bx).max(layout.size);
                                            return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx,
                                                        size, layout));
                                        }
                                        PassMode::IndirectUnsized { .. } =>
                                            ::rustc_span::macros::bug_impl(None,
                                                format_args!("unsized returns are not supported"),
                                                Location::caller()),
                                        _ => {}
                                    };
                                }
                                if memory_locals.contains(local) {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs:345",
                                                            "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(345u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} -> place",
                                                                                        local) as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                    if layout.is_unsized() {
                                        LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx,
                                                layout))
                                    } else {
                                        LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
                                    }
                                } else {
                                    {
                                        use ::tracing::__macro_support::Callsite as _;
                                        static __CALLSITE: ::tracing::callsite::DefaultCallsite =
                                            {
                                                static META: ::tracing::Metadata<'static> =
                                                    {
                                                        ::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs:352",
                                                            "rustc_codegen_ssa::mir", ::tracing::Level::DEBUG,
                                                            ::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/mir/mod.rs"),
                                                            ::tracing_core::__macro_support::Option::Some(352u32),
                                                            ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::mir"),
                                                            ::tracing_core::field::FieldSet::new(&["message"],
                                                                ::tracing_core::callsite::Identifier(&__CALLSITE)),
                                                            ::tracing::metadata::Kind::EVENT)
                                                    };
                                                ::tracing::callsite::DefaultCallsite::new(&META)
                                            };
                                        let enabled =
                                            ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::STATIC_MAX_LEVEL &&
                                                    ::tracing::Level::DEBUG <=
                                                        ::tracing::level_filters::LevelFilter::current() &&
                                                {
                                                    let interest = __CALLSITE.interest();
                                                    !interest.is_never() &&
                                                        ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                                                            interest)
                                                };
                                        if enabled {
                                            (|value_set: ::tracing::field::ValueSet|
                                                        {
                                                            let meta = __CALLSITE.metadata();
                                                            ::tracing::Event::dispatch(meta, &value_set);
                                                            ;
                                                        })({
                                                    #[allow(unused_imports)]
                                                    use ::tracing::field::{debug, display, Value};
                                                    __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("alloc: {0:?} -> operand",
                                                                                        local) as &dyn ::tracing::field::Value))])
                                                });
                                        } else { ; }
                                    };
                                    LocalRef::new_operand(layout)
                                }
                            };
                    let retptr = allocate_local(mir::RETURN_PLACE);
                    iter::once(retptr).chain(args.into_iter()).chain(mir.vars_and_temps_iter().map(allocate_local)).collect()
                };
            fx.initialize_locals(local_values);
            fx.debug_introduce_locals(&mut start_bx,
                consts_debug_info.unwrap_or_default());
            drop(start_bx);
            let mut unreached_blocks =
                DenseBitSet::new_filled(mir.basic_blocks.len());
            for bb in traversal_order {
                fx.codegen_block(bb);
                unreached_blocks.remove(bb);
            }
            for bb in unreached_blocks.iter() {
                fx.codegen_block_as_unreachable(bb);
            }
        }
    }
}#[instrument(level = "debug", skip(cx))]
203pub fn codegen_mir<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
204    cx: &'a Bx::CodegenCx,
205    instance: Instance<'tcx>,
206) {
207    assert!(!instance.args.has_infer());
208
209    let tcx = cx.tcx();
210    let llfn = cx.get_fn(instance);
211
212    let mut mir = tcx.instance_mir(instance.def);
213    // Note that the ABI logic has deduced facts about the functions' parameters based on the MIR we
214    // got here (`deduce_param_attrs`). That means we can *not* apply arbitrary further MIR
215    // transforms as that may invalidate those deduced facts!
216
217    let fn_abi = cx.fn_abi_of_instance(instance, ty::List::empty());
218    debug!("fn_abi: {:?}", fn_abi);
219
220    let nop_landing_pads = tcx.find_noop_landing_pads_for_instance(mir, instance, cx.typing_env());
221
222    if tcx.features().ergonomic_clones() {
223        let monomorphized_mir = instance.instantiate_mir_and_normalize_erasing_regions(
224            tcx,
225            cx.typing_env(),
226            ty::EarlyBinder::bind(tcx, mir.clone()),
227        );
228        mir = tcx.arena.alloc(optimize_use_clone::<Bx>(cx, monomorphized_mir));
229    }
230
231    let start_llbb = Bx::append_block(cx, llfn, "start");
232    let mut start_bx = Bx::build(cx, start_llbb);
233
234    if mir::traversal::mono_reachable(&mir, tcx, instance).any(|(bb, block)| {
235        (block.is_cleanup && !nop_landing_pads.contains(bb))
236            || matches!(block.terminator().unwind(), Some(mir::UnwindAction::Terminate(_)))
237    }) {
238        start_bx.set_personality_fn(cx.eh_personality());
239    }
240
241    let cleanup_kinds = base::wants_new_eh_instructions(&tcx.sess.target)
242        .then(|| analyze::cleanup_kinds(&mir, &nop_landing_pads));
243
244    let cached_llbbs: IndexVec<mir::BasicBlock, CachedLlbb<Bx::BasicBlock>> =
245        mir.basic_blocks
246            .indices()
247            .map(|bb| {
248                if bb == mir::START_BLOCK { CachedLlbb::Some(start_llbb) } else { CachedLlbb::None }
249            })
250            .collect();
251
252    let mut fx = FunctionCx {
253        instance,
254        mir,
255        llfn,
256        fn_abi,
257        cx,
258        personality_slot: None,
259        cached_llbbs,
260        unreachable_block: None,
261        terminate_blocks: IndexVec::from_elem(None, &mir.basic_blocks),
262        cleanup_kinds,
263        landing_pads: IndexVec::from_elem(None, &mir.basic_blocks),
264        funclets: IndexVec::from_fn_n(|_| None, mir.basic_blocks.len()),
265        cold_blocks: find_cold_blocks(tcx, mir),
266        locals: locals::Locals::empty(),
267        debug_context: None,
268        per_local_var_debug_info: None,
269        caller_location: None,
270        nop_landing_pads,
271    };
272
273    // It may seem like we should iterate over `required_consts` to ensure they all successfully
274    // evaluate; however, the `MirUsedCollector` already did that during the collection phase of
275    // monomorphization, and if there is an error during collection then codegen never starts -- so
276    // we don't have to do it again.
277
278    fx.fill_function_debug_context(&mut start_bx);
279
280    let (per_local_var_debug_info, consts_debug_info) =
281        fx.compute_per_local_var_debug_info(&mut start_bx).unzip();
282    fx.per_local_var_debug_info = per_local_var_debug_info;
283
284    let mut traversal_order = traversal::mono_reachable_reverse_postorder(mir, tcx, instance);
285
286    // Filter out blocks that won't be codegen'd because of nop_landing_pads optimization.
287    // FIXME: We might want to integrate the nop_landing_pads analysis into mono reachability.
288    {
289        let mut reachable = DenseBitSet::new_empty(mir.basic_blocks.len());
290        let mut to_visit = vec![mir::START_BLOCK];
291        while let Some(next) = to_visit.pop() {
292            if !reachable.insert(next) {
293                continue;
294            }
295
296            let block = &mir.basic_blocks[next];
297            let successors = block.mono_successors(tcx, instance);
298
299            if let Some(mir::UnwindAction::Cleanup(target)) = block.terminator().unwind()
300                && fx.nop_landing_pads.contains(*target)
301            {
302                // This edge will not be followed when we actually codegen, so skip generating it here.
303                //
304                // It's guaranteed that the cleanup block (`target`) occurs only in
305                // UnwindAction::Cleanup(...) -- i.e., we can't incorrectly filter too much here --
306                // because cleanup transitions must happen via UnwindAction::Cleanup.
307                to_visit.extend(successors.filter(|s| s != target));
308            } else {
309                to_visit.extend(successors);
310            }
311        }
312
313        traversal_order.retain(|bb| reachable.contains(*bb));
314    }
315
316    let memory_locals = analyze::non_ssa_locals(&fx, &traversal_order);
317
318    // Allocate variable and temp allocas
319    let local_values = {
320        let args = arg_local_refs(&mut start_bx, &mut fx, &memory_locals);
321
322        let mut allocate_local = |local: Local| {
323            let decl = &mir.local_decls[local];
324            let layout = start_bx.layout_of(fx.monomorphize(decl.ty));
325            assert!(!layout.ty.has_erasable_regions());
326
327            if local == mir::RETURN_PLACE {
328                match fx.fn_abi.ret.mode {
329                    PassMode::Indirect { .. } => {
330                        debug!("alloc: {:?} (return place) -> place", local);
331                        let llretptr = start_bx.get_param(0);
332                        return LocalRef::Place(PlaceRef::new_sized(llretptr, layout));
333                    }
334                    PassMode::Cast { ref cast, .. } => {
335                        debug!("alloc: {:?} (return place) -> place", local);
336                        let size = cast.size(&start_bx).max(layout.size);
337                        return LocalRef::Place(PlaceRef::alloca_size(&mut start_bx, size, layout));
338                    }
339                    PassMode::IndirectUnsized { .. } => bug!("unsized returns are not supported"),
340                    _ => {}
341                };
342            }
343
344            if memory_locals.contains(local) {
345                debug!("alloc: {:?} -> place", local);
346                if layout.is_unsized() {
347                    LocalRef::UnsizedPlace(PlaceRef::alloca_unsized_indirect(&mut start_bx, layout))
348                } else {
349                    LocalRef::Place(PlaceRef::alloca(&mut start_bx, layout))
350                }
351            } else {
352                debug!("alloc: {:?} -> operand", local);
353                LocalRef::new_operand(layout)
354            }
355        };
356
357        let retptr = allocate_local(mir::RETURN_PLACE);
358        iter::once(retptr)
359            .chain(args.into_iter())
360            .chain(mir.vars_and_temps_iter().map(allocate_local))
361            .collect()
362    };
363    fx.initialize_locals(local_values);
364
365    // Apply debuginfo to the newly allocated locals.
366    fx.debug_introduce_locals(&mut start_bx, consts_debug_info.unwrap_or_default());
367
368    // The builders will be created separately for each basic block at `codegen_block`.
369    // So drop the builder of `start_llbb` to avoid having two at the same time.
370    drop(start_bx);
371
372    let mut unreached_blocks = DenseBitSet::new_filled(mir.basic_blocks.len());
373    // Codegen the body of each reachable block using our reverse postorder list.
374    for bb in traversal_order {
375        fx.codegen_block(bb);
376        unreached_blocks.remove(bb);
377    }
378
379    // FIXME: These empty unreachable blocks are *mostly* a waste. They are occasionally
380    // targets for a SwitchInt terminator, but the reimplementation of the mono-reachable
381    // simplification in SwitchInt lowering sometimes misses cases that
382    // mono_reachable_reverse_postorder manages to figure out.
383    // The solution is to do something like post-mono GVN. But for now we have this hack.
384    for bb in unreached_blocks.iter() {
385        fx.codegen_block_as_unreachable(bb);
386    }
387}
388
389/// Replace `clone` calls that come from `use` statements with direct copies if possible.
390// FIXME: Move this function to mir::transform when post-mono MIR passes land.
391fn optimize_use_clone<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
392    cx: &'a Bx::CodegenCx,
393    mut mir: Body<'tcx>,
394) -> Body<'tcx> {
395    let tcx = cx.tcx();
396
397    if tcx.features().ergonomic_clones() {
398        for bb in mir.basic_blocks.as_mut() {
399            let mir::TerminatorKind::Call {
400                args,
401                destination,
402                target,
403                call_source: mir::CallSource::Use,
404                ..
405            } = &bb.terminator().kind
406            else {
407                continue;
408            };
409
410            // CallSource::Use calls always use 1 argument.
411            {
    match (&args.len(), &1) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(args.len(), 1);
412            let arg = &args[0];
413
414            // These types are easily available from locals, so check that before
415            // doing DefId lookups to figure out what we're actually calling.
416            let arg_ty = arg.node.ty(&mir.local_decls, tcx);
417
418            let ty::Ref(_region, inner_ty, mir::Mutability::Not) = *arg_ty.kind() else { continue };
419
420            if !tcx.type_is_copy_modulo_regions(cx.typing_env(), inner_ty) {
421                continue;
422            }
423
424            let Some(arg_place) = arg.node.place() else { continue };
425
426            let destination_block = target.unwrap();
427
428            bb.statements.push(mir::Statement::new(
429                bb.terminator().source_info,
430                mir::StatementKind::Assign(Box::new((
431                    *destination,
432                    mir::Rvalue::Use(
433                        mir::Operand::Copy(
434                            arg_place.project_deeper(&[mir::ProjectionElem::Deref], tcx),
435                        ),
436                        mir::WithRetag::Yes,
437                    ),
438                ))),
439            ));
440
441            bb.terminator_mut().kind = mir::TerminatorKind::goto(destination_block);
442        }
443    }
444
445    mir
446}
447
448/// Produces, for each argument, a `Value` pointing at the
449/// argument's value. As arguments are places, these are always
450/// indirect.
451fn arg_local_refs<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
452    bx: &mut Bx,
453    fx: &mut FunctionCx<'a, 'tcx, Bx>,
454    memory_locals: &DenseBitSet<mir::Local>,
455) -> Vec<LocalRef<'tcx, Bx::Value>> {
456    let mir = fx.mir;
457    let mut idx = 0;
458    let mut llarg_idx = fx.fn_abi.ret.is_indirect() as usize;
459
460    let mut num_untupled = None;
461
462    let codegen_fn_attrs = bx.tcx().codegen_instance_attrs(fx.instance.def);
463    if codegen_fn_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
464        return ::alloc::vec::Vec::new()vec![];
465    }
466
467    let mut args = mir
468        .args_iter()
469        .enumerate()
470        .map(|(arg_index, local)| {
471            let arg_decl = &mir.local_decls[local];
472            let arg_ty = fx.monomorphize(arg_decl.ty);
473
474            // FIXME(splat): re-tuple splatted arguments that were un-tupled in the ABI
475            if Some(local) == mir.spread_arg {
476                // This argument (e.g., the last argument in the "rust-call" ABI)
477                // is a tuple that was spread at the ABI level and now we have
478                // to reconstruct it into a tuple local variable, from multiple
479                // individual LLVM function arguments.
480                let ty::Tuple(tupled_arg_tys) = arg_ty.kind() else {
481                    ::rustc_span::macros::bug_impl(None,
    format_args!("spread argument isn\'t a tuple?!"), Location::caller());bug!("spread argument isn't a tuple?!");
482                };
483
484                let layout = bx.layout_of(arg_ty);
485
486                // FIXME: support unsized params in "rust-call" ABI
487                if layout.is_unsized() {
488                    ::rustc_span::macros::bug_impl(Some(arg_decl.source_info.span),
    format_args!("\"rust-call\" ABI does not support unsized params"),
    Location::caller());span_bug!(
489                        arg_decl.source_info.span,
490                        "\"rust-call\" ABI does not support unsized params",
491                    );
492                }
493
494                let place = PlaceRef::alloca(bx, layout);
495                for i in 0..tupled_arg_tys.len() {
496                    let arg = &fx.fn_abi.args[idx];
497                    idx += 1;
498                    if let PassMode::Cast { pad_i32_count, .. } = arg.mode {
499                        llarg_idx += usize::from(pad_i32_count);
500                    }
501                    let pr_field = place.project_field(bx, i);
502                    bx.store_fn_arg(arg, &mut llarg_idx, pr_field);
503                }
504                {
    match (&None, &num_untupled.replace(tupled_arg_tys.len())) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("Replaced existing num_untupled")));
            }
        }
    }
};assert_eq!(
505                    None,
506                    num_untupled.replace(tupled_arg_tys.len()),
507                    "Replaced existing num_untupled"
508                );
509
510                return LocalRef::Place(place);
511            }
512
513            if fx.fn_abi.c_variadic && arg_index == fx.fn_abi.args.len() {
514                let va_list = PlaceRef::alloca(bx, bx.layout_of(arg_ty));
515
516                // Explicitly start the lifetime of the `va_list`, improves LLVM codegen.
517                bx.lifetime_start(va_list.val.llval, va_list.layout.size);
518
519                bx.va_start(va_list.val.llval);
520
521                return LocalRef::Place(va_list);
522            }
523
524            let arg = &fx.fn_abi.args[idx];
525            idx += 1;
526            if let PassMode::Cast { pad_i32_count, .. } = arg.mode {
527                llarg_idx += usize::from(pad_i32_count);
528            }
529
530            if !memory_locals.contains(local) {
531                // We don't have to cast or keep the argument in the alloca.
532                // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
533                // of putting everything in allocas just so we can use llvm.dbg.declare.
534                let local = |op| LocalRef::Operand(op);
535                match arg.mode {
536                    PassMode::Ignore => {
537                        return local(OperandRef::zero_sized(arg.layout));
538                    }
539                    PassMode::Direct(_) => {
540                        let llarg = bx.get_param(llarg_idx);
541                        llarg_idx += 1;
542                        if true {
    if !arg.layout.backend_repr.is_scalar_or_simd() {
        ::core::panicking::panic("assertion failed: arg.layout.backend_repr.is_scalar_or_simd()")
    };
};debug_assert!(arg.layout.backend_repr.is_scalar_or_simd());
543                        return local(OperandRef {
544                            val: OperandValue::Immediate(llarg),
545                            layout: arg.layout,
546                            move_annotation: None,
547                        });
548                    }
549                    PassMode::Pair(..) => {
550                        let (a, b) = (bx.get_param(llarg_idx), bx.get_param(llarg_idx + 1));
551                        llarg_idx += 2;
552
553                        return local(OperandRef {
554                            val: OperandValue::Pair(a, b),
555                            layout: arg.layout,
556                            move_annotation: None,
557                        });
558                    }
559                    _ => {}
560                }
561            }
562
563            match arg.mode {
564                // Sized indirect arguments
565                PassMode::Indirect { attrs, address_space: _, mode } => {
566                    // Don't copy an indirect argument to an alloca, the caller already put it
567                    // in a temporary alloca and gave it up.
568                    // AmdgpuKernelArg/byref arguments must not be modified, so always create a
569                    // local alloca for them.
570                    // If the argument is underaligned, then we need to copy it to a higher-aligned
571                    // alloca.
572                    // FIXME: lifetimes
573                    let mut needs_alloca = mode == IndirectMode::AmdgpuKernelArg;
574                    if let Some(pointee_align) = attrs.pointee_align
575                        && pointee_align < arg.layout.align.abi
576                    {
577                        needs_alloca = true;
578                    }
579                    if needs_alloca {
580                        let tmp = PlaceRef::alloca(bx, arg.layout);
581                        bx.store_fn_arg(arg, &mut llarg_idx, tmp);
582                        LocalRef::Place(tmp)
583                    } else {
584                        let llarg = bx.get_param(llarg_idx);
585                        llarg_idx += 1;
586                        LocalRef::Place(PlaceRef::new_sized(llarg, arg.layout))
587                    }
588                }
589                // Unsized indirect arguments
590                PassMode::IndirectUnsized { attrs: _, meta_attrs: _ } => {
591                    // As the storage for the indirect argument lives during
592                    // the whole function call, we just copy the wide pointer.
593                    let llarg = bx.get_param(llarg_idx);
594                    llarg_idx += 1;
595                    let llextra = bx.get_param(llarg_idx);
596                    llarg_idx += 1;
597                    let indirect_operand = OperandValue::Pair(llarg, llextra);
598
599                    let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout);
600                    indirect_operand.store(bx, tmp);
601                    LocalRef::UnsizedPlace(tmp)
602                }
603                _ => {
604                    let tmp = PlaceRef::alloca(bx, arg.layout);
605                    bx.store_fn_arg(arg, &mut llarg_idx, tmp);
606                    LocalRef::Place(tmp)
607                }
608            }
609        })
610        .collect::<Vec<_>>();
611    if bx.tcx().sess.opts.unstable_opts.codegen_emit_retag.is_some() {
612        args = args
613            .iter()
614            .map(|arg| match arg {
615                &LocalRef::Place(place_ref) => {
616                    fx.codegen_retag_place(bx, place_ref, true);
617                    LocalRef::Place(place_ref)
618                }
619                &LocalRef::UnsizedPlace(place_ref) => {
620                    let operand = bx.load_operand(place_ref);
621                    let retagged = fx.codegen_retag_operand(bx, operand, true);
622                    if !#[allow(non_exhaustive_omitted_patterns)] match retagged.val {
            OperandValue::Pair(_, _) => true,
            _ => false,
        } {
    ::core::panicking::panic("assertion failed: matches!(retagged.val, OperandValue::Pair(_, _))")
};assert!(matches!(retagged.val, OperandValue::Pair(_, _)));
623                    retagged.val.store(bx, place_ref);
624                    LocalRef::UnsizedPlace(place_ref)
625                }
626                &LocalRef::Operand(operand_ref) => {
627                    let retagged = fx.codegen_retag_operand(bx, operand_ref, true);
628                    LocalRef::Operand(retagged)
629                }
630                LocalRef::PendingOperand => LocalRef::PendingOperand,
631            })
632            .collect::<Vec<_>>();
633        // If we branched during retagging, then we need to update the
634        // start block to the new location.
635        fx.cached_llbbs[mir::START_BLOCK] = CachedLlbb::Some(bx.llbb());
636    }
637
638    if fx.instance.def.requires_caller_location(bx.tcx()) {
639        let mir_args = if let Some(num_untupled) = num_untupled {
640            // Subtract off the tupled argument that gets 'expanded'
641            args.len() - 1 + num_untupled
642        } else {
643            args.len()
644        };
645        {
    match (&fx.fn_abi.args.len(), &(mir_args + 1)) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val,
                    ::core::option::Option::Some(format_args!("#[track_caller] instance {0:?} must have 1 more argument in their ABI than in their MIR",
                            fx.instance)));
            }
        }
    }
};assert_eq!(
646            fx.fn_abi.args.len(),
647            mir_args + 1,
648            "#[track_caller] instance {:?} must have 1 more argument in their ABI than in their MIR",
649            fx.instance
650        );
651
652        let arg = fx.fn_abi.args.last().unwrap();
653        match arg.mode {
654            PassMode::Direct(_) => (),
655            _ => ::rustc_span::macros::bug_impl(None,
    format_args!("caller location must be PassMode::Direct, found {0:?}",
        arg.mode), Location::caller())bug!("caller location must be PassMode::Direct, found {:?}", arg.mode),
656        }
657
658        fx.caller_location = Some(OperandRef {
659            val: OperandValue::Immediate(bx.get_param(llarg_idx)),
660            layout: arg.layout,
661            move_annotation: None,
662        });
663    }
664
665    args
666}
667
668fn find_cold_blocks<'tcx>(
669    tcx: TyCtxt<'tcx>,
670    mir: &mir::Body<'tcx>,
671) -> IndexVec<mir::BasicBlock, bool> {
672    let local_decls = &mir.local_decls;
673
674    let mut cold_blocks: IndexVec<mir::BasicBlock, bool> =
675        IndexVec::from_elem(false, &mir.basic_blocks);
676
677    // Traverse all basic blocks from end of the function to the start.
678    for (bb, bb_data) in traversal::postorder(mir) {
679        let terminator = bb_data.terminator();
680
681        match terminator.kind {
682            // If a BB ends with a call to a cold function, mark it as cold.
683            mir::TerminatorKind::Call { ref func, .. }
684            | mir::TerminatorKind::TailCall { ref func, .. }
685                if let ty::FnDef(def_id, ..) = *func.ty(local_decls, tcx).kind()
686                    && let attrs = tcx.codegen_fn_attrs(def_id)
687                    && attrs.flags.contains(CodegenFnAttrFlags::COLD) =>
688            {
689                cold_blocks[bb] = true;
690                continue;
691            }
692
693            // If a BB ends with an `unreachable`, also mark it as cold.
694            mir::TerminatorKind::Unreachable => {
695                cold_blocks[bb] = true;
696                continue;
697            }
698
699            _ => {}
700        }
701
702        // If all successors of a BB are cold and there's at least one of them, mark this BB as cold
703        let mut succ = terminator.successors();
704        if let Some(first) = succ.next()
705            && cold_blocks[first]
706            && succ.all(|s| cold_blocks[s])
707        {
708            cold_blocks[bb] = true;
709        }
710    }
711
712    cold_blocks
713}