Skip to main content

cranelift_codegen/
inline.rs

1//! Function inlining infrastructure.
2//!
3//! This module provides "inlining as a library" to Cranelift users; it does
4//! _not_ provide a complete, off-the-shelf inlining solution. Cranelift's
5//! compilation context is per-function and does not encompass the full call
6//! graph. It does not know which functions are hot and which are cold, which
7//! have been marked the equivalent of `#[inline(never)]`, etc... Only the
8//! Cranelift user can understand these aspects of the full compilation
9//! pipeline, and these things can be very different between (say) Wasmtime and
10//! `cg_clif`. Therefore, this module does not attempt to define heuristics for
11//! when inlining a particular call is likely beneficial. This module only
12//! provides hooks for the Cranelift user to define whether a given call should
13//! be inlined or not, and the mechanics to inline a callee into a particular
14//! call site when directed to do so by the Cranelift user.
15//!
16//! The top-level inlining entry point during Cranelift compilation is
17//! [`Context::inline`][crate::Context::inline]. It takes an [`Inline`] trait
18//! implementation, which is authored by the Cranelift user and directs
19//! Cranelift whether to inline a particular call, and, when inlining, gives
20//! Cranelift the body of the callee that is to be inlined.
21
22use crate::cursor::{Cursor as _, FuncCursor};
23use crate::ir::{self, DebugTag, ExceptionTableData, ExceptionTableItem, InstBuilder as _};
24use crate::isa::CallConv;
25use crate::result::CodegenResult;
26use crate::trace;
27use crate::traversals::Dfs;
28use alloc::borrow::Cow;
29use alloc::vec::Vec;
30use cranelift_entity::{SecondaryMap, packed_option::PackedOption};
31use smallvec::SmallVec;
32
33type SmallValueVec = SmallVec<[ir::Value; 8]>;
34type SmallBlockArgVec = SmallVec<[ir::BlockArg; 8]>;
35type SmallBlockCallVec = SmallVec<[ir::BlockCall; 8]>;
36
37/// A command directing Cranelift whether or not to inline a particular call.
38pub enum InlineCommand<'a> {
39    /// Keep the call as-is, out-of-line, and do not inline the callee.
40    KeepCall,
41
42    /// Inline the call, using this function as the body of the callee.
43    ///
44    /// It is the `Inline` implementor's responsibility to ensure that this
45    /// function is the correct callee. Providing the wrong function may result
46    /// in panics during compilation or incorrect runtime behavior.
47    Inline {
48        /// The callee function's body.
49        callee: Cow<'a, ir::Function>,
50        /// Whether to visit any function calls within the callee body after
51        /// inlining and consider them for further inlining.
52        visit_callee: bool,
53    },
54}
55
56/// A trait for directing Cranelift whether to inline a particular call or not.
57///
58/// Used in combination with the [`Context::inline`][crate::Context::inline]
59/// method.
60pub trait Inline {
61    /// A hook invoked for each direct call instruction in a function, whose
62    /// result determines whether Cranelift should inline a given call.
63    ///
64    /// The Cranelift user is responsible for defining their own heuristics and
65    /// deciding whether inlining the call is beneficial.
66    ///
67    /// When returning a function and directing Cranelift to inline its body
68    /// into the call site, the `Inline` implementer must ensure the following:
69    ///
70    /// * The returned function's signature exactly matches the `callee`
71    ///   `FuncRef`'s signature.
72    ///
73    /// * The returned function must be legalized.
74    ///
75    /// * The returned function must be valid (i.e. it must pass the CLIF
76    ///   verifier).
77    ///
78    /// * The returned function is a correct and valid implementation of the
79    ///   `callee` according to your language's semantics.
80    ///
81    /// Failure to uphold these invariants may result in panics during
82    /// compilation or incorrect runtime behavior in the generated code.
83    fn inline(
84        &mut self,
85        caller: &ir::Function,
86        call_inst: ir::Inst,
87        call_opcode: ir::Opcode,
88        callee: ir::FuncRef,
89        call_args: &[ir::Value],
90    ) -> InlineCommand<'_>;
91}
92
93impl<'a, T> Inline for &'a mut T
94where
95    T: Inline,
96{
97    fn inline(
98        &mut self,
99        caller: &ir::Function,
100        inst: ir::Inst,
101        opcode: ir::Opcode,
102        callee: ir::FuncRef,
103        args: &[ir::Value],
104    ) -> InlineCommand<'_> {
105        (*self).inline(caller, inst, opcode, callee, args)
106    }
107}
108
109/// Walk the given function, invoke the `Inline` implementation for each call
110/// instruction, and inline the callee when directed to do so.
111///
112/// Returns whether any call was inlined.
113pub(crate) fn do_inlining(
114    func: &mut ir::Function,
115    mut inliner: impl Inline,
116) -> CodegenResult<bool> {
117    trace!("function {} before inlining: {}", func.name, func);
118
119    let mut inlined_any = false;
120    let mut allocs = InliningAllocs::default();
121
122    let mut cursor = FuncCursor::new(func);
123    'block_loop: while let Some(block) = cursor.next_block() {
124        // Always keep track of our previous cursor position. Assuming that the
125        // current position is a function call that we will inline, then the
126        // previous position is just before the inlined callee function. After
127        // inlining a call, the Cranelift user can decide whether to consider
128        // any function calls in the inlined callee for further inlining or
129        // not. When they do, then we back up to this previous cursor position
130        // so that our traversal will then continue over the inlined body.
131        let mut prev_pos;
132
133        while let Some(inst) = {
134            prev_pos = cursor.position();
135            cursor.next_inst()
136        } {
137            // Make sure that `block` is always `inst`'s block, even with all of
138            // our cursor-position-updating and block-splitting-during-inlining
139            // shenanigans below.
140            debug_assert_eq!(Some(block), cursor.func.layout.inst_block(inst));
141
142            match cursor.func.dfg.insts[inst] {
143                ir::InstructionData::Call { func_ref, .. }
144                    if cursor.func.dfg.ext_funcs[func_ref].patchable =>
145                {
146                    // Can't inline patchable calls; they need to
147                    // remain patchable and inlining the whole body is
148                    // decidedly *not* patchable!
149                }
150
151                ir::InstructionData::Call {
152                    opcode: opcode @ ir::Opcode::Call | opcode @ ir::Opcode::ReturnCall,
153                    args: _,
154                    func_ref,
155                } => {
156                    trace!(
157                        "considering call site for inlining: {inst}: {}",
158                        cursor.func.dfg.display_inst(inst),
159                    );
160                    let args = cursor.func.dfg.inst_args(inst);
161                    match inliner.inline(&cursor.func, inst, opcode, func_ref, args) {
162                        InlineCommand::KeepCall => {
163                            trace!("  --> keeping call");
164                        }
165                        InlineCommand::Inline {
166                            callee,
167                            visit_callee,
168                        } => {
169                            if can_inline(cursor.func, &callee) {
170                                let last_inlined_block = inline_one(
171                                    &mut allocs,
172                                    cursor.func,
173                                    func_ref,
174                                    block,
175                                    inst,
176                                    opcode,
177                                    &callee,
178                                    None,
179                                )?;
180                                inlined_any = true;
181                                if visit_callee {
182                                    cursor.set_position(prev_pos);
183                                } else {
184                                    // Arrange it so that the `next_block()` loop
185                                    // will continue to the next block that is not
186                                    // associated with the just-inlined callee.
187                                    cursor.goto_bottom(last_inlined_block);
188                                    continue 'block_loop;
189                                }
190                            }
191                        }
192                    }
193                }
194                ir::InstructionData::TryCall {
195                    opcode: opcode @ ir::Opcode::TryCall,
196                    args: _,
197                    func_ref,
198                    exception,
199                } => {
200                    trace!(
201                        "considering call site for inlining: {inst}: {}",
202                        cursor.func.dfg.display_inst(inst),
203                    );
204                    let args = cursor.func.dfg.inst_args(inst);
205                    match inliner.inline(&cursor.func, inst, opcode, func_ref, args) {
206                        InlineCommand::KeepCall => {
207                            trace!("  --> keeping call");
208                        }
209                        InlineCommand::Inline {
210                            callee,
211                            visit_callee,
212                        } => {
213                            if can_inline(cursor.func, &callee) {
214                                let last_inlined_block = inline_one(
215                                    &mut allocs,
216                                    cursor.func,
217                                    func_ref,
218                                    block,
219                                    inst,
220                                    opcode,
221                                    &callee,
222                                    Some(exception),
223                                )?;
224                                inlined_any = true;
225                                if visit_callee {
226                                    cursor.set_position(prev_pos);
227                                } else {
228                                    // Arrange it so that the `next_block()` loop
229                                    // will continue to the next block that is not
230                                    // associated with the just-inlined callee.
231                                    cursor.goto_bottom(last_inlined_block);
232                                    continue 'block_loop;
233                                }
234                            }
235                        }
236                    }
237                }
238                ir::InstructionData::CallIndirect { .. }
239                | ir::InstructionData::TryCallIndirect { .. } => {
240                    // Can't inline indirect calls; need to have some earlier
241                    // pass rewrite them into direct calls first, when possible.
242                }
243                _ => {
244                    debug_assert!(
245                        !cursor.func.dfg.insts[inst].opcode().is_call(),
246                        "should have matched all call instructions, but found: {inst}: {}",
247                        cursor.func.dfg.display_inst(inst),
248                    );
249                }
250            }
251        }
252    }
253
254    if inlined_any {
255        trace!("function {} after inlining: {}", func.name, func);
256    } else {
257        trace!("function {} did not have any callees inlined", func.name);
258    }
259
260    Ok(inlined_any)
261}
262
263/// Returns whether `callee` is allowed to be inlined into `caller`. Future ad
264/// hoc rules can accumulate here.
265fn can_inline(caller: &ir::Function, callee: &ir::Function) -> bool {
266    // `interrupt_poll` can occur only in functions with the `tail` calling
267    // convention, so don't inline functions using it into those with other
268    // conventions.
269    if caller.signature.call_conv != CallConv::Tail
270        // A verified non-`tail` callee can't contain `interrupt_poll`. This
271        // saves us scanning through the whole function.
272        && callee.signature.call_conv == CallConv::Tail
273        && contains_opcode(callee, ir::Opcode::InterruptPoll)
274    {
275        trace!(
276            "  --> keeping call because callee uses `interrupt_poll` and caller doesn't use `tail` convention"
277        );
278        return false;
279    }
280
281    true
282}
283
284/// Returns whether a function contains a certain opcode.
285fn contains_opcode(func: &ir::Function, opcode: ir::Opcode) -> bool {
286    func.layout
287        .blocks()
288        .flat_map(|b| func.layout.block_insts(b))
289        .any(|i| func.dfg.insts[i].opcode() == opcode)
290}
291
292#[derive(Default)]
293struct InliningAllocs {
294    /// Map from callee value to inlined caller value.
295    values: SecondaryMap<ir::Value, PackedOption<ir::Value>>,
296
297    /// Map from callee constant to inlined caller constant.
298    ///
299    /// Not in `EntityMap` because these are hash-consed inside the
300    /// `ir::Function`.
301    constants: SecondaryMap<ir::Constant, PackedOption<ir::Constant>>,
302
303    /// Map from callee to inlined caller external name refs.
304    ///
305    /// Not in `EntityMap` because these are hash-consed inside the
306    /// `ir::Function`.
307    user_external_name_refs:
308        SecondaryMap<ir::UserExternalNameRef, PackedOption<ir::UserExternalNameRef>>,
309
310    /// The set of _caller_ inlined call instructions that need exception table
311    /// fixups at the end of inlining.
312    ///
313    /// This includes all kinds of non-returning calls, not just the literal
314    /// `call` instruction: `call_indirect`, `try_call`, `try_call_indirect`,
315    /// etc... However, it does not include `return_call` and
316    /// `return_call_indirect` instructions because the caller cannot catch
317    /// exceptions that those calls throw because the caller is no longer on the
318    /// stack as soon as they are executed.
319    ///
320    /// Note: this is a simple `Vec`, and not an `EntitySet`, because it is very
321    /// sparse: most of the caller's instructions are not inlined call
322    /// instructions. Additionally, we require deterministic iteration order and
323    /// do not require set-membership testing, so a hash set is not a good
324    /// choice either.
325    calls_needing_exception_table_fixup: Vec<ir::Inst>,
326}
327
328impl InliningAllocs {
329    fn reset(&mut self, callee: &ir::Function) {
330        let InliningAllocs {
331            values,
332            constants,
333            user_external_name_refs,
334            calls_needing_exception_table_fixup,
335        } = self;
336
337        values.clear();
338        values.resize(callee.dfg.len_values());
339
340        constants.clear();
341        constants.resize(callee.dfg.constants.len());
342
343        user_external_name_refs.clear();
344        user_external_name_refs.resize(callee.params.user_named_funcs().len());
345
346        // Note: We do not reserve capacity for
347        // `calls_needing_exception_table_fixup` because it is a sparse set and
348        // we don't know how large it needs to be ahead of time.
349        calls_needing_exception_table_fixup.clear();
350    }
351
352    /// Translate a callee `ir::ExternalName` into the caller.
353    ///
354    /// Must only be called after `create_user_external_name_refs`.
355    fn inlined_external_name(&self, name: &ir::ExternalName) -> ir::ExternalName {
356        match name {
357            ir::ExternalName::User(name_ref) => {
358                ir::ExternalName::User(self.user_external_name_refs[*name_ref].expect(
359                    "should have translated all `ir::UserExternalNameRef`s before translating \
360                     entities that reference them",
361                ))
362            }
363            ir::ExternalName::TestCase(_)
364            | ir::ExternalName::LibCall(_)
365            | ir::ExternalName::KnownSymbol(_) => name.clone(),
366        }
367    }
368
369    fn set_inlined_value(
370        &mut self,
371        callee: &ir::Function,
372        callee_val: ir::Value,
373        inlined_val: ir::Value,
374    ) {
375        trace!("  --> callee {callee_val:?} = inlined {inlined_val:?}");
376        debug_assert!(self.values[callee_val].is_none());
377        let resolved_callee_val = callee.dfg.resolve_aliases(callee_val);
378        debug_assert!(self.values[resolved_callee_val].is_none());
379        self.values[resolved_callee_val] = Some(inlined_val).into();
380    }
381
382    fn get_inlined_value(&self, callee: &ir::Function, callee_val: ir::Value) -> Option<ir::Value> {
383        let resolved_callee_val = callee.dfg.resolve_aliases(callee_val);
384        self.values[resolved_callee_val].expand()
385    }
386}
387
388/// Inline one particular function call.
389///
390/// Returns the last inlined block in the layout.
391fn inline_one(
392    allocs: &mut InliningAllocs,
393    func: &mut ir::Function,
394    callee_func_ref: ir::FuncRef,
395    call_block: ir::Block,
396    call_inst: ir::Inst,
397    call_opcode: ir::Opcode,
398    callee: &ir::Function,
399    call_exception_table: Option<ir::ExceptionTable>,
400) -> CodegenResult<ir::Block> {
401    trace!(
402        "Inlining call {call_inst:?}: {}\n\
403         with callee = {callee:?}",
404        func.dfg.display_inst(call_inst)
405    );
406
407    // Type check callee signature.
408    let expected_callee_sig = func.dfg.ext_funcs[callee_func_ref].signature;
409    let expected_callee_sig = &func.dfg.signatures[expected_callee_sig];
410    assert_eq!(expected_callee_sig, &callee.signature);
411
412    allocs.reset(callee);
413
414    // First, append various callee entity arenas to the end of the caller's
415    // entity arenas.
416    let entity_map = create_entities(allocs, func, callee)?;
417
418    // Inlined prologue: split the call instruction's block at the point of the
419    // call and replace the call with a jump.
420    let return_block = split_off_return_block(func, call_inst, call_opcode, callee);
421    let call_stack_map = replace_call_with_jump(allocs, func, call_inst, callee, &entity_map);
422
423    // Prepare for translating the actual instructions by inserting the inlined
424    // blocks into the caller's layout in the same order that they appear in the
425    // callee.
426    let mut last_inlined_block = inline_block_layout(func, call_block, callee, &entity_map);
427
428    // Get a copy of debug tags on the call instruction; these are
429    // prepended to debug tags on inlined instructions. Remove them
430    // from the call itself as it will be rewritten to a jump (which
431    // cannot have tags).
432    let call_debug_tags = func.debug_tags.get(call_inst).to_vec();
433    func.debug_tags.set(call_inst, []);
434
435    // Translate each instruction from the callee into the caller,
436    // appending them to their associated block in the caller.
437    //
438    // Note that we iterate over the callee with a pre-order traversal so that
439    // we see value defs before uses.
440    for callee_block in Dfs::new().pre_order_iter(callee) {
441        let inlined_block = entity_map.inlined_block(callee_block);
442        trace!(
443            "Processing instructions in callee block {callee_block:?} (inlined block {inlined_block:?}"
444        );
445
446        let mut next_callee_inst = callee.layout.first_inst(callee_block);
447        while let Some(callee_inst) = next_callee_inst {
448            trace!(
449                "Processing callee instruction {callee_inst:?}: {}",
450                callee.dfg.display_inst(callee_inst)
451            );
452
453            // Remap the callee instruction's entities and insert it into the
454            // caller's DFG.
455            let mut inst_remapper = InliningInstRemapper {
456                allocs: &allocs,
457                func,
458                callee,
459                entity_map: &entity_map,
460                error: None,
461            };
462            let inlined_inst_data = callee.dfg.insts[callee_inst].map(&mut inst_remapper);
463            if let Some(err) = inst_remapper.error.take() {
464                return Err(err);
465            }
466            let inlined_inst = func.dfg.make_inst(inlined_inst_data);
467            func.layout.append_inst(inlined_inst, inlined_block);
468
469            // Copy over debug tags, translating referenced entities
470            // as appropriate.
471            let debug_tags = callee.debug_tags.get(callee_inst);
472            // If there are tags on the inlined instruction, we always
473            // add tags, and we prepend any tags from the call
474            // instruction; but we don't add tags if only the callsite
475            // had them (this would otherwise mean that every single
476            // instruction in an inlined function body would get
477            // tags).
478            if !debug_tags.is_empty() {
479                let tags = call_debug_tags
480                    .iter()
481                    .cloned()
482                    .chain(debug_tags.iter().map(|tag| match *tag {
483                        DebugTag::User(value) => DebugTag::User(value),
484                        DebugTag::StackSlot(slot) => {
485                            DebugTag::StackSlot(entity_map.inlined_stack_slot(slot))
486                        }
487                    }))
488                    .collect::<SmallVec<[_; 4]>>();
489                func.debug_tags.set(inlined_inst, tags);
490            }
491
492            let opcode = callee.dfg.insts[callee_inst].opcode();
493            if opcode.is_return() {
494                // Instructions that return do not define any values, so we
495                // don't need to worry about that, but we do need to fix them up
496                // so that they return by jumping to our control-flow join
497                // block, rather than returning from the caller.
498                if let Some(return_block) = return_block {
499                    fixup_inst_that_returns(
500                        allocs,
501                        func,
502                        callee,
503                        &entity_map,
504                        call_opcode,
505                        inlined_inst,
506                        callee_inst,
507                        return_block,
508                        call_stack_map.as_ref().map(|es| &**es),
509                    );
510                } else {
511                    // If we are inlining a callee that was invoked via
512                    // `return_call`, we leave inlined return instructions
513                    // as-is: there is no logical caller frame on the stack to
514                    // continue to.
515                    debug_assert_eq!(call_opcode, ir::Opcode::ReturnCall);
516                }
517            } else {
518                // Make the instruction's result values.
519                let ctrl_typevar = callee.dfg.ctrl_typevar(callee_inst);
520                func.dfg.make_inst_results(inlined_inst, ctrl_typevar);
521
522                // Update the value map for this instruction's defs.
523                let callee_results = callee.dfg.inst_results(callee_inst);
524                let inlined_results = func.dfg.inst_results(inlined_inst);
525                debug_assert_eq!(callee_results.len(), inlined_results.len());
526                for (callee_val, inlined_val) in callee_results.iter().zip(inlined_results) {
527                    allocs.set_inlined_value(callee, *callee_val, *inlined_val);
528                }
529
530                if opcode.is_safepoint() {
531                    append_stack_map_entries(
532                        func,
533                        callee,
534                        &entity_map,
535                        call_stack_map.as_deref(),
536                        inlined_inst,
537                        callee_inst,
538                    );
539                }
540
541                if opcode.is_call() {
542                    // When we are inlining a `try_call` call site, we need to merge
543                    // the call site's exception table into the inlined calls'
544                    // exception tables. This can involve rewriting regular `call`s
545                    // into `try_call`s, which requires mutating the CFG because
546                    // `try_call` is a block terminator. However, we can't mutate
547                    // the CFG in the middle of this traversal because we rely on
548                    // the existence of a one-to-one mapping between the callee
549                    // layout and the inlined layout. Instead, we record the set of
550                    // inlined call instructions that will need fixing up, and
551                    // perform that possibly-CFG-mutating exception table merging in
552                    // a follow up pass, when we no longer rely on that one-to-one
553                    // layout mapping.
554                    debug_assert_eq!(
555                        call_opcode == ir::Opcode::TryCall,
556                        call_exception_table.is_some()
557                    );
558                    if call_opcode == ir::Opcode::TryCall {
559                        allocs
560                            .calls_needing_exception_table_fixup
561                            .push(inlined_inst);
562                    }
563                }
564            }
565
566            trace!(
567                "  --> inserted inlined instruction {inlined_inst:?}: {}",
568                func.dfg.display_inst(inlined_inst)
569            );
570
571            next_callee_inst = callee.layout.next_inst(callee_inst);
572        }
573    }
574
575    // We copied *all* callee blocks into the caller's layout, but only copied
576    // the callee instructions in *reachable* callee blocks into the caller's
577    // associated blocks. Therefore, any *unreachable* blocks are empty in the
578    // caller, which is invalid CLIF because all blocks must end in a
579    // terminator, so do a quick pass over the inlined blocks and remove any
580    // empty blocks from the caller's layout.
581    for block in entity_map.iter_inlined_blocks(func) {
582        if func.layout.is_block_inserted(block) && func.layout.first_inst(block).is_none() {
583            log::trace!("removing unreachable inlined block from layout: {block}");
584
585            // If the block being removed is our last-inlined block, then back
586            // it up to the previous block in the layout, which will be the new
587            // last-inlined block after this one's removal.
588            if block == last_inlined_block {
589                last_inlined_block = func.layout.prev_block(last_inlined_block).expect(
590                    "there will always at least be the block that contained the call we are \
591                     inlining",
592                );
593            }
594
595            func.layout.remove_block(block);
596        }
597    }
598
599    // Final step: fixup the exception tables of any inlined calls when we are
600    // inlining a `try_call` site.
601    //
602    // Subtly, this requires rewriting non-catching `call[_indirect]`
603    // instructions into `try_call[_indirect]` instructions so that exceptions
604    // that unwound through the original callee frame and were caught by the
605    // caller's `try_call` do not unwind past this inlined frame. And turning a
606    // `call` into a `try_call` mutates the CFG, breaking our one-to-one mapping
607    // between callee blocks and inlined blocks, so we delay these fixups to
608    // this final step, when we no longer rely on that mapping.
609    debug_assert!(
610        allocs.calls_needing_exception_table_fixup.is_empty() || call_exception_table.is_some()
611    );
612    debug_assert_eq!(
613        call_opcode == ir::Opcode::TryCall,
614        call_exception_table.is_some()
615    );
616    if let Some(call_exception_table) = call_exception_table {
617        fixup_inlined_call_exception_tables(allocs, func, call_exception_table);
618    }
619
620    debug_assert!(
621        func.layout.is_block_inserted(last_inlined_block),
622        "last_inlined_block={last_inlined_block} should be inserted in the layout"
623    );
624    Ok(last_inlined_block)
625}
626
627/// Append stack map entries from the caller and callee to the given inlined
628/// instruction.
629fn append_stack_map_entries(
630    func: &mut ir::Function,
631    callee: &ir::Function,
632    entity_map: &EntityMap,
633    call_stack_map: Option<&[ir::UserStackMapEntry]>,
634    inlined_inst: ir::Inst,
635    callee_inst: ir::Inst,
636) {
637    // Add the caller's stack map to this call. These entries
638    // already refer to caller entities and do not need further
639    // translation.
640    func.dfg.append_user_stack_map_entries(
641        inlined_inst,
642        call_stack_map
643            .iter()
644            .flat_map(|entries| entries.iter().cloned()),
645    );
646
647    // Append the callee's stack map to this call. These entries
648    // refer to callee entities and therefore do require
649    // translation into the caller's index space.
650    func.dfg.append_user_stack_map_entries(
651        inlined_inst,
652        callee
653            .dfg
654            .user_stack_map_entries(callee_inst)
655            .iter()
656            .flat_map(|entries| entries.iter())
657            .map(|entry| ir::UserStackMapEntry {
658                ty: entry.ty,
659                slot: entity_map.inlined_stack_slot(entry.slot),
660                offset: entry.offset,
661            }),
662    );
663}
664
665/// Create or update the exception tables for any inlined call instructions:
666/// when inlining at a `try_call` site, we must forward our exceptional edges
667/// into each inlined call instruction.
668fn fixup_inlined_call_exception_tables(
669    allocs: &mut InliningAllocs,
670    func: &mut ir::Function,
671    call_exception_table: ir::ExceptionTable,
672) {
673    // Split a block at a `call[_indirect]` instruction, detach the
674    // instruction's results, and alias them to the new block's parameters.
675    let split_block_for_new_try_call = |func: &mut ir::Function, inst: ir::Inst| -> ir::Block {
676        debug_assert!(func.dfg.insts[inst].opcode().is_call());
677        debug_assert!(!func.dfg.insts[inst].opcode().is_terminator());
678
679        // Split the block.
680        let next_inst = func
681            .layout
682            .next_inst(inst)
683            .expect("inst is not a terminator, should have a successor");
684        let new_block = func.dfg.blocks.add();
685        func.layout.split_block(new_block, next_inst);
686
687        // `try_call[_indirect]` instructions do not define values themselves;
688        // the normal-return block has parameters for the results. So remove
689        // this instruction's results, create an associated block parameter for
690        // each of them, and alias them to the new block parameter.
691        let old_results = SmallValueVec::from_iter(func.dfg.inst_results(inst).iter().copied());
692        func.dfg.detach_inst_results(inst);
693        for old_result in old_results {
694            let ty = func.dfg.value_type(old_result);
695            let new_block_param = func.dfg.append_block_param(new_block, ty);
696            func.dfg.change_to_alias(old_result, new_block_param);
697        }
698
699        new_block
700    };
701
702    // Clone the caller's exception table, updating it for use in the current
703    // `call[_indirect]` instruction as it becomes a `try_call[_indirect]`.
704    let clone_exception_table_for_this_call = |func: &mut ir::Function,
705                                               signature: ir::SigRef,
706                                               new_block: ir::Block|
707     -> ir::ExceptionTable {
708        let mut exception = func.stencil.dfg.exception_tables[call_exception_table]
709            .deep_clone(&mut func.stencil.dfg.value_lists);
710
711        *exception.signature_mut() = signature;
712
713        let returns_len = func.dfg.signatures[signature].returns.len();
714        let returns_len = u32::try_from(returns_len).unwrap();
715
716        *exception.normal_return_mut() = ir::BlockCall::new(
717            new_block,
718            (0..returns_len).map(|i| ir::BlockArg::TryCallRet(i)),
719            &mut func.dfg.value_lists,
720        );
721
722        func.dfg.exception_tables.push(exception)
723    };
724
725    for inst in allocs.calls_needing_exception_table_fixup.drain(..) {
726        debug_assert!(func.dfg.insts[inst].opcode().is_call());
727        debug_assert!(!func.dfg.insts[inst].opcode().is_return());
728        match func.dfg.insts[inst] {
729            //     current_block:
730            //         preds...
731            //         rets... = call f(args...)
732            //         succs...
733            //
734            // becomes
735            //
736            //     current_block:
737            //         preds...
738            //         try_call f(args...), new_block(rets...), [call_exception_table...]
739            //     new_block(rets...):
740            //         succs...
741            ir::InstructionData::Call {
742                opcode: ir::Opcode::Call,
743                args,
744                func_ref,
745            } => {
746                let new_block = split_block_for_new_try_call(func, inst);
747                let signature = func.dfg.ext_funcs[func_ref].signature;
748                let exception = clone_exception_table_for_this_call(func, signature, new_block);
749                func.dfg.insts[inst] = ir::InstructionData::TryCall {
750                    opcode: ir::Opcode::TryCall,
751                    args,
752                    func_ref,
753                    exception,
754                };
755            }
756
757            //     current_block:
758            //         preds...
759            //         rets... = call_indirect sig, val(args...)
760            //         succs...
761            //
762            // becomes
763            //
764            //     current_block:
765            //         preds...
766            //         try_call_indirect sig, val(args...), new_block(rets...), [call_exception_table...]
767            //     new_block(rets...):
768            //         succs...
769            ir::InstructionData::CallIndirect {
770                opcode: ir::Opcode::CallIndirect,
771                args,
772                sig_ref,
773            } => {
774                let new_block = split_block_for_new_try_call(func, inst);
775                let exception = clone_exception_table_for_this_call(func, sig_ref, new_block);
776                func.dfg.insts[inst] = ir::InstructionData::TryCallIndirect {
777                    opcode: ir::Opcode::TryCallIndirect,
778                    args,
779                    exception,
780                };
781            }
782
783            // For `try_call[_indirect]` instructions, we just need to merge the
784            // exception tables.
785            ir::InstructionData::TryCall {
786                opcode: ir::Opcode::TryCall,
787                exception,
788                ..
789            }
790            | ir::InstructionData::TryCallIndirect {
791                opcode: ir::Opcode::TryCallIndirect,
792                exception,
793                ..
794            } => {
795                // Construct a new exception table that consists of
796                // the inlined instruction's exception table match
797                // sequence, with the inlining site's exception table
798                // appended. This will ensure that the first-match
799                // semantics emulates the original behavior of
800                // matching in the inner frame first.
801                let sig = func.dfg.exception_tables[exception].signature();
802                let normal_return = *func.dfg.exception_tables[exception].normal_return();
803                let exception_data = ExceptionTableData::new(
804                    sig,
805                    normal_return,
806                    func.dfg.exception_tables[exception]
807                        .items()
808                        .chain(func.dfg.exception_tables[call_exception_table].items()),
809                )
810                .deep_clone(&mut func.dfg.value_lists);
811
812                func.dfg.exception_tables[exception] = exception_data;
813            }
814
815            otherwise => unreachable!("unknown non-return call instruction: {otherwise:?}"),
816        }
817    }
818}
819
820/// After having created an inlined version of a callee instruction that returns
821/// in the caller, we need to fix it up so that it doesn't actually return
822/// (since we are already in the caller's frame) and instead just jumps to the
823/// control-flow join point.
824fn fixup_inst_that_returns(
825    allocs: &mut InliningAllocs,
826    func: &mut ir::Function,
827    callee: &ir::Function,
828    entity_map: &EntityMap,
829    call_opcode: ir::Opcode,
830    inlined_inst: ir::Inst,
831    callee_inst: ir::Inst,
832    return_block: ir::Block,
833    call_stack_map: Option<&[ir::UserStackMapEntry]>,
834) {
835    debug_assert!(func.dfg.insts[inlined_inst].opcode().is_return());
836    match func.dfg.insts[inlined_inst] {
837        //     return rets...
838        //
839        // becomes
840        //
841        //     jump return_block(rets...)
842        ir::InstructionData::MultiAry {
843            opcode: ir::Opcode::Return,
844            args,
845        } => {
846            let rets = SmallBlockArgVec::from_iter(
847                args.as_slice(&func.dfg.value_lists)
848                    .iter()
849                    .copied()
850                    .map(|v| v.into()),
851            );
852            func.replace(inlined_inst).jump(return_block, &rets);
853        }
854
855        //     return_call f(args...)
856        //
857        // becomes
858        //
859        //     rets... = call f(args...)
860        //     jump return_block(rets...)
861        ir::InstructionData::Call {
862            opcode: ir::Opcode::ReturnCall,
863            args,
864            func_ref,
865        } => {
866            func.dfg.insts[inlined_inst] = ir::InstructionData::Call {
867                opcode: ir::Opcode::Call,
868                args,
869                func_ref,
870            };
871            func.dfg.make_inst_results(inlined_inst, ir::types::INVALID);
872
873            append_stack_map_entries(
874                func,
875                callee,
876                &entity_map,
877                call_stack_map,
878                inlined_inst,
879                callee_inst,
880            );
881
882            let rets = SmallBlockArgVec::from_iter(
883                func.dfg
884                    .inst_results(inlined_inst)
885                    .iter()
886                    .copied()
887                    .map(|v| v.into()),
888            );
889            let mut cursor = FuncCursor::new(func);
890            cursor.goto_after_inst(inlined_inst);
891            cursor.ins().jump(return_block, &rets);
892
893            if call_opcode == ir::Opcode::TryCall {
894                allocs
895                    .calls_needing_exception_table_fixup
896                    .push(inlined_inst);
897            }
898        }
899
900        //     return_call_indirect val(args...)
901        //
902        // becomes
903        //
904        //     rets... = call_indirect val(args...)
905        //     jump return_block(rets...)
906        ir::InstructionData::CallIndirect {
907            opcode: ir::Opcode::ReturnCallIndirect,
908            args,
909            sig_ref,
910        } => {
911            func.dfg.insts[inlined_inst] = ir::InstructionData::CallIndirect {
912                opcode: ir::Opcode::CallIndirect,
913                args,
914                sig_ref,
915            };
916            func.dfg.make_inst_results(inlined_inst, ir::types::INVALID);
917
918            append_stack_map_entries(
919                func,
920                callee,
921                &entity_map,
922                call_stack_map,
923                inlined_inst,
924                callee_inst,
925            );
926
927            let rets = SmallBlockArgVec::from_iter(
928                func.dfg
929                    .inst_results(inlined_inst)
930                    .iter()
931                    .copied()
932                    .map(|v| v.into()),
933            );
934            let mut cursor = FuncCursor::new(func);
935            cursor.goto_after_inst(inlined_inst);
936            cursor.ins().jump(return_block, &rets);
937
938            if call_opcode == ir::Opcode::TryCall {
939                allocs
940                    .calls_needing_exception_table_fixup
941                    .push(inlined_inst);
942            }
943        }
944
945        inst_data => unreachable!(
946            "should have handled all `is_return() == true` instructions above; \
947             got {inst_data:?}"
948        ),
949    }
950}
951
952/// An `InstructionMapper` implementation that remaps a callee instruction's
953/// entity references to their new indices in the caller function.
954struct InliningInstRemapper<'a> {
955    allocs: &'a InliningAllocs,
956    func: &'a mut ir::Function,
957    callee: &'a ir::Function,
958    entity_map: &'a EntityMap,
959    error: Option<crate::result::CodegenError>,
960}
961
962impl<'a> ir::instructions::InstructionMapper for InliningInstRemapper<'a> {
963    fn map_value(&mut self, value: ir::Value) -> ir::Value {
964        self.allocs.get_inlined_value(self.callee, value).expect(
965            "defs come before uses; we should have already inlined all values \
966             used by an instruction",
967        )
968    }
969
970    fn map_value_list(&mut self, value_list: ir::ValueList) -> ir::ValueList {
971        let mut inlined_list = ir::ValueList::new();
972        for callee_val in value_list.as_slice(&self.callee.dfg.value_lists) {
973            let inlined_val = self.map_value(*callee_val);
974            inlined_list.push(inlined_val, &mut self.func.dfg.value_lists);
975        }
976        inlined_list
977    }
978
979    fn map_global_value(&mut self, global_value: ir::GlobalValue) -> ir::GlobalValue {
980        self.entity_map.inlined_global_value(global_value)
981    }
982
983    fn map_jump_table(&mut self, jump_table: ir::JumpTable) -> ir::JumpTable {
984        let inlined_default =
985            self.map_block_call(self.callee.dfg.jump_tables[jump_table].default_block());
986        let inlined_table = self.callee.dfg.jump_tables[jump_table]
987            .as_slice()
988            .iter()
989            .map(|callee_block_call| self.map_block_call(*callee_block_call))
990            .collect::<SmallBlockCallVec>();
991        self.func
992            .dfg
993            .jump_tables
994            .push(ir::JumpTableData::new(inlined_default, &inlined_table))
995    }
996
997    fn map_exception_table(&mut self, exception_table: ir::ExceptionTable) -> ir::ExceptionTable {
998        let exception_table = &self.callee.dfg.exception_tables[exception_table];
999        let inlined_sig_ref = self.map_sig_ref(exception_table.signature());
1000        let inlined_normal_return = self.map_block_call(*exception_table.normal_return());
1001        let inlined_table = exception_table
1002            .items()
1003            .map(|item| match item {
1004                ExceptionTableItem::Tag(tag, block_call) => {
1005                    ExceptionTableItem::Tag(tag, self.map_block_call(block_call))
1006                }
1007                ExceptionTableItem::Default(block_call) => {
1008                    ExceptionTableItem::Default(self.map_block_call(block_call))
1009                }
1010                ExceptionTableItem::Context(value) => {
1011                    ExceptionTableItem::Context(self.map_value(value))
1012                }
1013            })
1014            .collect::<SmallVec<[_; 8]>>();
1015        self.func
1016            .dfg
1017            .exception_tables
1018            .push(ir::ExceptionTableData::new(
1019                inlined_sig_ref,
1020                inlined_normal_return,
1021                inlined_table,
1022            ))
1023    }
1024
1025    fn map_block_call(&mut self, block_call: ir::BlockCall) -> ir::BlockCall {
1026        let callee_block = block_call.block(&self.callee.dfg.value_lists);
1027        let inlined_block = self.entity_map.inlined_block(callee_block);
1028        let args = block_call
1029            .args(&self.callee.dfg.value_lists)
1030            .map(|arg| match arg {
1031                ir::BlockArg::Value(value) => self.map_value(value).into(),
1032                ir::BlockArg::TryCallRet(_) | ir::BlockArg::TryCallExn(_) => arg,
1033            })
1034            .collect::<SmallBlockArgVec>();
1035        ir::BlockCall::new(inlined_block, args, &mut self.func.dfg.value_lists)
1036    }
1037
1038    fn map_block(&mut self, block: ir::Block) -> ir::Block {
1039        self.entity_map.inlined_block(block)
1040    }
1041
1042    fn map_func_ref(&mut self, func_ref: ir::FuncRef) -> ir::FuncRef {
1043        self.entity_map.inlined_func_ref(func_ref)
1044    }
1045
1046    fn map_sig_ref(&mut self, sig_ref: ir::SigRef) -> ir::SigRef {
1047        self.entity_map.inlined_sig_ref(sig_ref)
1048    }
1049
1050    fn map_stack_slot(&mut self, stack_slot: ir::StackSlot) -> ir::StackSlot {
1051        self.entity_map.inlined_stack_slot(stack_slot)
1052    }
1053
1054    fn map_dynamic_stack_slot(
1055        &mut self,
1056        dynamic_stack_slot: ir::DynamicStackSlot,
1057    ) -> ir::DynamicStackSlot {
1058        self.entity_map
1059            .inlined_dynamic_stack_slot(dynamic_stack_slot)
1060    }
1061
1062    fn map_constant(&mut self, constant: ir::Constant) -> ir::Constant {
1063        self.allocs
1064            .constants
1065            .get(constant)
1066            .and_then(|o| o.expand())
1067            .expect("should have inlined all callee constants")
1068    }
1069
1070    fn map_immediate(&mut self, immediate: ir::Immediate) -> ir::Immediate {
1071        self.entity_map.inlined_immediate(immediate)
1072    }
1073    fn map_mem_flags(&mut self, flags: ir::MemFlags) -> ir::MemFlags {
1074        let mut flags_data = self.callee.dfg.mem_flags[flags];
1075        // Remap the alias region entity from callee to caller.
1076        if let Some(callee_region) = flags_data.alias_region() {
1077            let region_data = self.callee.dfg.alias_regions[callee_region].clone();
1078            let caller_region = self.func.dfg.alias_regions.insert(region_data);
1079            flags_data.set_alias_region(Some(caller_region));
1080        }
1081        match self.func.dfg.mem_flags.insert(flags_data) {
1082            Ok(flags) => flags,
1083            Err(_) => {
1084                self.error = Some(crate::result::CodegenError::ImplLimitExceeded);
1085                self.func
1086                    .dfg
1087                    .mem_flags
1088                    .insert(ir::MemFlagsData::trusted())
1089                    .unwrap()
1090            }
1091        }
1092    }
1093}
1094
1095/// Inline the callee's layout into the caller's layout.
1096///
1097/// Returns the last inlined block in the layout.
1098fn inline_block_layout(
1099    func: &mut ir::Function,
1100    call_block: ir::Block,
1101    callee: &ir::Function,
1102    entity_map: &EntityMap,
1103) -> ir::Block {
1104    debug_assert!(func.layout.is_block_inserted(call_block));
1105
1106    // Iterate over callee blocks in layout order, inserting their associated
1107    // inlined block into the caller's layout.
1108    let mut prev_inlined_block = call_block;
1109    let mut next_callee_block = callee.layout.entry_block();
1110    while let Some(callee_block) = next_callee_block {
1111        debug_assert!(func.layout.is_block_inserted(prev_inlined_block));
1112
1113        let inlined_block = entity_map.inlined_block(callee_block);
1114        func.layout
1115            .insert_block_after(inlined_block, prev_inlined_block);
1116
1117        prev_inlined_block = inlined_block;
1118        next_callee_block = callee.layout.next_block(callee_block);
1119    }
1120
1121    debug_assert!(func.layout.is_block_inserted(prev_inlined_block));
1122    prev_inlined_block
1123}
1124
1125/// Split the call instruction's block just after the call instruction to create
1126/// the point where control-flow joins after the inlined callee "returns".
1127///
1128/// Note that tail calls do not return to the caller and therefore do not have a
1129/// control-flow join point.
1130fn split_off_return_block(
1131    func: &mut ir::Function,
1132    call_inst: ir::Inst,
1133    opcode: ir::Opcode,
1134    callee: &ir::Function,
1135) -> Option<ir::Block> {
1136    // When the `call_inst` is not a block terminator, we need to split the
1137    // block.
1138    let return_block = func.layout.next_inst(call_inst).map(|next_inst| {
1139        let return_block = func.dfg.blocks.add();
1140        func.layout.split_block(return_block, next_inst);
1141
1142        // Add block parameters for each return value and alias the call
1143        // instruction's results to them.
1144        let old_results =
1145            SmallValueVec::from_iter(func.dfg.inst_results(call_inst).iter().copied());
1146        debug_assert_eq!(old_results.len(), callee.signature.returns.len());
1147        func.dfg.detach_inst_results(call_inst);
1148        for (abi, old_val) in callee.signature.returns.iter().zip(old_results) {
1149            debug_assert_eq!(abi.value_type, func.dfg.value_type(old_val));
1150            let ret_param = func.dfg.append_block_param(return_block, abi.value_type);
1151            func.dfg.change_to_alias(old_val, ret_param);
1152        }
1153
1154        return_block
1155    });
1156
1157    // When the `call_inst` is a block terminator, then it is either a
1158    // `return_call` or a `try_call`:
1159    //
1160    // * For `return_call`s, we don't have a control-flow join point, because
1161    //   the caller permanently transfers control to the callee.
1162    //
1163    // * For `try_call`s, we probably already have a block for the control-flow
1164    //   join point, but it isn't guaranteed: the `try_call` might ignore the
1165    //   call's returns and not forward them to the normal-return block or it
1166    //   might also pass additional arguments. We can only reuse the existing
1167    //   normal-return block when the `try_call` forwards exactly our callee's
1168    //   returns to that block (and therefore that block's parameter types also
1169    //   exactly match the callee's return types). Otherwise, we must create a new
1170    //   return block that forwards to the existing normal-return
1171    //   block. (Elsewhere, at the end of inlining, we will also update any inlined
1172    //   calls to forward any raised exceptions to the caller's exception table,
1173    //   as necessary.)
1174    //
1175    //   Finally, note that reusing the normal-return's target block is just an
1176    //   optimization to emit a simpler CFG when we can, and is not
1177    //   fundamentally required for correctness. We could always insert a
1178    //   temporary block as our control-flow join point that then forwards to
1179    //   the normal-return's target block. However, at the time of writing,
1180    //   Cranelift doesn't currently do any jump-threading or branch
1181    //   simplification in the mid-end, and removing unnecessary blocks in this
1182    //   way can help some subsequent mid-end optimizations. If, in the future,
1183    //   we gain support for jump-threading optimizations in the mid-end, we can
1184    //   come back and simplify the below code a bit to always generate the
1185    //   temporary block, and then rely on the subsequent optimizations to clean
1186    //   everything up.
1187    debug_assert_eq!(
1188        return_block.is_none(),
1189        opcode == ir::Opcode::ReturnCall || opcode == ir::Opcode::TryCall,
1190    );
1191    return_block.or_else(|| match func.dfg.insts[call_inst] {
1192        ir::InstructionData::TryCall {
1193            opcode: ir::Opcode::TryCall,
1194            args: _,
1195            func_ref: _,
1196            exception,
1197        } => {
1198            let normal_return = func.dfg.exception_tables[exception].normal_return();
1199            let normal_return_block = normal_return.block(&func.dfg.value_lists);
1200
1201            // Check to see if we can reuse the existing normal-return block.
1202            {
1203                let normal_return_args = normal_return.args(&func.dfg.value_lists);
1204                if normal_return_args.len() == callee.signature.returns.len()
1205                    && normal_return_args.enumerate().all(|(i, arg)| {
1206                        let i = u32::try_from(i).unwrap();
1207                        arg == ir::BlockArg::TryCallRet(i)
1208                    })
1209                {
1210                    return Some(normal_return_block);
1211                }
1212            }
1213
1214            // Okay, we cannot reuse the normal-return block. Create a new block
1215            // that has the expected block parameter types and have it jump to
1216            // the normal-return block.
1217            let return_block = func.dfg.blocks.add();
1218            func.layout.insert_block(return_block, normal_return_block);
1219
1220            let return_block_params = callee
1221                .signature
1222                .returns
1223                .iter()
1224                .map(|abi| func.dfg.append_block_param(return_block, abi.value_type))
1225                .collect::<SmallValueVec>();
1226
1227            let normal_return_args = func.dfg.exception_tables[exception]
1228                .normal_return()
1229                .args(&func.dfg.value_lists)
1230                .collect::<SmallBlockArgVec>();
1231            let jump_args = normal_return_args
1232                .into_iter()
1233                .map(|arg| match arg {
1234                    ir::BlockArg::Value(value) => ir::BlockArg::Value(value),
1235                    ir::BlockArg::TryCallRet(i) => {
1236                        let i = usize::try_from(i).unwrap();
1237                        ir::BlockArg::Value(return_block_params[i])
1238                    }
1239                    ir::BlockArg::TryCallExn(_) => {
1240                        unreachable!("normal-return edges cannot use exceptional results")
1241                    }
1242                })
1243                .collect::<SmallBlockArgVec>();
1244
1245            let mut cursor = FuncCursor::new(func);
1246            cursor.goto_first_insertion_point(return_block);
1247            cursor.ins().jump(normal_return_block, &jump_args);
1248
1249            Some(return_block)
1250        }
1251        _ => None,
1252    })
1253}
1254
1255/// Replace the caller's call instruction with a jump to the caller's inlined
1256/// copy of the callee's entry block.
1257///
1258/// Also associates the callee's parameters with the caller's arguments in our
1259/// value map.
1260///
1261/// Returns the caller's stack map entries, if any.
1262fn replace_call_with_jump(
1263    allocs: &mut InliningAllocs,
1264    func: &mut ir::Function,
1265    call_inst: ir::Inst,
1266    callee: &ir::Function,
1267    entity_map: &EntityMap,
1268) -> Option<ir::UserStackMapEntryVec> {
1269    trace!("Replacing `call` with `jump`");
1270    trace!(
1271        "  --> call instruction: {call_inst:?}: {}",
1272        func.dfg.display_inst(call_inst)
1273    );
1274
1275    let callee_entry_block = callee
1276        .layout
1277        .entry_block()
1278        .expect("callee function should have an entry block");
1279    let callee_param_values = callee.dfg.block_params(callee_entry_block);
1280    let caller_arg_values = SmallValueVec::from_iter(func.dfg.inst_args(call_inst).iter().copied());
1281    debug_assert_eq!(callee_param_values.len(), caller_arg_values.len());
1282    debug_assert_eq!(callee_param_values.len(), callee.signature.params.len());
1283    for (abi, (callee_param_value, caller_arg_value)) in callee
1284        .signature
1285        .params
1286        .iter()
1287        .zip(callee_param_values.into_iter().zip(caller_arg_values))
1288    {
1289        debug_assert_eq!(abi.value_type, callee.dfg.value_type(*callee_param_value));
1290        debug_assert_eq!(abi.value_type, func.dfg.value_type(caller_arg_value));
1291        allocs.set_inlined_value(callee, *callee_param_value, caller_arg_value);
1292    }
1293
1294    // Replace the caller's call instruction with a jump to the caller's inlined
1295    // copy of the callee's entry block.
1296    //
1297    // Note that the call block dominates the inlined entry block (and also all
1298    // other inlined blocks) so we can reference the arguments directly, and do
1299    // not need to add block parameters to the inlined entry block.
1300    let inlined_entry_block = entity_map.inlined_block(callee_entry_block);
1301    func.replace(call_inst).jump(inlined_entry_block, &[]);
1302    trace!(
1303        "  --> replaced with jump instruction: {call_inst:?}: {}",
1304        func.dfg.display_inst(call_inst)
1305    );
1306
1307    let stack_map_entries = func.dfg.take_user_stack_map_entries(call_inst);
1308    stack_map_entries
1309}
1310
1311/// Keeps track of mapping callee entities to their associated inlined caller
1312/// entities.
1313#[derive(Default)]
1314struct EntityMap {
1315    // Rather than doing an implicit, demand-based, DCE'ing translation of
1316    // entities, which would require maps from each callee entity to its
1317    // associated caller entity, we copy all entities into the caller, remember
1318    // each entity's initial offset, and then mapping from the callee to the
1319    // inlined caller entity is just adding that initial offset to the callee's
1320    // index. This should be both faster and simpler than the alternative. Most
1321    // of these sets are relatively small, and they rarely have too much dead
1322    // code in practice, so this is a good trade off.
1323    //
1324    // Note that there are a few kinds of entities that are excluded from the
1325    // `EntityMap`, and for which we do actually take the demand-based approach:
1326    // values and value lists being the notable ones.
1327    block_offset: Option<u32>,
1328    global_value_offset: Option<u32>,
1329    sig_ref_offset: Option<u32>,
1330    func_ref_offset: Option<u32>,
1331    stack_slot_offset: Option<u32>,
1332    dynamic_type_offset: Option<u32>,
1333    dynamic_stack_slot_offset: Option<u32>,
1334    immediate_offset: Option<u32>,
1335}
1336
1337impl EntityMap {
1338    fn inlined_block(&self, callee_block: ir::Block) -> ir::Block {
1339        let offset = self
1340            .block_offset
1341            .expect("must create inlined `ir::Block`s before calling `EntityMap::inlined_block`");
1342        ir::Block::from_u32(offset + callee_block.as_u32())
1343    }
1344
1345    fn iter_inlined_blocks(&self, func: &ir::Function) -> impl Iterator<Item = ir::Block> + use<> {
1346        let start = self.block_offset.expect(
1347            "must create inlined `ir::Block`s before calling `EntityMap::iter_inlined_blocks`",
1348        );
1349
1350        let end = func.dfg.blocks.len();
1351        let end = u32::try_from(end).unwrap();
1352
1353        (start..end).map(|i| ir::Block::from_u32(i))
1354    }
1355
1356    fn inlined_global_value(&self, callee_global_value: ir::GlobalValue) -> ir::GlobalValue {
1357        let offset = self
1358            .global_value_offset
1359            .expect("must create inlined `ir::GlobalValue`s before calling `EntityMap::inlined_global_value`");
1360        ir::GlobalValue::from_u32(offset + callee_global_value.as_u32())
1361    }
1362
1363    fn inlined_sig_ref(&self, callee_sig_ref: ir::SigRef) -> ir::SigRef {
1364        let offset = self.sig_ref_offset.expect(
1365            "must create inlined `ir::SigRef`s before calling `EntityMap::inlined_sig_ref`",
1366        );
1367        ir::SigRef::from_u32(offset + callee_sig_ref.as_u32())
1368    }
1369
1370    fn inlined_func_ref(&self, callee_func_ref: ir::FuncRef) -> ir::FuncRef {
1371        let offset = self.func_ref_offset.expect(
1372            "must create inlined `ir::FuncRef`s before calling `EntityMap::inlined_func_ref`",
1373        );
1374        ir::FuncRef::from_u32(offset + callee_func_ref.as_u32())
1375    }
1376
1377    fn inlined_stack_slot(&self, callee_stack_slot: ir::StackSlot) -> ir::StackSlot {
1378        let offset = self.stack_slot_offset.expect(
1379            "must create inlined `ir::StackSlot`s before calling `EntityMap::inlined_stack_slot`",
1380        );
1381        ir::StackSlot::from_u32(offset + callee_stack_slot.as_u32())
1382    }
1383
1384    fn inlined_dynamic_type(&self, callee_dynamic_type: ir::DynamicType) -> ir::DynamicType {
1385        let offset = self.dynamic_type_offset.expect(
1386            "must create inlined `ir::DynamicType`s before calling `EntityMap::inlined_dynamic_type`",
1387        );
1388        ir::DynamicType::from_u32(offset + callee_dynamic_type.as_u32())
1389    }
1390
1391    fn inlined_dynamic_stack_slot(
1392        &self,
1393        callee_dynamic_stack_slot: ir::DynamicStackSlot,
1394    ) -> ir::DynamicStackSlot {
1395        let offset = self.dynamic_stack_slot_offset.expect(
1396            "must create inlined `ir::DynamicStackSlot`s before calling `EntityMap::inlined_dynamic_stack_slot`",
1397        );
1398        ir::DynamicStackSlot::from_u32(offset + callee_dynamic_stack_slot.as_u32())
1399    }
1400
1401    fn inlined_immediate(&self, callee_immediate: ir::Immediate) -> ir::Immediate {
1402        let offset = self.immediate_offset.expect(
1403            "must create inlined `ir::Immediate`s before calling `EntityMap::inlined_immediate`",
1404        );
1405        ir::Immediate::from_u32(offset + callee_immediate.as_u32())
1406    }
1407}
1408
1409/// Translate all of the callee's various entities into the caller, producing an
1410/// `EntityMap` that can be used to translate callee entity references into
1411/// inlined caller entity references.
1412fn create_entities(
1413    allocs: &mut InliningAllocs,
1414    func: &mut ir::Function,
1415    callee: &ir::Function,
1416) -> CodegenResult<EntityMap> {
1417    let mut entity_map = EntityMap::default();
1418
1419    entity_map.block_offset = Some(create_blocks(allocs, func, callee));
1420    create_user_external_name_refs(allocs, func, callee);
1421    entity_map.global_value_offset = Some(create_global_values(allocs, func, callee)?);
1422    entity_map.sig_ref_offset = Some(create_sig_refs(func, callee));
1423    entity_map.func_ref_offset = Some(create_func_refs(allocs, func, callee, &entity_map));
1424    entity_map.stack_slot_offset = Some(create_stack_slots(func, callee));
1425    entity_map.dynamic_type_offset = Some(create_dynamic_types(func, callee, &entity_map));
1426    entity_map.dynamic_stack_slot_offset =
1427        Some(create_dynamic_stack_slots(func, callee, &entity_map));
1428    entity_map.immediate_offset = Some(create_immediates(func, callee));
1429
1430    // `ir::ConstantData` is deduplicated, so we cannot use our offset scheme
1431    // for `ir::Constant`s. Nonetheless, we still insert them into the caller
1432    // now, at the same time as the rest of our entities.
1433    create_constants(allocs, func, callee);
1434
1435    Ok(entity_map)
1436}
1437
1438/// Create inlined blocks in the caller for every block in the callee.
1439fn create_blocks(
1440    allocs: &mut InliningAllocs,
1441    func: &mut ir::Function,
1442    callee: &ir::Function,
1443) -> u32 {
1444    let offset = func.dfg.blocks.len();
1445    let offset = u32::try_from(offset).unwrap();
1446
1447    func.dfg.blocks.reserve(callee.dfg.blocks.len());
1448    for callee_block in callee.dfg.blocks.iter() {
1449        let caller_block = func.dfg.blocks.add();
1450        trace!("Callee {callee_block:?} = inlined {caller_block:?}");
1451
1452        if callee.layout.is_cold(callee_block) {
1453            func.layout.set_cold(caller_block);
1454        }
1455
1456        // Note: the entry block does not need parameters because the only
1457        // predecessor is the call block and we associate the callee's
1458        // parameters with the caller's arguments directly.
1459        if callee.layout.entry_block() != Some(callee_block) {
1460            for callee_param in callee.dfg.blocks[callee_block].params(&callee.dfg.value_lists) {
1461                let ty = callee.dfg.value_type(*callee_param);
1462                let caller_param = func.dfg.append_block_param(caller_block, ty);
1463
1464                allocs.set_inlined_value(callee, *callee_param, caller_param);
1465            }
1466        }
1467    }
1468
1469    offset
1470}
1471
1472/// Copy and translate global values from the callee into the caller.
1473fn create_global_values(
1474    allocs: &InliningAllocs,
1475    func: &mut ir::Function,
1476    callee: &ir::Function,
1477) -> CodegenResult<u32> {
1478    let gv_offset = func.global_values.len();
1479    let gv_offset = u32::try_from(gv_offset).unwrap();
1480
1481    func.global_values.reserve(callee.global_values.len());
1482    for gv in callee.global_values.values() {
1483        // Re-insert callee mem flags into the caller's DFG before constructing
1484        // the global value data, to avoid borrow conflicts.
1485        let remapped_flags = match gv {
1486            ir::GlobalValueData::Load { flags, .. } => {
1487                let mut flags_data = callee.dfg.mem_flags[*flags];
1488                // Remap alias region entity from callee to caller.
1489                if let Some(callee_region) = flags_data.alias_region() {
1490                    let region_data = callee.dfg.alias_regions[callee_region].clone();
1491                    let caller_region = func.dfg.alias_regions.insert(region_data);
1492                    flags_data.set_alias_region(Some(caller_region));
1493                }
1494                Some(
1495                    func.dfg
1496                        .mem_flags
1497                        .insert(flags_data)
1498                        .map_err(|_| crate::result::CodegenError::ImplLimitExceeded)?,
1499                )
1500            }
1501            _ => None,
1502        };
1503        func.global_values.push(match gv {
1504            // These kinds of global values reference other global values, so we
1505            // need to fixup that reference.
1506            ir::GlobalValueData::Load {
1507                base,
1508                offset,
1509                global_type,
1510                flags: _,
1511            } => ir::GlobalValueData::Load {
1512                base: ir::GlobalValue::from_u32(base.as_u32() + gv_offset),
1513                offset: *offset,
1514                global_type: *global_type,
1515                flags: remapped_flags.unwrap(),
1516            },
1517            ir::GlobalValueData::IAddImm {
1518                base,
1519                offset,
1520                global_type,
1521            } => ir::GlobalValueData::IAddImm {
1522                base: ir::GlobalValue::from_u32(base.as_u32() + gv_offset),
1523                offset: *offset,
1524                global_type: *global_type,
1525            },
1526
1527            // Symbols may reference a user external name, which must be
1528            // translated into the caller's user external name table.
1529            ir::GlobalValueData::Symbol {
1530                name,
1531                offset,
1532                colocated,
1533                tls,
1534            } => ir::GlobalValueData::Symbol {
1535                name: allocs.inlined_external_name(name),
1536                offset: *offset,
1537                colocated: *colocated,
1538                tls: *tls,
1539            },
1540
1541            // These kinds of global values do not reference other entities,
1542            // so we can just clone them.
1543            ir::GlobalValueData::VMContext | ir::GlobalValueData::DynScaleTargetConst { .. } => {
1544                gv.clone()
1545            }
1546        });
1547    }
1548
1549    Ok(gv_offset)
1550}
1551
1552/// Copy `ir::SigRef`s from the callee into the caller.
1553fn create_sig_refs(func: &mut ir::Function, callee: &ir::Function) -> u32 {
1554    let offset = func.dfg.signatures.len();
1555    let offset = u32::try_from(offset).unwrap();
1556
1557    func.dfg.signatures.reserve(callee.dfg.signatures.len());
1558    for sig in callee.dfg.signatures.values() {
1559        func.dfg.signatures.push(sig.clone());
1560    }
1561
1562    offset
1563}
1564
1565fn create_user_external_name_refs(
1566    allocs: &mut InliningAllocs,
1567    func: &mut ir::Function,
1568    callee: &ir::Function,
1569) {
1570    for (callee_named_func_ref, name) in callee.params.user_named_funcs().iter() {
1571        let caller_named_func_ref = func.declare_imported_user_function(name.clone());
1572        allocs.user_external_name_refs[callee_named_func_ref] = Some(caller_named_func_ref).into();
1573    }
1574}
1575
1576/// Translate `ir::FuncRef`s from the callee into the caller.
1577fn create_func_refs(
1578    allocs: &InliningAllocs,
1579    func: &mut ir::Function,
1580    callee: &ir::Function,
1581    entity_map: &EntityMap,
1582) -> u32 {
1583    let offset = func.dfg.ext_funcs.len();
1584    let offset = u32::try_from(offset).unwrap();
1585
1586    func.dfg.ext_funcs.reserve(callee.dfg.ext_funcs.len());
1587    for ir::ExtFuncData {
1588        name,
1589        signature,
1590        colocated,
1591        patchable,
1592    } in callee.dfg.ext_funcs.values()
1593    {
1594        func.dfg.ext_funcs.push(ir::ExtFuncData {
1595            name: allocs.inlined_external_name(name),
1596            signature: entity_map.inlined_sig_ref(*signature),
1597            colocated: *colocated,
1598            patchable: *patchable,
1599        });
1600    }
1601
1602    offset
1603}
1604
1605/// Copy stack slots from the callee into the caller.
1606fn create_stack_slots(func: &mut ir::Function, callee: &ir::Function) -> u32 {
1607    let offset = func.sized_stack_slots.len();
1608    let offset = u32::try_from(offset).unwrap();
1609
1610    func.sized_stack_slots
1611        .reserve(callee.sized_stack_slots.len());
1612    for slot in callee.sized_stack_slots.values() {
1613        func.sized_stack_slots.push(slot.clone());
1614    }
1615
1616    offset
1617}
1618
1619/// Copy dynamic types from the callee into the caller.
1620fn create_dynamic_types(
1621    func: &mut ir::Function,
1622    callee: &ir::Function,
1623    entity_map: &EntityMap,
1624) -> u32 {
1625    let offset = func.dfg.dynamic_types.len();
1626    let offset = u32::try_from(offset).unwrap();
1627
1628    func.dfg
1629        .dynamic_types
1630        .reserve(callee.dfg.dynamic_types.len());
1631    for ir::DynamicTypeData {
1632        base_vector_ty,
1633        dynamic_scale,
1634    } in callee.dfg.dynamic_types.values()
1635    {
1636        func.dfg.dynamic_types.push(ir::DynamicTypeData {
1637            base_vector_ty: *base_vector_ty,
1638            dynamic_scale: entity_map.inlined_global_value(*dynamic_scale),
1639        });
1640    }
1641
1642    offset
1643}
1644
1645/// Copy dynamic stack slots from the callee into the caller.
1646fn create_dynamic_stack_slots(
1647    func: &mut ir::Function,
1648    callee: &ir::Function,
1649    entity_map: &EntityMap,
1650) -> u32 {
1651    let offset = func.dynamic_stack_slots.len();
1652    let offset = u32::try_from(offset).unwrap();
1653
1654    func.dynamic_stack_slots
1655        .reserve(callee.dynamic_stack_slots.len());
1656    for ir::DynamicStackSlotData { kind, dyn_ty } in callee.dynamic_stack_slots.values() {
1657        func.dynamic_stack_slots.push(ir::DynamicStackSlotData {
1658            kind: *kind,
1659            dyn_ty: entity_map.inlined_dynamic_type(*dyn_ty),
1660        });
1661    }
1662
1663    offset
1664}
1665
1666/// Copy immediates from the callee into the caller.
1667fn create_immediates(func: &mut ir::Function, callee: &ir::Function) -> u32 {
1668    let offset = func.dfg.immediates.len();
1669    let offset = u32::try_from(offset).unwrap();
1670
1671    func.dfg.immediates.reserve(callee.dfg.immediates.len());
1672    for imm in callee.dfg.immediates.values() {
1673        func.dfg.immediates.push(imm.clone());
1674    }
1675
1676    offset
1677}
1678
1679/// Copy constants from the callee into the caller.
1680fn create_constants(allocs: &mut InliningAllocs, func: &mut ir::Function, callee: &ir::Function) {
1681    for (callee_constant, data) in callee.dfg.constants.iter() {
1682        let inlined_constant = func.dfg.constants.insert(data.clone());
1683        allocs.constants[*callee_constant] = Some(inlined_constant).into();
1684    }
1685}