Skip to main content

wasmtime_environ/fact/
trampoline.rs

1//! Low-level compilation of an fused adapter function.
2//!
3//! This module is tasked with the top-level `compile` function which creates a
4//! single WebAssembly function which will perform the steps of the fused
5//! adapter for an `AdapterData` provided. This is the "meat" of compilation
6//! where the validation of the canonical ABI or similar all happens to
7//! translate arguments from one module to another.
8//!
9//! ## Traps and their ordering
10//!
11//! Currently this compiler is pretty "loose" about the ordering of precisely
12//! what trap happens where. The main reason for this is that to core wasm all
13//! traps are the same and for fused adapters if a trap happens no intermediate
14//! side effects are visible (as designed by the canonical ABI itself). For this
15//! it's important to note that some of the precise choices of control flow here
16//! can be somewhat arbitrary, an intentional decision.
17
18use crate::component::{
19    CanonicalAbiInfo, ComponentTypesBuilder, FixedEncoding as FE, FlatType, InterfaceType,
20    MAX_FLAT_ASYNC_PARAMS, MAX_FLAT_PARAMS, PREPARE_ASYNC_NO_RESULT, PREPARE_ASYNC_WITH_RESULT,
21    START_FLAG_ASYNC_CALLEE, START_FLAG_ASYNC_CALLER, StringEncoding, Transcode,
22    TypeComponentLocalErrorContextTableIndex, TypeEnumIndex, TypeFixedLengthListIndex,
23    TypeFlagsIndex, TypeFutureTableIndex, TypeListIndex, TypeMapIndex, TypeOptionIndex,
24    TypeRecordIndex, TypeResourceTableIndex, TypeResultIndex, TypeStreamTableIndex, TypeTupleIndex,
25    TypeVariantIndex, VariantInfo,
26};
27use crate::fact::signature::Signature;
28use crate::fact::transcode::Transcoder;
29use crate::fact::{
30    AdapterData, Body, Function, FunctionId, Helper, HelperLocation, HelperType,
31    LinearMemoryOptions, Module, Options,
32};
33use crate::prelude::*;
34use crate::{FuncIndex, GlobalIndex, IndexType, NUM_COMPONENT_CONTEXT_SLOTS, Trap};
35use std::collections::HashMap;
36use std::mem;
37use std::ops::Range;
38use wasm_encoder::{
39    BlockType, Catch, Encode, Instruction, Instruction::*, MemArg, MemArgTarget, ValType,
40};
41use wasmtime_component_util::{DiscriminantSize, FlagsSize};
42
43use super::DataModel;
44
45const MAX_STRING_BYTE_LENGTH: u32 = (1 << 31) - 1;
46
47/// This value is arbitrarily chosen and should be fine to change at any time,
48/// it just seemed like a halfway reasonable starting point.
49const INITIAL_FUEL: usize = 1_000;
50
51struct Compiler<'a, 'b> {
52    types: &'a ComponentTypesBuilder,
53    module: &'b mut Module<'a>,
54    result: FunctionId,
55
56    /// The encoded WebAssembly function body so far, not including locals.
57    code: Vec<u8>,
58
59    /// Total number of locals generated so far.
60    nlocals: u32,
61
62    /// Locals partitioned by type which are not currently in use.
63    free_locals: HashMap<ValType, Vec<u32>>,
64
65    /// A heuristic which is intended to limit the size of a generated function
66    /// to a certain maximum to avoid generating arbitrarily large functions.
67    ///
68    /// This fuel counter is decremented each time `translate` is called and
69    /// when fuel is entirely consumed further translations, if necessary, will
70    /// be done through calls to other functions in the module. This is intended
71    /// to be a heuristic to split up the main function into theoretically
72    /// reusable portions.
73    fuel: usize,
74
75    /// Indicates whether an "enter call" should be emitted in the generated
76    /// function with a call to `Resource{Enter,Exit}Call` at the beginning and
77    /// end of the function for tracking of information related to borrowed
78    /// resources.
79    emit_resource_call: bool,
80}
81
82pub(super) fn compile(module: &mut Module<'_>, adapter: &AdapterData) {
83    fn compiler<'a, 'b>(
84        module: &'b mut Module<'a>,
85        adapter: &AdapterData,
86    ) -> (Compiler<'a, 'b>, Signature, Signature) {
87        let lower_sig = module.types.signature(&adapter.lower);
88        let lift_sig = module.types.signature(&adapter.lift);
89        let ty = module
90            .core_types
91            .function(&lower_sig.params, &lower_sig.results);
92        let result = module
93            .funcs
94            .push(Function::new(Some(adapter.name.clone()), ty));
95
96        // If this type signature contains any borrowed resources then invocations
97        // of enter/exit call for resource-related metadata tracking must be used.
98        // It shouldn't matter whether the lower/lift signature is used here as both
99        // should return the same answer.
100        let emit_resource_call = module.types.contains_borrow_resource(&adapter.lower);
101        assert_eq!(
102            emit_resource_call,
103            module.types.contains_borrow_resource(&adapter.lift)
104        );
105
106        (
107            Compiler::new(
108                module,
109                result,
110                lower_sig.params.len() as u32,
111                emit_resource_call,
112            ),
113            lower_sig,
114            lift_sig,
115        )
116    }
117
118    // Disallow same-instance adapters. This is, as of the time of this writing,
119    // technically not spec-conformant. This is something we'll want to
120    // reconcile with the upstream specification because without this check the
121    // precise order of lifts/lowers is visible to the guest which is generally
122    // not something that the spec desires.
123    if adapter.lift.instance == adapter.lower.instance {
124        let (mut compiler, _, _) = compiler(module, adapter);
125        compiler.trap(Trap::CannotEnterComponent);
126        compiler.finish();
127        return;
128    }
129
130    // This closure compiles a function to be exported to the host which host to
131    // lift the parameters from the caller and lower them to the callee.
132    //
133    // This allows the host to delay copying the parameters until the callee
134    // signals readiness by clearing its backpressure flag.
135    let async_start_adapter = |module: &mut Module| {
136        let sig = module
137            .types
138            .async_start_signature(&adapter.lower, &adapter.lift);
139        let ty = module.core_types.function(&sig.params, &sig.results);
140        let result = module.funcs.push(Function::new(
141            Some(format!("[async-start]{}", adapter.name)),
142            ty,
143        ));
144
145        Compiler::new(module, result, sig.params.len() as u32, false)
146            .compile_async_start_adapter(adapter, &sig);
147
148        result
149    };
150
151    // This closure compiles a function to be exported by the adapter module and
152    // called by the host to lift the results from the callee and lower them to
153    // the caller.
154    //
155    // Given that async-lifted exports return their results via the
156    // `task.return` intrinsic, the host will need to copy the results from
157    // callee to caller when that intrinsic is called rather than when the
158    // callee task fully completes (which may happen much later).
159    let async_return_adapter = |module: &mut Module| {
160        let sig = module
161            .types
162            .async_return_signature(&adapter.lower, &adapter.lift);
163        let ty = module.core_types.function(&sig.params, &sig.results);
164        let result = module.funcs.push(Function::new(
165            Some(format!("[async-return]{}", adapter.name)),
166            ty,
167        ));
168
169        Compiler::new(module, result, sig.params.len() as u32, false)
170            .compile_async_return_adapter(adapter, &sig);
171
172        result
173    };
174
175    let lower_async = adapter.lower.options.async_;
176    let lift_async = adapter.lift.options.async_;
177    if !lower_async && !lift_async && !module.types[adapter.lift.ty].async_ {
178        // We can adapt sync->sync case with only minimal use of intrinsics,
179        // e.g. resource enter and exit calls as needed.
180        let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
181        compiler.compile_sync_to_sync_adapter(adapter, &lower_sig, &lift_sig);
182        return;
183    }
184
185    assert!(module.tunables.concurrency_support);
186
187    // All other cases are mediated by the host: the caller and/or callee use
188    // the async ABI, or the callee has an async function type (in which case
189    // it's subject to backpressure and exclusive-entry checks even if both
190    // sides are otherwise sync).  For these we compile a couple of helper
191    // functions:
192    //
193    // - `async-start`: copies the parameters from the caller to the callee
194    // - `async-return`: copies the result from the callee to the caller
195    //
196    // The host calls `async-start` once the callee is ready to handle a new
197    // call (e.g. it has no backpressure and, if required, its instance isn't
198    // exclusively held by another task), which may not be immediately.  It
199    // calls `async-return` once the callee has produced its result, either
200    // via `task.return` (if async-lifted) or by returning (if sync-lifted).
201    //
202    // In the meantime, an async caller gets control back immediately so it can
203    // do other work, and is later notified of the subtask's progress via
204    // events.  A sync caller instead blocks until the callee has produced its
205    // result.  Since a sync caller may have passed its parameters on the stack
206    // rather than in linear memory, the host stores them in a task-local
207    // location until `async-start` is called, and similarly stores the results
208    // until the caller is resumed.
209    let start = async_start_adapter(module);
210    let return_ = async_return_adapter(module);
211    let (compiler, lower_sig, lift_sig) = compiler(module, adapter);
212    compiler.compile_host_mediated_adapter(adapter, start, return_, &lower_sig, &lift_sig);
213}
214
215/// Compiles a helper function as specified by the `Helper` configuration.
216///
217/// This function is invoked when the translation process runs out of fuel for
218/// some prior function which enqueues a helper to get translated later. This
219/// translation function will perform one type translation as specified by
220/// `Helper` which can either be in the stack or memory for each side.
221pub(super) fn compile_helper(module: &mut Module<'_>, result: FunctionId, helper: Helper) {
222    let mut nlocals = 0;
223    let src_flat;
224    let src = match helper.src.loc {
225        // If the source is on the stack then it's specified in the parameters
226        // to the function, so this creates the flattened representation and
227        // then lists those as the locals with appropriate types for the source
228        // values.
229        HelperLocation::Stack => {
230            src_flat = module
231                .types
232                .flatten_types(&helper.src.opts, usize::MAX, [helper.src.ty])
233                .unwrap()
234                .iter()
235                .enumerate()
236                .map(|(i, ty)| (i as u32, *ty))
237                .collect::<Vec<_>>();
238            nlocals += src_flat.len() as u32;
239            Source::Stack(Stack {
240                locals: &src_flat,
241                opts: &helper.src.opts,
242            })
243        }
244        // If the source is in memory then that's just propagated here as the
245        // first local is the pointer to the source.
246        HelperLocation::Memory => {
247            nlocals += 1;
248            Source::Memory(Memory {
249                opts: &helper.src.opts,
250                addr: TempLocal::new(0, helper.src.opts.data_model.unwrap_memory().ptr()),
251                offset: 0,
252            })
253        }
254        HelperLocation::StructField | HelperLocation::ArrayElement => todo!("CM+GC"),
255    };
256    let dst_flat;
257    let dst = match helper.dst.loc {
258        // This is the same as the stack-based source although `Destination` is
259        // configured slightly differently.
260        HelperLocation::Stack => {
261            dst_flat = module
262                .types
263                .flatten_types(&helper.dst.opts, usize::MAX, [helper.dst.ty])
264                .unwrap();
265            Destination::Stack(&dst_flat, &helper.dst.opts)
266        }
267        // This is the same as a memory-based source but note that the address
268        // of the destination is passed as the final parameter to the function.
269        HelperLocation::Memory => {
270            nlocals += 1;
271            Destination::Memory(Memory {
272                opts: &helper.dst.opts,
273                addr: TempLocal::new(
274                    nlocals - 1,
275                    helper.dst.opts.data_model.unwrap_memory().ptr(),
276                ),
277                offset: 0,
278            })
279        }
280        HelperLocation::StructField | HelperLocation::ArrayElement => todo!("CM+GC"),
281    };
282    let mut compiler = Compiler {
283        types: module.types,
284        module,
285        code: Vec::new(),
286        nlocals,
287        free_locals: HashMap::new(),
288        result,
289        fuel: INITIAL_FUEL,
290        // This is a helper function and only the top-level function is
291        // responsible for emitting these intrinsic calls.
292        emit_resource_call: false,
293    };
294    compiler.translate(&helper.src.ty, &src, &helper.dst.ty, &dst);
295    compiler.finish();
296}
297
298/// Possible ways that a interface value is represented in the core wasm
299/// canonical ABI.
300enum Source<'a> {
301    /// This value is stored on the "stack" in wasm locals.
302    ///
303    /// This could mean that it's inline from the parameters to the function or
304    /// that after a function call the results were stored in locals and the
305    /// locals are the inline results.
306    Stack(Stack<'a>),
307
308    /// This value is stored in linear memory described by the `Memory`
309    /// structure.
310    Memory(Memory<'a>),
311
312    /// This value is stored in a GC struct field described by the `GcStruct`
313    /// structure.
314    #[allow(dead_code, reason = "CM+GC is still WIP")]
315    Struct(GcStruct<'a>),
316
317    /// This value is stored in a GC array element described by the `GcArray`
318    /// structure.
319    #[allow(dead_code, reason = "CM+GC is still WIP")]
320    Array(GcArray<'a>),
321}
322
323/// Same as `Source` but for where values are translated into.
324enum Destination<'a> {
325    /// This value is destined for the WebAssembly stack which means that
326    /// results are simply pushed as we go along.
327    ///
328    /// The types listed are the types that are expected to be on the stack at
329    /// the end of translation.
330    Stack(&'a [ValType], &'a Options),
331
332    /// This value is to be placed in linear memory described by `Memory`.
333    Memory(Memory<'a>),
334
335    /// This value is to be placed in a GC struct field described by the
336    /// `GcStruct` structure.
337    #[allow(dead_code, reason = "CM+GC is still WIP")]
338    Struct(GcStruct<'a>),
339
340    /// This value is to be placed in a GC array element described by the
341    /// `GcArray` structure.
342    #[allow(dead_code, reason = "CM+GC is still WIP")]
343    Array(GcArray<'a>),
344}
345
346struct Stack<'a> {
347    /// The locals that comprise a particular value.
348    ///
349    /// The length of this list represents the flattened list of types that make
350    /// up the component value. Each list has the index of the local being
351    /// accessed as well as the type of the local itself.
352    locals: &'a [(u32, ValType)],
353    /// The lifting/lowering options for where this stack of values comes from
354    opts: &'a Options,
355}
356
357/// Representation of where a value is going to be stored in linear memory.
358struct Memory<'a> {
359    /// The lifting/lowering options with memory configuration
360    opts: &'a Options,
361    /// The index of the local that contains the base address of where the
362    /// storage is happening.
363    addr: TempLocal,
364    /// A "static" offset that will be baked into wasm instructions for where
365    /// memory loads/stores happen.
366    offset: u32,
367}
368
369impl<'a> Memory<'a> {
370    fn mem_opts(&self) -> &'a LinearMemoryOptions {
371        self.opts.data_model.unwrap_memory()
372    }
373}
374
375/// Representation of where a value is coming from or going to in a GC struct.
376struct GcStruct<'a> {
377    opts: &'a Options,
378    // TODO: more fields to come in the future.
379}
380
381/// Representation of where a value is coming from or going to in a GC array.
382struct GcArray<'a> {
383    opts: &'a Options,
384    // TODO: more fields to come in the future.
385}
386
387impl<'a, 'b> Compiler<'a, 'b> {
388    fn new(
389        module: &'b mut Module<'a>,
390        result: FunctionId,
391        nlocals: u32,
392        emit_resource_call: bool,
393    ) -> Self {
394        Self {
395            types: module.types,
396            module,
397            result,
398            code: Vec::new(),
399            nlocals,
400            free_locals: HashMap::new(),
401            fuel: INITIAL_FUEL,
402            emit_resource_call,
403        }
404    }
405
406    /// Compile an adapter function for a call which is mediated by the host,
407    /// i.e. any call other than a sync->sync call to a sync-typed function.
408    ///
409    /// This uses a pair of `prepare-call` and `start-call` built-in functions
410    /// to set up and start a subtask, respectively.  `prepare-call` accepts
411    /// `start` and `return_` functions which copy the parameters and results,
412    /// respectively; the host will call the former when the callee may be
413    /// entered (e.g. it has no backpressure) and the latter when the callee has
414    /// produced its result.
415    ///
416    /// For an async caller, `start-call` returns the subtask's status.  For a
417    /// sync caller, it blocks until the callee has produced its result and
418    /// returns the lowered result, if any.
419    fn compile_host_mediated_adapter(
420        mut self,
421        adapter: &AdapterData,
422        start: FunctionId,
423        return_: FunctionId,
424        lower_sig: &Signature,
425        lift_sig: &Signature,
426    ) {
427        let async_caller = adapter.lower.options.async_;
428        let start_call = self.module.import_start_call(
429            &adapter.name,
430            adapter.lift.options.callback,
431            adapter.lift.post_return,
432            if async_caller {
433                &[ValType::I32]
434            } else {
435                &lower_sig.results
436            },
437        );
438
439        self.call_prepare(adapter, start, return_, lower_sig, !async_caller);
440
441        // TODO: As an optimization, consider checking the backpressure flag on
442        // the callee instance and, if it's unset _and_ the callee uses a
443        // callback, translate the params and call the callee function directly
444        // here (and make sure `start_call` knows _not_ to call it in that case).
445
446        // We export this function so we can pass a funcref to the host.
447        //
448        // TODO: Use a declarative element segment instead of exporting this.
449        self.module.exports.push((
450            adapter.callee.as_u32(),
451            format!("[adapter-callee]{}", adapter.name),
452        ));
453
454        let mut flags = 0;
455        if async_caller {
456            flags |= START_FLAG_ASYNC_CALLER;
457        }
458        if adapter.lift.options.async_ {
459            flags |= START_FLAG_ASYNC_CALLEE;
460        }
461
462        self.instruction(RefFunc(adapter.callee.as_u32()));
463        self.instruction(I32Const(i32::try_from(lift_sig.params.len()).unwrap()));
464        self.instruction(I32Const(i32::try_from(lift_sig.results.len()).unwrap()));
465        self.instruction(I32Const(flags));
466        self.instruction(Call(start_call.as_u32()));
467
468        self.finish()
469    }
470
471    /// Invokes the `prepare_call` builtin with the provided parameters for this
472    /// adapter.
473    ///
474    /// This is part of a async lower and/or async lift adapter. This is not
475    /// used for a sync->sync function call. This is done to create the task on
476    /// the host side of the runtime and such. This will notably invoke a
477    /// Cranelift builtin which will spill all wasm-level parameters to the
478    /// stack to handle variadic signatures.
479    ///
480    /// Note that the `prepare_sync` parameter here configures the
481    /// `result_count_or_max_if_async` parameter to indicate whether this is a
482    /// sync or async prepare.
483    fn call_prepare(
484        &mut self,
485        adapter: &AdapterData,
486        start: FunctionId,
487        return_: FunctionId,
488        lower_sig: &Signature,
489        prepare_sync: bool,
490    ) {
491        // Make sure the caller can indeed leave its instance before going
492        // further.
493        let saved = self.trap_if_not_may_leave(adapter.lower.flags, Trap::CannotLeaveComponent);
494        self.free_temp_local(saved);
495
496        let prepare = self.module.import_prepare_call(
497            &adapter.name,
498            &lower_sig.params,
499            match adapter.lift.options.data_model {
500                DataModel::Gc {} => todo!("CM+GC"),
501                DataModel::LinearMemory(LinearMemoryOptions { memory, .. }) => memory.map(|m| m.0),
502            },
503        );
504
505        self.push_body(Body::RefFunc(start));
506        self.push_body(Body::RefFunc(return_));
507        self.instruction(I32Const(
508            i32::try_from(adapter.lower.instance.as_u32()).unwrap(),
509        ));
510        self.instruction(I32Const(
511            i32::try_from(adapter.lift.instance.as_u32()).unwrap(),
512        ));
513        self.instruction(I32Const(
514            i32::try_from(self.types[adapter.lift.ty].results.as_u32()).unwrap(),
515        ));
516        self.instruction(I32Const(if self.types[adapter.lift.ty].async_ {
517            1
518        } else {
519            0
520        }));
521        self.instruction(I32Const(i32::from(
522            adapter.lift.options.string_encoding as u8,
523        )));
524
525        // flag this as a preparation for either an async call or sync call,
526        // depending on `prepare_sync`
527        let result_types = &self.types[self.types[adapter.lower.ty].results].types;
528        if prepare_sync {
529            self.instruction(I32Const(
530                i32::try_from(
531                    self.types
532                        .flatten_types(
533                            &adapter.lower.options,
534                            usize::MAX,
535                            result_types.iter().copied(),
536                        )
537                        .map(|v| v.len())
538                        .unwrap_or(usize::try_from(i32::MAX).unwrap()),
539                )
540                .unwrap(),
541            ));
542        } else {
543            if result_types.len() > 0 {
544                self.instruction(I32Const(PREPARE_ASYNC_WITH_RESULT.cast_signed()));
545            } else {
546                self.instruction(I32Const(PREPARE_ASYNC_NO_RESULT.cast_signed()));
547            }
548        }
549
550        // forward all our own arguments on to the host stub
551        for index in 0..lower_sig.params.len() {
552            self.instruction(LocalGet(u32::try_from(index).unwrap()));
553        }
554        self.instruction(Call(prepare.as_u32()));
555    }
556
557    /// Compiles a function to be exported to the host which host to lift the
558    /// parameters from the caller and lower them to the callee.
559    ///
560    /// This allows the host to delay copying the parameters until the callee
561    /// signals readiness by clearing its backpressure flag.
562    fn compile_async_start_adapter(mut self, adapter: &AdapterData, sig: &Signature) {
563        // Note that unlike `compile_sync_to_sync_adapter` no exception
564        // barrier is emitted here: this function is invoked by the host, so
565        // an exception thrown by any guest code it calls (e.g. `realloc`)
566        // unwinds to the host rather than into another component, and the
567        // host already catches it at that boundary.
568        let param_locals = sig
569            .params
570            .iter()
571            .enumerate()
572            .map(|(i, ty)| (i as u32, *ty))
573            .collect::<Vec<_>>();
574
575        let saved = self
576            .translate_params_may_call_lift_realloc(adapter)
577            .then(|| self.clear_may_leave(adapter.lift.flags));
578        self.translate_params(adapter, &param_locals);
579        if let Some(saved) = saved {
580            self.restore_may_leave(adapter.lift.flags, saved);
581        }
582
583        self.finish();
584    }
585
586    /// Compiles a function to be exported by the adapter module and called by
587    /// the host to lift the results from the callee and lower them to the
588    /// caller.
589    ///
590    /// Given that async-lifted exports return their results via the
591    /// `task.return` intrinsic, the host will need to copy the results from
592    /// callee to caller when that intrinsic is called rather than when the
593    /// callee task fully completes (which may happen much later).
594    fn compile_async_return_adapter(mut self, adapter: &AdapterData, sig: &Signature) {
595        // As with `compile_async_start_adapter`, no exception barrier is
596        // emitted here: the host invokes this function and already catches
597        // exceptions unwinding out of it.
598        let param_locals = sig
599            .params
600            .iter()
601            .enumerate()
602            .map(|(i, ty)| (i as u32, *ty))
603            .collect::<Vec<_>>();
604
605        let saved = self
606            .translate_results_may_call_lower_realloc(adapter)
607            .then(|| self.clear_may_leave(adapter.lower.flags));
608        // Note that we pass `param_locals` as _both_ the `param_locals` and
609        // `result_locals` parameters to `translate_results`.  That's because
610        // the _parameters_ to `task.return` are actually the _results_ that the
611        // caller is waiting for.
612        //
613        // Additionally, the host will append a return
614        // pointer to the end of that list before calling this adapter's
615        // `async-return` function if the results exceed `MAX_FLAT_RESULTS` or
616        // the import is lowered async, in which case `translate_results` will
617        // use that pointer to store the results.
618        self.translate_results(adapter, &param_locals, &param_locals);
619        if let Some(saved) = saved {
620            self.restore_may_leave(adapter.lower.flags, saved);
621        }
622
623        self.finish()
624    }
625
626    /// Compile an adapter function supporting a sync-lowered import to a
627    /// sync-lifted export.
628    ///
629    /// Unlike calls involving async-lowered imports or async-lifted exports,
630    /// this adapter need not involve host built-ins except possibly for
631    /// resource bookkeeping.
632    fn compile_sync_to_sync_adapter(
633        mut self,
634        adapter: &AdapterData,
635        lower_sig: &Signature,
636        lift_sig: &Signature,
637    ) {
638        self.enter_exception_barrier(&lower_sig.results);
639
640        // Check the instance flags required for this trampoline.
641        //
642        // This inserts the initial check required by `canon_lower` that the
643        // caller instance can be left and additionally checks the
644        // flags on the callee if necessary whether it can be entered.
645        //
646        // The loaded `may_leave` value is saved into `saved_lower_may_leave`
647        // so that it can be restored after results are translated below
648        // without reloading the global.
649        let saved_lower_may_leave =
650            self.trap_if_not_may_leave(adapter.lower.flags, Trap::CannotLeaveComponent);
651
652        // If nothing that this adapter can reach is able to observe or mutate
653        // the thread state that `enter-sync-call`/`exit-sync-call` maintain then
654        // none of its bookkeeping is necessary.
655        //
656        // See `crates/environ/src/component/thread_transparency.rs` for details.
657        debug_assert!(
658            !(adapter.thread_transparent && self.emit_resource_call),
659            "resources are not thread transparent",
660        );
661        let needs_thread_state =
662            self.module.tunables.concurrency_support && !adapter.thread_transparent;
663
664        if needs_thread_state {
665            // Push a task onto the current task stack.
666            //
667            // Note that for sync-to-sync calls, we replace this call with
668            // inline code for lazy/deferred task creation during translation to
669            // CLIF. This avoids task creation and out-of-line calls in the
670            // adapter for most sync-to-sync calls, since most sync-to-sync
671            // calls do not do anything to force the task's creation
672            // (e.g. adjust backpressure).
673            self.instruction(I32Const(if self.types[adapter.lift.ty].async_ {
674                1
675            } else {
676                0
677            }));
678            self.instruction(I32Const(
679                i32::try_from(adapter.lift.instance.as_u32()).unwrap(),
680            ));
681            let enter_sync_call = self.module.import_enter_sync_call();
682            self.instruction(Call(enter_sync_call.as_u32()));
683        } else if self.emit_resource_call {
684            assert!(!self.types[adapter.lift.ty].async_);
685            self.instruction(I32Const(0));
686            self.instruction(I32Const(
687                i32::try_from(adapter.lift.instance.as_u32()).unwrap(),
688            ));
689            let enter_sync_call = self.module.import_enter_sync_call();
690            self.instruction(Call(enter_sync_call.as_u32()));
691        }
692
693        // Perform the translation of arguments. Note that the `may_leave` flag
694        // is cleared around this invocation for the callee as per the
695        // `canon_lift` definition in the spec. Additionally note that the
696        // precise ordering of traps here is not required since internal state
697        // is not visible to either instance and a trap will "lock down" both
698        // instances to no longer be visible. This means that we're free to
699        // reorder lifts/lowers and flags and such as is necessary and
700        // convenient here.
701        //
702        // The clear-and-restore is structured (a constant `0` store to clear,
703        // then a store of the saved original value to restore) so that if
704        // translation doesn't actually call any functions in either instance
705        // then a future dead-store elimination pass in Cranelift can remove all
706        // the flag juggling entirely (other than trapping when `!may_leave`):
707        //
708        //     may_leave = load vmctx+MAY_LEAVE_OFFSET      ;; (0)
709        //     trapz may_leave
710        //
711        //     ...
712        //
713        //     zero = iconst 0
714        //     store zero, vmctx+MAY_LEAVE_OFFSET           ;; (1)
715        //
716        //     ...
717        //
718        //     store may_leave, vmctx+MAY_LEAVE_OFFSET      ;; (2)
719        //
720        // First, the dead-store elimination pass will see that the the store at
721        // (1) is dead and remove it. Then, the idempotent-store eliminator will
722        // recognize that the store at (2) is storing the same value that the
723        // memory location already contains and it will also be removed. The
724        // more we can reuse locals to make this idempotency obvious, rather
725        // than force Cranelift's optimizer to rediscover this information, the
726        // better.
727        //
728        // If translation can't call the callee's `realloc` then no callee code
729        // runs while the flag is cleared, so the clear-and-restore is skipped
730        // entirely. Cranelift can't always remove it on its own because host
731        // libcalls made during translation (e.g. resource transfers) are
732        // opaque.
733        let saved_lift_may_leave = self
734            .translate_params_may_call_lift_realloc(adapter)
735            .then(|| self.clear_may_leave(adapter.lift.flags));
736        let param_locals = lower_sig
737            .params
738            .iter()
739            .enumerate()
740            .map(|(i, ty)| (i as u32, *ty))
741            .collect::<Vec<_>>();
742        self.translate_params(adapter, &param_locals);
743        if let Some(saved) = saved_lift_may_leave {
744            self.restore_may_leave(adapter.lift.flags, saved);
745        }
746
747        // With all the arguments on the stack the actual target function is
748        // now invoked. The core wasm results of the function are then placed
749        // into locals for result translation afterwards.
750
751        self.instruction(Call(adapter.callee.as_u32()));
752
753        let mut result_locals = Vec::with_capacity(lift_sig.results.len());
754        let mut temps = Vec::new();
755        for ty in lift_sig.results.iter().rev() {
756            let local = self.local_set_new_tmp(*ty);
757            result_locals.push((local.idx, *ty));
758            temps.push(local);
759        }
760        result_locals.reverse();
761
762        // The `exit-sync-call` intrinsic below will clobber this task's context
763        // slots, but if we've got a post-return we'll want to restore them
764        // temporarily for that. Save them if it's necessary.
765        let callee_context = if adapter.lift.post_return.is_some() {
766            self.save_context()
767        } else {
768            Vec::new()
769        };
770
771        // Handle a few things related to the concurrent task infrastructure
772        // after the callee has finished, such as:
773        //
774        // * Validate that the callee dropped all its borrows
775        // * Transition the current running task back to the caller.
776        //
777        // This is not necessary if there are no resources in this call, nor if
778        // concurrency support is disabled (no tasks). Note that this must
779        // happen before lowering below because semantically that's where the
780        // "you forgot to drop borrows" trap shows up and additionally the
781        // lowering below may call realloc which is in the context of the
782        // caller's task, not the callee.
783        //
784        // Note that for sync-to-sync calls, we will emit inline code during
785        // translation to CLIF to avoid actually calling out to a libcall when
786        // the deferred task's allocation was never forced.
787        if self.emit_resource_call || needs_thread_state {
788            let exit_sync_call = self.module.import_exit_sync_call();
789            self.instruction(Call(exit_sync_call.as_u32()));
790        }
791
792        // Like above during the translation of results the caller cannot be
793        // left (as we might invoke things like `realloc`). Again the precise
794        // order of everything doesn't matter since intermediate states cannot
795        // be witnessed, hence the setting of flags here to encapsulate both
796        // liftings and lowerings. As with parameters, this is skipped if
797        // translation can't call the caller's `realloc`.
798        if self.translate_results_may_call_lower_realloc(adapter) {
799            self.set_may_leave_false(adapter.lower.flags);
800            self.translate_results(adapter, &param_locals, &result_locals);
801            self.restore_may_leave(adapter.lower.flags, saved_lower_may_leave);
802        } else {
803            self.translate_results(adapter, &param_locals, &result_locals);
804            self.free_temp_local(saved_lower_may_leave);
805        }
806
807        // And finally post-return state is handled here once all results/etc
808        // are all translated.
809        //
810        // Note that for this call the callee's previous context is shuffled
811        // in-and-then-back-out after the call. Additionally the callee cannot
812        // leave its instance during post-return, so `may_leave` is cleared.
813        if let Some(func) = adapter.lift.post_return {
814            let caller_context = self.save_context();
815            self.restore_context(callee_context);
816            let saved_lift_may_leave = self.clear_may_leave(adapter.lift.flags);
817            for (result, _) in result_locals.iter() {
818                self.instruction(LocalGet(*result));
819            }
820            self.instruction(Call(func.as_u32()));
821            self.restore_may_leave(adapter.lift.flags, saved_lift_may_leave);
822            self.restore_context(caller_context);
823        } else {
824            assert!(callee_context.is_empty());
825        }
826
827        for tmp in temps {
828            self.free_temp_local(tmp);
829        }
830
831        self.exit_exception_barrier();
832
833        self.finish()
834    }
835
836    /// The maximum number of flat parameters a lifted function receives on the
837    /// stack before they are spilled to memory allocated with its `realloc`.
838    fn max_lift_flat_params(lift_opts: &Options) -> usize {
839        match lift_opts.data_model {
840            DataModel::Gc {} => usize::MAX,
841            DataModel::LinearMemory(_) => MAX_FLAT_PARAMS,
842        }
843    }
844
845    /// Whether `translate_params` might call the callee's `realloc`.
846    fn translate_params_may_call_lift_realloc(&self, adapter: &AdapterData) -> bool {
847        let lift_opts = &adapter.lift.options;
848        let tys = &self.types[self.types[adapter.lift.ty].params].types;
849        tys.iter().any(|ty| self.types.ty_needs_realloc(ty))
850            || self
851                .types
852                .flatten_types(
853                    lift_opts,
854                    Self::max_lift_flat_params(lift_opts),
855                    tys.iter().copied(),
856                )
857                .is_none()
858    }
859
860    /// Whether `translate_results` might call the caller's `realloc`.
861    ///
862    /// Results that don't fit on the stack are written to a caller-provided
863    /// return pointer, so only strings, lists, and maps allocate.
864    fn translate_results_may_call_lower_realloc(&self, adapter: &AdapterData) -> bool {
865        let tys = &self.types[self.types[adapter.lower.ty].results].types;
866        tys.iter().any(|ty| self.types.ty_needs_realloc(ty))
867    }
868
869    fn translate_params(&mut self, adapter: &AdapterData, param_locals: &[(u32, ValType)]) {
870        let src_tys = self.types[adapter.lower.ty].params;
871        let src_tys = self.types[src_tys]
872            .types
873            .iter()
874            .copied()
875            .collect::<Vec<_>>();
876        self.init_hostcall_fuel(&src_tys);
877        let dst_tys = self.types[adapter.lift.ty].params;
878        let dst_tys = self.types[dst_tys]
879            .types
880            .iter()
881            .copied()
882            .collect::<Vec<_>>();
883        let lift_opts = &adapter.lift.options;
884        let lower_opts = &adapter.lower.options;
885
886        // TODO: handle subtyping
887        assert_eq!(src_tys.len(), dst_tys.len());
888
889        // Async lowered functions have a smaller limit on flat parameters, but
890        // their destination, a lifted function, does not have a different limit
891        // than sync functions.
892        let max_flat_params = match lower_opts.data_model {
893            // Under the GC data model the core function type is declared
894            // up-front via the `core-type` canonical option and maps 1:1 to the
895            // component type, so parameters are never spilled to memory.
896            DataModel::Gc {} => usize::MAX,
897            DataModel::LinearMemory(_) if adapter.lower.options.async_ => MAX_FLAT_ASYNC_PARAMS,
898            DataModel::LinearMemory(_) => MAX_FLAT_PARAMS,
899        };
900        let src_flat =
901            self.types
902                .flatten_types(lower_opts, max_flat_params, src_tys.iter().copied());
903        let max_dst_flat_params = Self::max_lift_flat_params(lift_opts);
904        let dst_flat =
905            self.types
906                .flatten_types(lift_opts, max_dst_flat_params, dst_tys.iter().copied());
907
908        let src = if let Some(flat) = &src_flat {
909            Source::Stack(Stack {
910                locals: &param_locals[..flat.len()],
911                opts: lower_opts,
912            })
913        } else {
914            // If there are too many parameters then that means the parameters
915            // are actually a tuple stored in linear memory addressed by the
916            // first parameter local.
917            let lower_mem_opts = lower_opts.data_model.unwrap_memory();
918            let (addr, ty) = param_locals[0];
919            assert_eq!(ty, lower_mem_opts.ptr());
920            let abi = CanonicalAbiInfo::record(src_tys.iter().map(|t| self.types.canonical_abi(t)));
921            Source::Memory(self.memory_operand_abi(
922                lower_opts,
923                TempLocal::new(addr, ty),
924                &abi,
925                Trap::MemoryOutOfBounds,
926            ))
927        };
928
929        let dst = if let Some(flat) = &dst_flat {
930            Destination::Stack(flat, lift_opts)
931        } else {
932            // If there are too many parameters then space is allocated in the
933            // destination module for the parameters via its `realloc` function.
934            let abi = CanonicalAbiInfo::record(dst_tys.iter().map(|t| self.types.canonical_abi(t)));
935            Destination::Memory(self.malloc_abi(lift_opts, &abi, Trap::MemoryOutOfBounds))
936        };
937
938        let srcs = src
939            .record_field_srcs(self.types, src_tys.iter().copied())
940            .zip(src_tys.iter());
941        let dsts = dst
942            .record_field_dsts(self.types, dst_tys.iter().copied())
943            .zip(dst_tys.iter());
944        for ((src, src_ty), (dst, dst_ty)) in srcs.zip(dsts) {
945            self.translate(&src_ty, &src, &dst_ty, &dst);
946        }
947
948        // If the destination was linear memory instead of the stack then the
949        // actual parameter that we're passing is the address of the values
950        // stored, so ensure that's happening in the wasm body here.
951        if let Destination::Memory(mem) = dst {
952            self.instruction(LocalGet(mem.addr.idx));
953            self.free_temp_local(mem.addr);
954        }
955    }
956
957    fn translate_results(
958        &mut self,
959        adapter: &AdapterData,
960        param_locals: &[(u32, ValType)],
961        result_locals: &[(u32, ValType)],
962    ) {
963        let src_tys = self.types[adapter.lift.ty].results;
964        let src_tys = self.types[src_tys]
965            .types
966            .iter()
967            .copied()
968            .collect::<Vec<_>>();
969        self.init_hostcall_fuel(&src_tys);
970        let dst_tys = self.types[adapter.lower.ty].results;
971        let dst_tys = self.types[dst_tys]
972            .types
973            .iter()
974            .copied()
975            .collect::<Vec<_>>();
976        let lift_opts = &adapter.lift.options;
977        let lower_opts = &adapter.lower.options;
978
979        let src_flat = self
980            .types
981            .flatten_lifting_types(lift_opts, src_tys.iter().copied());
982        let dst_flat = self
983            .types
984            .flatten_lowering_types(lower_opts, dst_tys.iter().copied());
985
986        let src = if src_flat.is_some() {
987            Source::Stack(Stack {
988                locals: result_locals,
989                opts: lift_opts,
990            })
991        } else {
992            // The original results to read from in this case come from the
993            // return value of the function itself. The imported function will
994            // return a linear memory address at which the values can be read
995            // from.
996            let abi = CanonicalAbiInfo::record(src_tys.iter().map(|t| self.types.canonical_abi(t)));
997            assert_eq!(
998                result_locals.len(),
999                if lower_opts.async_ || lift_opts.async_ || self.types[adapter.lift.ty].async_ {
1000                    2
1001                } else {
1002                    1
1003                }
1004            );
1005            let (addr, ty) = result_locals[0];
1006            assert_eq!(ty, lift_opts.data_model.unwrap_memory().ptr());
1007            Source::Memory(self.memory_operand_abi(
1008                lift_opts,
1009                TempLocal::new(addr, ty),
1010                &abi,
1011                Trap::MemoryOutOfBounds,
1012            ))
1013        };
1014
1015        let dst = if let Some(flat) = &dst_flat {
1016            Destination::Stack(flat, lower_opts)
1017        } else {
1018            // This is slightly different than `translate_params` where the
1019            // return pointer was provided by the caller of this function
1020            // meaning the last parameter local is a pointer into linear memory.
1021            let abi = CanonicalAbiInfo::record(dst_tys.iter().map(|t| self.types.canonical_abi(t)));
1022            let (addr, ty) = *param_locals.last().expect("no retptr");
1023            assert_eq!(ty, lower_opts.data_model.unwrap_memory().ptr());
1024            Destination::Memory(self.memory_operand_abi(
1025                lower_opts,
1026                TempLocal::new(addr, ty),
1027                &abi,
1028                Trap::MemoryOutOfBounds,
1029            ))
1030        };
1031
1032        let srcs = src
1033            .record_field_srcs(self.types, src_tys.iter().copied())
1034            .zip(src_tys.iter());
1035        let dsts = dst
1036            .record_field_dsts(self.types, dst_tys.iter().copied())
1037            .zip(dst_tys.iter());
1038        for ((src, src_ty), (dst, dst_ty)) in srcs.zip(dsts) {
1039            self.translate(&src_ty, &src, &dst_ty, &dst);
1040        }
1041    }
1042
1043    fn translate(
1044        &mut self,
1045        src_ty: &InterfaceType,
1046        src: &Source<'_>,
1047        dst_ty: &InterfaceType,
1048        dst: &Destination,
1049    ) {
1050        if let Source::Memory(mem) = src {
1051            self.assert_aligned(src_ty, mem);
1052        }
1053        if let Destination::Memory(mem) = dst {
1054            self.assert_aligned(dst_ty, mem);
1055        }
1056
1057        // Calculate a cost heuristic for what the translation of this specific
1058        // layer of the type is going to incur. The purpose of this cost is that
1059        // we'll deduct it from `self.fuel` and if no fuel is remaining then
1060        // translation is outlined into a separate function rather than being
1061        // translated into this function.
1062        //
1063        // The general goal is to avoid creating an exponentially sized function
1064        // for a linearly sized input (the type section). By outlining helper
1065        // functions there will ideally be a constant set of helper functions
1066        // per type (to accommodate in-memory or on-stack transfers as well as
1067        // src/dst options) which means that each function is at most a certain
1068        // size and we have a linear number of functions which should guarantee
1069        // an overall linear size of the output.
1070        //
1071        // To implement this the current heuristic is that each layer of
1072        // translating a type has a cost associated with it and this cost is
1073        // accounted for in `self.fuel`. Some conversions are considered free as
1074        // they generate basically as much code as the `call` to the translation
1075        // function while other are considered proportionally expensive to the
1076        // size of the type. The hope is that some upper layers are of a type's
1077        // translation are all inlined into one function but bottom layers end
1078        // up getting outlined to separate functions. Theoretically, again this
1079        // is built on hopes and dreams, the outlining can be shared amongst
1080        // tightly-intertwined type hierarchies which will reduce the size of
1081        // the output module due to the helpers being used.
1082        //
1083        // This heuristic of how to split functions has changed a few times in
1084        // the past and this isn't necessarily guaranteed to be the final
1085        // iteration.
1086        let cost = match src_ty {
1087            // These types are all quite simple to load/store and equate to
1088            // basically the same cost of the `call` instruction to call an
1089            // out-of-line translation function, so give them 0 cost.
1090            InterfaceType::Bool
1091            | InterfaceType::U8
1092            | InterfaceType::S8
1093            | InterfaceType::U16
1094            | InterfaceType::S16
1095            | InterfaceType::U32
1096            | InterfaceType::S32
1097            | InterfaceType::U64
1098            | InterfaceType::S64
1099            | InterfaceType::Float32
1100            | InterfaceType::Float64 => 0,
1101
1102            // This has a small amount of validation associated with it, so
1103            // give it a cost of 1.
1104            InterfaceType::Char => 1,
1105
1106            // This has a fair bit of code behind it depending on the
1107            // strings/encodings in play, so arbitrarily assign it this cost.
1108            InterfaceType::String => 40,
1109
1110            // Iteration of a loop is along the lines of the cost of a string
1111            // so give it the same cost
1112            InterfaceType::List(_) => 40,
1113            // Maps are similar to lists in terms of iteration cost
1114            InterfaceType::Map(_) => 40,
1115
1116            InterfaceType::Flags(i) => {
1117                let count = self.module.types[*i].names.len();
1118                match FlagsSize::from_count(count) {
1119                    FlagsSize::Size0 => 0,
1120                    FlagsSize::Size1 | FlagsSize::Size2 => 1,
1121                    FlagsSize::Size4Plus(n) => n.into(),
1122                }
1123            }
1124
1125            InterfaceType::Record(i) => self.types[*i].fields.len(),
1126            InterfaceType::Tuple(i) => self.types[*i].types.len(),
1127            InterfaceType::Variant(i) => self.types[*i].cases.len(),
1128            InterfaceType::Enum(i) => self.types[*i].names.len(),
1129
1130            // 2 cases to consider for each of these variants.
1131            InterfaceType::Option(_) | InterfaceType::Result(_) => 2,
1132
1133            // TODO(#6696) - something nonzero, is 1 right?
1134            InterfaceType::Own(_)
1135            | InterfaceType::Borrow(_)
1136            | InterfaceType::Future(_)
1137            | InterfaceType::Stream(_)
1138            | InterfaceType::ErrorContext(_) => 1,
1139            InterfaceType::FixedLengthList(i) => self.types[*i].size as usize,
1140        };
1141
1142        // If this function has the initial set of fuel then we want to be sure
1143        // to translate at least one type, even if it's a huge one,
1144        // unconditionally allow this type to get translate.d Here
1145        // `saturating_sub` will clamp at 0 if `cost` is higher than `fuel`,
1146        // which is what we want anyway where if this type is huge it just
1147        // prevents other translations in this function.
1148        let remaining_fuel = if self.fuel == INITIAL_FUEL {
1149            Some(self.fuel.saturating_sub(cost))
1150        } else {
1151            self.fuel.checked_sub(cost)
1152        };
1153
1154        match remaining_fuel {
1155            // This function has enough fuel to perform the layer of translation
1156            // necessary for this type, so the fuel is updated in-place and
1157            // translation continues. Note that the recursion here is bounded by
1158            // the static recursion limit for all interface types as imposed
1159            // during the translation phase.
1160            Some(n) => {
1161                self.fuel = n;
1162                match src_ty {
1163                    InterfaceType::Bool => self.translate_bool(src, dst_ty, dst),
1164                    InterfaceType::U8 => self.translate_u8(src, dst_ty, dst),
1165                    InterfaceType::S8 => self.translate_s8(src, dst_ty, dst),
1166                    InterfaceType::U16 => self.translate_u16(src, dst_ty, dst),
1167                    InterfaceType::S16 => self.translate_s16(src, dst_ty, dst),
1168                    InterfaceType::U32 => self.translate_u32(src, dst_ty, dst),
1169                    InterfaceType::S32 => self.translate_s32(src, dst_ty, dst),
1170                    InterfaceType::U64 => self.translate_u64(src, dst_ty, dst),
1171                    InterfaceType::S64 => self.translate_s64(src, dst_ty, dst),
1172                    InterfaceType::Float32 => self.translate_f32(src, dst_ty, dst),
1173                    InterfaceType::Float64 => self.translate_f64(src, dst_ty, dst),
1174                    InterfaceType::Char => self.translate_char(src, dst_ty, dst),
1175                    InterfaceType::String => self.translate_string(src, dst_ty, dst),
1176                    InterfaceType::List(t) => self.translate_list(*t, src, dst_ty, dst),
1177                    InterfaceType::Map(t) => self.translate_map(*t, src, dst_ty, dst),
1178                    InterfaceType::Record(t) => self.translate_record(*t, src, dst_ty, dst),
1179                    InterfaceType::Flags(f) => self.translate_flags(*f, src, dst_ty, dst),
1180                    InterfaceType::Tuple(t) => self.translate_tuple(*t, src, dst_ty, dst),
1181                    InterfaceType::Variant(v) => self.translate_variant(*v, src, dst_ty, dst),
1182                    InterfaceType::Enum(t) => self.translate_enum(*t, src, dst_ty, dst),
1183                    InterfaceType::Option(t) => self.translate_option(*t, src, dst_ty, dst),
1184                    InterfaceType::Result(t) => self.translate_result(*t, src, dst_ty, dst),
1185                    InterfaceType::Own(t) => self.translate_own(*t, src, dst_ty, dst),
1186                    InterfaceType::Borrow(t) => self.translate_borrow(*t, src, dst_ty, dst),
1187                    InterfaceType::Future(t) => self.translate_future(*t, src, dst_ty, dst),
1188                    InterfaceType::Stream(t) => self.translate_stream(*t, src, dst_ty, dst),
1189                    InterfaceType::ErrorContext(t) => {
1190                        self.translate_error_context(*t, src, dst_ty, dst)
1191                    }
1192                    InterfaceType::FixedLengthList(t) => {
1193                        self.translate_fixed_length_list(*t, src, dst_ty, dst);
1194                    }
1195                }
1196            }
1197
1198            // This function does not have enough fuel left to perform this
1199            // layer of translation so the translation is deferred to a helper
1200            // function. The actual translation here is then done by marshalling
1201            // the src/dst into the function we're calling and then processing
1202            // the results.
1203            None => {
1204                let src_loc = match src {
1205                    // If the source is on the stack then `stack_get` is used to
1206                    // convert everything to the appropriate flat representation
1207                    // for the source type.
1208                    Source::Stack(stack) => {
1209                        for (i, ty) in stack
1210                            .opts
1211                            .flat_types(src_ty, self.types)
1212                            .unwrap()
1213                            .iter()
1214                            .enumerate()
1215                        {
1216                            let stack = stack.slice(i..i + 1);
1217                            self.stack_get(&stack, (*ty).into());
1218                        }
1219                        HelperLocation::Stack
1220                    }
1221                    // If the source is in memory then the pointer is passed
1222                    // through, but note that the offset must be factored in
1223                    // here since the translation function will start from
1224                    // offset 0.
1225                    Source::Memory(mem) => {
1226                        self.push_mem_addr(mem);
1227                        HelperLocation::Memory
1228                    }
1229                    Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1230                };
1231                let dst_loc = match dst {
1232                    Destination::Stack(..) => HelperLocation::Stack,
1233                    Destination::Memory(mem) => {
1234                        self.push_mem_addr(mem);
1235                        HelperLocation::Memory
1236                    }
1237                    Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1238                };
1239                // Generate a `FunctionId` corresponding to the `Helper`
1240                // configuration that is necessary here. This will ideally be a
1241                // "cache hit" and use a preexisting helper which represents
1242                // outlining what would otherwise be duplicate code within a
1243                // function to one function.
1244                let helper = self.module.translate_helper(Helper {
1245                    src: HelperType {
1246                        ty: *src_ty,
1247                        opts: *src.opts(),
1248                        loc: src_loc,
1249                    },
1250                    dst: HelperType {
1251                        ty: *dst_ty,
1252                        opts: *dst.opts(),
1253                        loc: dst_loc,
1254                    },
1255                });
1256                // Emit a `call` instruction which will get "relocated" to a
1257                // function index once translation has completely finished.
1258                self.push_body(Body::Call(helper));
1259
1260                // If the destination of the translation was on the stack then
1261                // the types on the stack need to be optionally converted to
1262                // different types (e.g. if the result here is part of a variant
1263                // somewhere else).
1264                //
1265                // This translation happens inline here by popping the results
1266                // into new locals and then using those locals to do a
1267                // `stack_set`.
1268                if let Destination::Stack(tys, opts) = dst {
1269                    let flat = self
1270                        .types
1271                        .flatten_types(opts, usize::MAX, [*dst_ty])
1272                        .unwrap();
1273                    assert_eq!(flat.len(), tys.len());
1274                    let locals = flat
1275                        .iter()
1276                        .rev()
1277                        .map(|ty| self.local_set_new_tmp(*ty))
1278                        .collect::<Vec<_>>();
1279                    for (ty, local) in tys.iter().zip(locals.into_iter().rev()) {
1280                        self.instruction(LocalGet(local.idx));
1281                        self.stack_set(std::slice::from_ref(ty), local.ty);
1282                        self.free_temp_local(local);
1283                    }
1284                }
1285            }
1286        }
1287    }
1288
1289    fn push_mem_addr(&mut self, mem: &Memory<'_>) {
1290        self.instruction(LocalGet(mem.addr.idx));
1291        if mem.offset != 0 {
1292            self.ptr_uconst(mem.mem_opts(), mem.offset);
1293            self.ptr_add(mem.mem_opts());
1294        }
1295    }
1296
1297    fn translate_bool(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1298        // TODO: subtyping
1299        assert!(matches!(dst_ty, InterfaceType::Bool));
1300        self.push_dst_addr(dst);
1301
1302        // Booleans are canonicalized to 0 or 1 as they pass through the
1303        // component boundary, so use a `select` instruction to do so.
1304        self.instruction(I32Const(1));
1305        self.instruction(I32Const(0));
1306        match src {
1307            Source::Memory(mem) => self.i32_load8u(mem),
1308            Source::Stack(stack) => self.stack_get(stack, ValType::I32),
1309            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1310        }
1311        self.instruction(Select);
1312
1313        match dst {
1314            Destination::Memory(mem) => self.i32_store8(mem),
1315            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1316            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1317        }
1318    }
1319
1320    fn translate_u8(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1321        // TODO: subtyping
1322        assert!(matches!(dst_ty, InterfaceType::U8));
1323        self.convert_u8_mask(src, dst, 0xff);
1324    }
1325
1326    fn convert_u8_mask(&mut self, src: &Source<'_>, dst: &Destination<'_>, mask: u8) {
1327        self.push_dst_addr(dst);
1328        let mut needs_mask = true;
1329        match src {
1330            Source::Memory(mem) => {
1331                self.i32_load8u(mem);
1332                needs_mask = mask != 0xff;
1333            }
1334            Source::Stack(stack) => {
1335                self.stack_get(stack, ValType::I32);
1336            }
1337            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1338        }
1339        if needs_mask {
1340            self.instruction(I32Const(i32::from(mask)));
1341            self.instruction(I32And);
1342        }
1343        match dst {
1344            Destination::Memory(mem) => self.i32_store8(mem),
1345            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1346            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1347        }
1348    }
1349
1350    fn translate_s8(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1351        // TODO: subtyping
1352        assert!(matches!(dst_ty, InterfaceType::S8));
1353        self.push_dst_addr(dst);
1354        match src {
1355            Source::Memory(mem) => self.i32_load8s(mem),
1356            Source::Stack(stack) => {
1357                self.stack_get(stack, ValType::I32);
1358                self.instruction(I32Extend8S);
1359            }
1360            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1361        }
1362        match dst {
1363            Destination::Memory(mem) => self.i32_store8(mem),
1364            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1365            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1366        }
1367    }
1368
1369    fn translate_u16(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1370        // TODO: subtyping
1371        assert!(matches!(dst_ty, InterfaceType::U16));
1372        self.convert_u16_mask(src, dst, 0xffff);
1373    }
1374
1375    fn convert_u16_mask(&mut self, src: &Source<'_>, dst: &Destination<'_>, mask: u16) {
1376        self.push_dst_addr(dst);
1377        let mut needs_mask = true;
1378        match src {
1379            Source::Memory(mem) => {
1380                self.i32_load16u(mem);
1381                needs_mask = mask != 0xffff;
1382            }
1383            Source::Stack(stack) => {
1384                self.stack_get(stack, ValType::I32);
1385            }
1386            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1387        }
1388        if needs_mask {
1389            self.instruction(I32Const(i32::from(mask)));
1390            self.instruction(I32And);
1391        }
1392        match dst {
1393            Destination::Memory(mem) => self.i32_store16(mem),
1394            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1395            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1396        }
1397    }
1398
1399    fn translate_s16(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1400        // TODO: subtyping
1401        assert!(matches!(dst_ty, InterfaceType::S16));
1402        self.push_dst_addr(dst);
1403        match src {
1404            Source::Memory(mem) => self.i32_load16s(mem),
1405            Source::Stack(stack) => {
1406                self.stack_get(stack, ValType::I32);
1407                self.instruction(I32Extend16S);
1408            }
1409            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1410        }
1411        match dst {
1412            Destination::Memory(mem) => self.i32_store16(mem),
1413            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1414            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1415        }
1416    }
1417
1418    fn translate_u32(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1419        // TODO: subtyping
1420        assert!(matches!(dst_ty, InterfaceType::U32));
1421        self.convert_u32_mask(src, dst, 0xffffffff)
1422    }
1423
1424    fn convert_u32_mask(&mut self, src: &Source<'_>, dst: &Destination<'_>, mask: u32) {
1425        self.push_dst_addr(dst);
1426        match src {
1427            Source::Memory(mem) => self.i32_load(mem),
1428            Source::Stack(stack) => self.stack_get(stack, ValType::I32),
1429            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1430        }
1431        if mask != 0xffffffff {
1432            self.instruction(I32Const(mask as i32));
1433            self.instruction(I32And);
1434        }
1435        match dst {
1436            Destination::Memory(mem) => self.i32_store(mem),
1437            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1438            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1439        }
1440    }
1441
1442    fn translate_s32(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1443        // TODO: subtyping
1444        assert!(matches!(dst_ty, InterfaceType::S32));
1445        self.push_dst_addr(dst);
1446        match src {
1447            Source::Memory(mem) => self.i32_load(mem),
1448            Source::Stack(stack) => self.stack_get(stack, ValType::I32),
1449            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1450        }
1451        match dst {
1452            Destination::Memory(mem) => self.i32_store(mem),
1453            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1454            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1455        }
1456    }
1457
1458    fn translate_u64(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1459        // TODO: subtyping
1460        assert!(matches!(dst_ty, InterfaceType::U64));
1461        self.push_dst_addr(dst);
1462        match src {
1463            Source::Memory(mem) => self.i64_load(mem),
1464            Source::Stack(stack) => self.stack_get(stack, ValType::I64),
1465            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1466        }
1467        match dst {
1468            Destination::Memory(mem) => self.i64_store(mem),
1469            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I64),
1470            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1471        }
1472    }
1473
1474    fn translate_s64(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1475        // TODO: subtyping
1476        assert!(matches!(dst_ty, InterfaceType::S64));
1477        self.push_dst_addr(dst);
1478        match src {
1479            Source::Memory(mem) => self.i64_load(mem),
1480            Source::Stack(stack) => self.stack_get(stack, ValType::I64),
1481            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1482        }
1483        match dst {
1484            Destination::Memory(mem) => self.i64_store(mem),
1485            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I64),
1486            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1487        }
1488    }
1489
1490    fn translate_f32(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1491        // TODO: subtyping
1492        assert!(matches!(dst_ty, InterfaceType::Float32));
1493        self.push_dst_addr(dst);
1494        match src {
1495            Source::Memory(mem) => self.f32_load(mem),
1496            Source::Stack(stack) => self.stack_get(stack, ValType::F32),
1497            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1498        }
1499        match dst {
1500            Destination::Memory(mem) => self.f32_store(mem),
1501            Destination::Stack(stack, _) => self.stack_set(stack, ValType::F32),
1502            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1503        }
1504    }
1505
1506    fn translate_f64(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1507        // TODO: subtyping
1508        assert!(matches!(dst_ty, InterfaceType::Float64));
1509        self.push_dst_addr(dst);
1510        match src {
1511            Source::Memory(mem) => self.f64_load(mem),
1512            Source::Stack(stack) => self.stack_get(stack, ValType::F64),
1513            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1514        }
1515        match dst {
1516            Destination::Memory(mem) => self.f64_store(mem),
1517            Destination::Stack(stack, _) => self.stack_set(stack, ValType::F64),
1518            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1519        }
1520    }
1521
1522    fn translate_char(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1523        assert!(matches!(dst_ty, InterfaceType::Char));
1524        match src {
1525            Source::Memory(mem) => self.i32_load(mem),
1526            Source::Stack(stack) => self.stack_get(stack, ValType::I32),
1527            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1528        }
1529        let local = self.local_set_new_tmp(ValType::I32);
1530
1531        // This sequence is copied from the output of LLVM for:
1532        //
1533        //      pub extern "C" fn foo(x: u32) -> char {
1534        //          char::try_from(x)
1535        //              .unwrap_or_else(|_| std::arch::wasm32::unreachable())
1536        //      }
1537        //
1538        // Apparently this does what's required by the canonical ABI:
1539        //
1540        //    def i32_to_char(opts, i):
1541        //      trap_if(i >= 0x110000)
1542        //      trap_if(0xD800 <= i <= 0xDFFF)
1543        //      return chr(i)
1544        //
1545        // ... but I don't know how it works other than "well I trust LLVM"
1546        self.instruction(Block(BlockType::Empty));
1547        self.instruction(Block(BlockType::Empty));
1548        self.instruction(LocalGet(local.idx));
1549        self.instruction(I32Const(0xd800));
1550        self.instruction(I32Xor);
1551        self.instruction(I32Const(-0x110000));
1552        self.instruction(I32Add);
1553        self.instruction(I32Const(-0x10f800));
1554        self.instruction(I32LtU);
1555        self.instruction(BrIf(0));
1556        self.instruction(LocalGet(local.idx));
1557        self.instruction(I32Const(0x110000));
1558        self.instruction(I32Ne);
1559        self.instruction(BrIf(1));
1560        self.instruction(End);
1561        self.trap(Trap::InvalidChar);
1562        self.instruction(End);
1563
1564        self.push_dst_addr(dst);
1565        self.instruction(LocalGet(local.idx));
1566        match dst {
1567            Destination::Memory(mem) => {
1568                self.i32_store(mem);
1569            }
1570            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
1571            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1572        }
1573
1574        self.free_temp_local(local);
1575    }
1576
1577    fn translate_string(&mut self, src: &Source<'_>, dst_ty: &InterfaceType, dst: &Destination) {
1578        assert!(matches!(dst_ty, InterfaceType::String));
1579        let src_opts = src.opts();
1580        let dst_opts = dst.opts();
1581
1582        let src_mem_opts = match &src_opts.data_model {
1583            DataModel::Gc {} => todo!("CM+GC"),
1584            DataModel::LinearMemory(opts) => opts,
1585        };
1586        let dst_mem_opts = match &dst_opts.data_model {
1587            DataModel::Gc {} => todo!("CM+GC"),
1588            DataModel::LinearMemory(opts) => opts,
1589        };
1590
1591        // Load the pointer/length of this string into temporary locals. These
1592        // will be referenced a good deal so this just makes it easier to deal
1593        // with them consistently below rather than trying to reload from memory
1594        // for example.
1595        match src {
1596            Source::Stack(s) => {
1597                assert_eq!(s.locals.len(), 2);
1598                self.stack_get(&s.slice(0..1), src_mem_opts.ptr());
1599                self.stack_get(&s.slice(1..2), src_mem_opts.ptr());
1600            }
1601            Source::Memory(mem) => {
1602                self.ptr_load(mem);
1603                self.ptr_load(&mem.bump(src_mem_opts.ptr_size().into()));
1604            }
1605            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
1606        }
1607        let src_len = self.local_set_new_tmp(src_mem_opts.ptr());
1608        let src_ptr = self.local_set_new_tmp(src_mem_opts.ptr());
1609        let src_str = WasmString {
1610            ptr: src_ptr,
1611            len: src_len,
1612            opts: src_opts,
1613        };
1614
1615        let dst_str = match src_opts.string_encoding {
1616            StringEncoding::Utf8 => {
1617                self.validate_guest_pointer(
1618                    src_opts,
1619                    &src_str.ptr,
1620                    &AllocSize::Local(src_str.len.idx),
1621                    1,
1622                    Trap::StringOutOfBounds,
1623                );
1624                match dst_opts.string_encoding {
1625                    StringEncoding::Utf8 => {
1626                        self.string_copy(&src_str, FE::Utf8, dst_opts, FE::Utf8)
1627                    }
1628                    StringEncoding::Utf16 => self.string_utf8_to_utf16(&src_str, dst_opts),
1629                    StringEncoding::CompactUtf16 => {
1630                        self.string_to_compact(&src_str, FE::Utf8, dst_opts)
1631                    }
1632                }
1633            }
1634
1635            StringEncoding::Utf16 => {
1636                self.validate_guest_pointer(
1637                    src_opts,
1638                    &src_str.ptr,
1639                    &AllocSize::DoubleLocal(src_str.len.idx),
1640                    2,
1641                    Trap::StringOutOfBounds,
1642                );
1643                match dst_opts.string_encoding {
1644                    StringEncoding::Utf8 => {
1645                        self.string_deflate_to_utf8(&src_str, FE::Utf16, dst_opts)
1646                    }
1647                    StringEncoding::Utf16 => {
1648                        self.string_copy(&src_str, FE::Utf16, dst_opts, FE::Utf16)
1649                    }
1650                    StringEncoding::CompactUtf16 => {
1651                        self.string_to_compact(&src_str, FE::Utf16, dst_opts)
1652                    }
1653                }
1654            }
1655
1656            StringEncoding::CompactUtf16 => {
1657                // Test the tag big to see if this is a utf16 or a latin1 string
1658                // at runtime...
1659                self.instruction(LocalGet(src_str.len.idx));
1660                self.ptr_utf16_tag(src_mem_opts);
1661                self.ptr_and(src_mem_opts);
1662                self.ptr_if(src_mem_opts, BlockType::Empty);
1663
1664                // In the utf16 block unset the upper bit from the length local
1665                // so further calculations have the right value. Afterwards the
1666                // string transcode proceeds assuming utf16.
1667                self.instruction(LocalGet(src_str.len.idx));
1668                self.ptr_utf16_tag(src_mem_opts);
1669                self.ptr_xor(src_mem_opts);
1670                self.instruction(LocalSet(src_str.len.idx));
1671
1672                // Now that we dynamically know this is utf16 perform a
1673                // validation of the guest's pointer to ensure it's aligned and
1674                // in-bounds.
1675                self.validate_guest_pointer(
1676                    src_opts,
1677                    &src_str.ptr,
1678                    &AllocSize::DoubleLocal(src_str.len.idx),
1679                    2,
1680                    Trap::StringOutOfBounds,
1681                );
1682
1683                let s1 = match dst_opts.string_encoding {
1684                    StringEncoding::Utf8 => {
1685                        self.string_deflate_to_utf8(&src_str, FE::Utf16, dst_opts)
1686                    }
1687                    StringEncoding::Utf16 => {
1688                        self.string_copy(&src_str, FE::Utf16, dst_opts, FE::Utf16)
1689                    }
1690                    StringEncoding::CompactUtf16 => {
1691                        self.string_compact_utf16_to_compact(&src_str, dst_opts)
1692                    }
1693                };
1694
1695                self.instruction(Else);
1696
1697                // Now that we dynamically know this is latin1 perform the
1698                // same validation above, but with a different byte length.
1699                self.validate_guest_pointer(
1700                    src_opts,
1701                    &src_str.ptr,
1702                    &AllocSize::Local(src_str.len.idx),
1703                    2,
1704                    Trap::StringOutOfBounds,
1705                );
1706
1707                // In the latin1 block the `src_len` local is already the number
1708                // of code units, so the string transcoding is all that needs to
1709                // happen.
1710                let s2 = match dst_opts.string_encoding {
1711                    StringEncoding::Utf16 => {
1712                        self.string_copy(&src_str, FE::Latin1, dst_opts, FE::Utf16)
1713                    }
1714                    StringEncoding::Utf8 => {
1715                        self.string_deflate_to_utf8(&src_str, FE::Latin1, dst_opts)
1716                    }
1717                    StringEncoding::CompactUtf16 => {
1718                        self.string_copy(&src_str, FE::Latin1, dst_opts, FE::Latin1)
1719                    }
1720                };
1721                // Set our `s2` generated locals to the `s2` generated locals
1722                // as the resulting pointer of this transcode.
1723                self.instruction(LocalGet(s2.ptr.idx));
1724                self.instruction(LocalSet(s1.ptr.idx));
1725                self.instruction(LocalGet(s2.len.idx));
1726                self.instruction(LocalSet(s1.len.idx));
1727                self.instruction(End);
1728                self.free_temp_local(s2.ptr);
1729                self.free_temp_local(s2.len);
1730                s1
1731            }
1732        };
1733
1734        // Store the ptr/length in the desired destination
1735        match dst {
1736            Destination::Stack(s, _) => {
1737                self.instruction(LocalGet(dst_str.ptr.idx));
1738                self.stack_set(&s[..1], dst_mem_opts.ptr());
1739                self.instruction(LocalGet(dst_str.len.idx));
1740                self.stack_set(&s[1..], dst_mem_opts.ptr());
1741            }
1742            Destination::Memory(mem) => {
1743                self.instruction(LocalGet(mem.addr.idx));
1744                self.instruction(LocalGet(dst_str.ptr.idx));
1745                self.ptr_store(mem);
1746                self.instruction(LocalGet(mem.addr.idx));
1747                self.instruction(LocalGet(dst_str.len.idx));
1748                self.ptr_store(&mem.bump(dst_mem_opts.ptr_size().into()));
1749            }
1750            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
1751        }
1752
1753        self.free_temp_local(src_str.ptr);
1754        self.free_temp_local(src_str.len);
1755        self.free_temp_local(dst_str.ptr);
1756        self.free_temp_local(dst_str.len);
1757    }
1758
1759    /// Resets the hostcall fuel remaining for the strings in `tys` to the
1760    /// store's hostcall fuel, if there are any strings.
1761    ///
1762    /// Strings are the only values the host copies on behalf of an adapter;
1763    /// everything else is copied by the adapter's own wasm and charged as
1764    /// such.
1765    fn init_hostcall_fuel(&mut self, tys: &[InterfaceType]) {
1766        if !tys.iter().any(|ty| self.types.ty_contains_string(ty)) {
1767            return;
1768        }
1769        self.module.hostcall_fuel_global = true;
1770        let hostcall_fuel = self.module.import_hostcall_fuel();
1771        self.instruction(Call(hostcall_fuel.as_u32()));
1772        self.push_body(Body::HostcallFuelGlobalSet);
1773    }
1774
1775    /// Charges `src`'s code units at `enc`'s width against the remaining
1776    /// hostcall fuel before the host copies it, trapping if there isn't
1777    /// enough.
1778    fn consume_hostcall_fuel(&mut self, src: &WasmString<'_>, enc: FE) {
1779        self.instruction(LocalGet(src.len.idx));
1780        if src.len.ty == ValType::I32 {
1781            self.instruction(I64ExtendI32U);
1782        }
1783        if enc.width() > 1 {
1784            self.instruction(I64Const(i64::from(enc.width())));
1785            self.instruction(I64Mul);
1786        }
1787        let bytes = self.local_set_new_tmp(ValType::I64);
1788
1789        self.instruction(LocalGet(bytes.idx));
1790        self.push_body(Body::HostcallFuelGlobalGet);
1791        self.instruction(I64GtU);
1792        self.instruction(If(BlockType::Empty));
1793        self.trap(Trap::HostcallFuelExhausted);
1794        self.instruction(End);
1795
1796        self.push_body(Body::HostcallFuelGlobalGet);
1797        self.instruction(LocalGet(bytes.idx));
1798        self.instruction(I64Sub);
1799        self.push_body(Body::HostcallFuelGlobalSet);
1800
1801        self.free_temp_local(bytes);
1802    }
1803
1804    // Corresponding function for `store_string_copy` in the spec.
1805    //
1806    // This performs a transcoding of the string with a one-pass copy from
1807    // the `src` encoding to the `dst` encoding. This is only possible for
1808    // fixed encodings where the first allocation is guaranteed to be an
1809    // appropriate fit so it's not suitable for all encodings.
1810    //
1811    // Imported host transcoding functions here take the src/dst pointers as
1812    // well as the number of code units in the source (which always matches
1813    // the number of code units in the destination). There is no return
1814    // value from the transcode function since the encoding should always
1815    // work on the first pass.
1816    fn string_copy<'c>(
1817        &mut self,
1818        src: &WasmString<'_>,
1819        src_enc: FE,
1820        dst_opts: &'c Options,
1821        dst_enc: FE,
1822    ) -> WasmString<'c> {
1823        assert!(dst_enc.width() >= src_enc.width());
1824
1825        // Validate the string's length is in-bounds. Note that `dst_enc` is
1826        // specifically used here since it's the larger of the two encodings.
1827        // The code-unit size of the src/dst is going to be the same so this is
1828        // the encoding to validate.
1829        self.validate_string_length(src, dst_enc);
1830
1831        let src_mem_opts = {
1832            match &src.opts.data_model {
1833                DataModel::Gc {} => todo!("CM+GC"),
1834                DataModel::LinearMemory(opts) => opts,
1835            }
1836        };
1837        let dst_mem_opts = {
1838            match &dst_opts.data_model {
1839                DataModel::Gc {} => todo!("CM+GC"),
1840                DataModel::LinearMemory(opts) => opts,
1841            }
1842        };
1843
1844        // Convert the source code units length to the destination byte
1845        // length type.
1846        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
1847        let dst_len = self.local_tee_new_tmp(dst_mem_opts.ptr());
1848        if dst_enc.width() > 1 {
1849            assert_eq!(dst_enc.width(), 2);
1850            self.ptr_uconst(dst_mem_opts, 1);
1851            self.ptr_shl(dst_mem_opts);
1852        }
1853        let dst_byte_len = self.local_set_new_tmp(dst_mem_opts.ptr());
1854
1855        // Allocate space in the destination using the calculated byte
1856        // length.
1857        let dst = {
1858            let dst_mem = self.malloc(
1859                dst_opts,
1860                AllocSize::Local(dst_byte_len.idx),
1861                dst_enc.align().into(),
1862                Trap::StringOutOfBounds,
1863            );
1864            WasmString {
1865                ptr: dst_mem.addr,
1866                len: dst_len,
1867                opts: dst_opts,
1868            }
1869        };
1870
1871        // If the validations pass then the host `transcode` intrinsic
1872        // is invoked. This will either raise a trap or otherwise succeed
1873        // in which case we're done.
1874        let op = if src_enc == dst_enc {
1875            Transcode::Copy(src_enc)
1876        } else {
1877            assert_eq!(src_enc, FE::Latin1);
1878            assert_eq!(dst_enc, FE::Utf16);
1879            Transcode::Latin1ToUtf16
1880        };
1881        let transcode = self.transcoder(src, &dst, op);
1882        self.instruction(LocalGet(src.ptr.idx));
1883        self.instruction(LocalGet(src.len.idx));
1884        self.instruction(LocalGet(dst.ptr.idx));
1885        self.instruction(Call(transcode.as_u32()));
1886
1887        self.free_temp_local(dst_byte_len);
1888
1889        dst
1890    }
1891
1892    // Corresponding function for `store_string_to_utf8` in the spec.
1893    //
1894    // This translation works by possibly performing a number of
1895    // reallocations. First a buffer of size input-code-units is used to try
1896    // to get the transcoding correct on the first try. If that fails the
1897    // maximum worst-case size is used and then that is resized down if it's
1898    // too large.
1899    //
1900    // The host transcoding function imported here will receive src ptr/len
1901    // and dst ptr/len and return how many code units were consumed on both
1902    // sides. The amount of code units consumed in the source dictates which
1903    // branches are taken in this conversion.
1904    fn string_deflate_to_utf8<'c>(
1905        &mut self,
1906        src: &WasmString<'_>,
1907        src_enc: FE,
1908        dst_opts: &'c Options,
1909    ) -> WasmString<'c> {
1910        let src_mem_opts = match &src.opts.data_model {
1911            DataModel::Gc {} => todo!("CM+GC"),
1912            DataModel::LinearMemory(opts) => opts,
1913        };
1914        let dst_mem_opts = match &dst_opts.data_model {
1915            DataModel::Gc {} => todo!("CM+GC"),
1916            DataModel::LinearMemory(opts) => opts,
1917        };
1918
1919        self.validate_string_length(src, src_enc);
1920
1921        // Optimistically assume that the code unit length of the source is
1922        // all that's needed in the destination. Perform that allocation
1923        // here and proceed to transcoding below.
1924        self.convert_src_len_to_dst(
1925            src.len.idx,
1926            src.opts.data_model.unwrap_memory().ptr(),
1927            dst_opts.data_model.unwrap_memory().ptr(),
1928        );
1929        let dst_len = self.local_tee_new_tmp(dst_opts.data_model.unwrap_memory().ptr());
1930        let dst_byte_len = self.local_set_new_tmp(dst_opts.data_model.unwrap_memory().ptr());
1931
1932        let dst = {
1933            let dst_mem = self.malloc(
1934                dst_opts,
1935                AllocSize::Local(dst_byte_len.idx),
1936                1,
1937                Trap::StringOutOfBounds,
1938            );
1939            WasmString {
1940                ptr: dst_mem.addr,
1941                len: dst_len,
1942                opts: dst_opts,
1943            }
1944        };
1945
1946        // Perform the initial transcode
1947        let op = match src_enc {
1948            FE::Latin1 => Transcode::Latin1ToUtf8,
1949            FE::Utf16 => Transcode::Utf16ToUtf8,
1950            FE::Utf8 => unreachable!(),
1951        };
1952        let transcode = self.transcoder(src, &dst, op);
1953        self.instruction(LocalGet(src.ptr.idx));
1954        self.instruction(LocalGet(src.len.idx));
1955        self.instruction(LocalGet(dst.ptr.idx));
1956        self.instruction(LocalGet(dst_byte_len.idx));
1957        self.instruction(I32Const(1)); // first_pass = true
1958        self.instruction(Call(transcode.as_u32()));
1959        self.instruction(LocalSet(dst.len.idx));
1960        let src_len_tmp = self.local_set_new_tmp(src.opts.data_model.unwrap_memory().ptr());
1961
1962        // Test if the source was entirely transcoded by comparing
1963        // `src_len_tmp`, the number of code units transcoded from the
1964        // source, with `src_len`, the original number of code units.
1965        self.instruction(LocalGet(src_len_tmp.idx));
1966        self.instruction(LocalGet(src.len.idx));
1967        self.ptr_ne(src_mem_opts);
1968        self.instruction(If(BlockType::Empty));
1969
1970        // Check that the worst-case byte size fits within the maximum size of
1971        // strings.
1972        let factor = match src_enc {
1973            FE::Latin1 => 2,
1974            FE::Utf16 => 3,
1975            _ => unreachable!(),
1976        };
1977        self.validate_string_length_u8(src, factor);
1978        self.convert_src_len_to_dst(
1979            src.len.idx,
1980            src.opts.data_model.unwrap_memory().ptr(),
1981            dst_opts.data_model.unwrap_memory().ptr(),
1982        );
1983        self.ptr_uconst(dst_mem_opts, factor.into());
1984        self.ptr_mul(dst_mem_opts);
1985        let new_byte_len = self.local_set_new_tmp(dst_mem_opts.ptr());
1986
1987        // Do a worst-case reallocation is performed to grow `dst_mem`.
1988        // Afterwards update our `dst_byte_len` local to reflect the new byte
1989        // length.
1990        self.realloc(
1991            dst_opts,
1992            &dst.ptr,
1993            AllocSize::Local(dst_byte_len.idx),
1994            AllocSize::Local(new_byte_len.idx),
1995            1,
1996            Trap::StringOutOfBounds,
1997        );
1998        self.instruction(LocalGet(new_byte_len.idx));
1999        self.instruction(LocalSet(dst_byte_len.idx));
2000        self.free_temp_local(new_byte_len);
2001
2002        // Perform another round of transcoding that should be guaranteed
2003        // to succeed. Note that all the parameters here are offset by the
2004        // results of the first transcoding to only perform the remaining
2005        // transcode on the final units.
2006        self.instruction(LocalGet(src.ptr.idx));
2007        self.instruction(LocalGet(src_len_tmp.idx));
2008        if let FE::Utf16 = src_enc {
2009            self.ptr_uconst(src_mem_opts, 1);
2010            self.ptr_shl(src_mem_opts);
2011        }
2012        self.ptr_add(src_mem_opts);
2013        self.instruction(LocalGet(src.len.idx));
2014        self.instruction(LocalGet(src_len_tmp.idx));
2015        self.ptr_sub(src_mem_opts);
2016        self.instruction(LocalGet(dst.ptr.idx));
2017        self.instruction(LocalGet(dst.len.idx));
2018        self.ptr_add(dst_mem_opts);
2019        self.instruction(LocalGet(dst_byte_len.idx));
2020        self.instruction(LocalGet(dst.len.idx));
2021        self.ptr_sub(dst_mem_opts);
2022        self.instruction(I32Const(0)); // first_pass = false
2023        self.instruction(Call(transcode.as_u32()));
2024
2025        // Add the second result, the amount of destination units encoded,
2026        // to `dst_len` so it's an accurate reflection of the final size of
2027        // the destination buffer.
2028        self.instruction(LocalGet(dst.len.idx));
2029        self.ptr_add(dst_mem_opts);
2030        self.instruction(LocalSet(dst.len.idx));
2031
2032        // In debug mode verify the first result consumed the entire string,
2033        // otherwise simply discard it.
2034        if self.module.tunables.debug_adapter_modules {
2035            self.instruction(LocalGet(src.len.idx));
2036            self.instruction(LocalGet(src_len_tmp.idx));
2037            self.ptr_sub(src_mem_opts);
2038            self.ptr_ne(src_mem_opts);
2039            self.instruction(If(BlockType::Empty));
2040            self.trap(Trap::DebugAssertStringEncodingFinished);
2041            self.instruction(End);
2042        } else {
2043            self.instruction(Drop);
2044        }
2045
2046        // Perform a downsizing if the worst-case size was too large
2047        self.instruction(LocalGet(dst.len.idx));
2048        self.instruction(LocalGet(dst_byte_len.idx));
2049        self.ptr_ne(dst_mem_opts);
2050        self.instruction(If(BlockType::Empty));
2051        self.realloc(
2052            dst_opts,
2053            &dst.ptr,
2054            AllocSize::Local(dst_byte_len.idx),
2055            AllocSize::Local(dst.len.idx),
2056            1,
2057            Trap::StringOutOfBounds,
2058        );
2059        self.instruction(End);
2060
2061        // If the first transcode was enough then assert that the returned
2062        // amount of destination items written equals the byte size.
2063        if self.module.tunables.debug_adapter_modules {
2064            self.instruction(Else);
2065
2066            self.instruction(LocalGet(dst.len.idx));
2067            self.instruction(LocalGet(dst_byte_len.idx));
2068            self.ptr_ne(dst_mem_opts);
2069            self.instruction(If(BlockType::Empty));
2070            self.trap(Trap::DebugAssertStringEncodingFinished);
2071            self.instruction(End);
2072        }
2073
2074        self.instruction(End); // end of "first transcode not enough"
2075
2076        self.free_temp_local(src_len_tmp);
2077        self.free_temp_local(dst_byte_len);
2078
2079        dst
2080    }
2081
2082    // Corresponds to the `store_utf8_to_utf16` function in the spec.
2083    //
2084    // When converting utf-8 to utf-16 a pessimistic allocation is
2085    // done which is twice the byte length of the utf-8 string.
2086    // The host then transcodes and returns how many code units were
2087    // actually used during the transcoding and if it's beneath the
2088    // pessimistic maximum then the buffer is reallocated down to
2089    // a smaller amount.
2090    //
2091    // The host-imported transcoding function takes the src/dst pointer as
2092    // well as the code unit size of both the source and destination. The
2093    // destination should always be big enough to hold the result of the
2094    // transcode and so the result of the host function is how many code
2095    // units were written to the destination.
2096    fn string_utf8_to_utf16<'c>(
2097        &mut self,
2098        src: &WasmString<'_>,
2099        dst_opts: &'c Options,
2100    ) -> WasmString<'c> {
2101        let src_mem_opts = match &src.opts.data_model {
2102            DataModel::Gc {} => todo!("CM+GC"),
2103            DataModel::LinearMemory(opts) => opts,
2104        };
2105        let dst_mem_opts = match &dst_opts.data_model {
2106            DataModel::Gc {} => todo!("CM+GC"),
2107            DataModel::LinearMemory(opts) => opts,
2108        };
2109
2110        self.validate_string_length(src, FE::Utf16);
2111        self.convert_src_len_to_dst(
2112            src.len.idx,
2113            src_mem_opts.ptr(),
2114            dst_opts.data_model.unwrap_memory().ptr(),
2115        );
2116        let dst_len = self.local_tee_new_tmp(dst_opts.data_model.unwrap_memory().ptr());
2117        self.ptr_uconst(dst_mem_opts, 1);
2118        self.ptr_shl(dst_mem_opts);
2119        let dst_byte_len = self.local_set_new_tmp(dst_opts.data_model.unwrap_memory().ptr());
2120        let dst = {
2121            let dst_mem = self.malloc(
2122                dst_opts,
2123                AllocSize::Local(dst_byte_len.idx),
2124                2,
2125                Trap::StringOutOfBounds,
2126            );
2127            WasmString {
2128                ptr: dst_mem.addr,
2129                len: dst_len,
2130                opts: dst_opts,
2131            }
2132        };
2133
2134        let transcode = self.transcoder(src, &dst, Transcode::Utf8ToUtf16);
2135        self.instruction(LocalGet(src.ptr.idx));
2136        self.instruction(LocalGet(src.len.idx));
2137        self.instruction(LocalGet(dst.ptr.idx));
2138        self.instruction(Call(transcode.as_u32()));
2139        self.instruction(LocalSet(dst.len.idx));
2140
2141        // If the number of code units returned by transcode is not
2142        // equal to the original number of code units then
2143        // the buffer must be shrunk.
2144        //
2145        // Note that the byte length of the final allocation we
2146        // want is twice the code unit length returned by the
2147        // transcoding function.
2148        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2149        self.instruction(LocalGet(dst.len.idx));
2150        self.ptr_ne(dst_mem_opts);
2151        self.instruction(If(BlockType::Empty));
2152        self.realloc(
2153            dst.opts,
2154            &dst.ptr,
2155            AllocSize::Local(dst_byte_len.idx),
2156            AllocSize::DoubleLocal(dst.len.idx),
2157            2,
2158            Trap::StringOutOfBounds,
2159        );
2160        self.instruction(End); // end of shrink-to-fit
2161
2162        self.free_temp_local(dst_byte_len);
2163
2164        dst
2165    }
2166
2167    // Corresponds to `store_probably_utf16_to_latin1_or_utf16` in the spec.
2168    //
2169    // This will try to transcode the input utf16 string to utf16 in the
2170    // destination. If utf16 isn't needed though and latin1 could be used
2171    // then that's used instead and a reallocation to downsize occurs
2172    // afterwards.
2173    //
2174    // The host transcode function here will take the src/dst pointers as
2175    // well as src length. The destination byte length is twice the src code
2176    // unit length. The return value is the tagged length of the returned
2177    // string. If the upper bit is set then utf16 was used and the
2178    // conversion is done. If the upper bit is not set then latin1 was used
2179    // and a downsizing needs to happen.
2180    fn string_compact_utf16_to_compact<'c>(
2181        &mut self,
2182        src: &WasmString<'_>,
2183        dst_opts: &'c Options,
2184    ) -> WasmString<'c> {
2185        let src_mem_opts = match &src.opts.data_model {
2186            DataModel::Gc {} => todo!("CM+GC"),
2187            DataModel::LinearMemory(opts) => opts,
2188        };
2189        let dst_mem_opts = match &dst_opts.data_model {
2190            DataModel::Gc {} => todo!("CM+GC"),
2191            DataModel::LinearMemory(opts) => opts,
2192        };
2193
2194        self.validate_string_length(src, FE::Utf16);
2195        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2196        let dst_len = self.local_tee_new_tmp(dst_mem_opts.ptr());
2197        self.ptr_uconst(dst_mem_opts, 1);
2198        self.ptr_shl(dst_mem_opts);
2199        let dst_byte_len = self.local_set_new_tmp(dst_mem_opts.ptr());
2200        let dst = {
2201            let dst_mem = self.malloc(
2202                dst_opts,
2203                AllocSize::Local(dst_byte_len.idx),
2204                2,
2205                Trap::StringOutOfBounds,
2206            );
2207            WasmString {
2208                ptr: dst_mem.addr,
2209                len: dst_len,
2210                opts: dst_opts,
2211            }
2212        };
2213
2214        self.convert_src_len_to_dst(
2215            dst_byte_len.idx,
2216            dst.opts.data_model.unwrap_memory().ptr(),
2217            src_mem_opts.ptr(),
2218        );
2219        let src_byte_len = self.local_set_new_tmp(src_mem_opts.ptr());
2220
2221        let transcode = self.transcoder(src, &dst, Transcode::Utf16ToCompactProbablyUtf16);
2222        self.instruction(LocalGet(src.ptr.idx));
2223        self.instruction(LocalGet(src.len.idx));
2224        self.instruction(LocalGet(dst.ptr.idx));
2225        self.instruction(Call(transcode.as_u32()));
2226        self.instruction(LocalSet(dst.len.idx));
2227
2228        // Assert that the untagged code unit length is the same as the
2229        // source code unit length.
2230        if self.module.tunables.debug_adapter_modules {
2231            self.instruction(LocalGet(dst.len.idx));
2232            self.ptr_utf16_untag_mask(dst_mem_opts);
2233            self.ptr_and(dst_mem_opts);
2234            self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2235            self.ptr_ne(dst_mem_opts);
2236            self.instruction(If(BlockType::Empty));
2237            self.trap(Trap::DebugAssertEqualCodeUnits);
2238            self.instruction(End);
2239        }
2240
2241        // If the utf16 tag is set then utf16 was used and the destination
2242        // should be appropriately sized. Bail out of the "is this string
2243        // empty" block and fall through otherwise to resizing.
2244        self.instruction(LocalGet(dst.len.idx));
2245        self.ptr_utf16_tag(dst_mem_opts);
2246        self.ptr_and(dst_mem_opts);
2247        self.ptr_br_if(dst_mem_opts, 0);
2248
2249        // Here `realloc` is used to downsize the string
2250        self.realloc(
2251            dst.opts,
2252            &dst.ptr,
2253            AllocSize::Local(dst_byte_len.idx),
2254            AllocSize::Local(dst.len.idx),
2255            2,
2256            Trap::StringOutOfBounds,
2257        );
2258
2259        self.free_temp_local(dst_byte_len);
2260        self.free_temp_local(src_byte_len);
2261
2262        dst
2263    }
2264
2265    // Corresponds to `store_string_to_latin1_or_utf16` in the spec.
2266    //
2267    // This will attempt a first pass of transcoding to latin1 and on
2268    // failure a larger buffer is allocated for utf16 and then utf16 is
2269    // encoded in-place into the buffer. After either latin1 or utf16 the
2270    // buffer is then resized to fit the final string allocation.
2271    fn string_to_compact<'c>(
2272        &mut self,
2273        src: &WasmString<'_>,
2274        src_enc: FE,
2275        dst_opts: &'c Options,
2276    ) -> WasmString<'c> {
2277        let src_mem_opts = match &src.opts.data_model {
2278            DataModel::Gc {} => todo!("CM+GC"),
2279            DataModel::LinearMemory(opts) => opts,
2280        };
2281        let dst_mem_opts = match &dst_opts.data_model {
2282            DataModel::Gc {} => todo!("CM+GC"),
2283            DataModel::LinearMemory(opts) => opts,
2284        };
2285
2286        self.validate_string_length(src, src_enc);
2287
2288        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2289        let dst_len = self.local_tee_new_tmp(dst_mem_opts.ptr());
2290        let dst_byte_len = self.local_set_new_tmp(dst_mem_opts.ptr());
2291        let dst = {
2292            let dst_mem = self.malloc(
2293                dst_opts,
2294                AllocSize::Local(dst_byte_len.idx),
2295                2,
2296                Trap::StringOutOfBounds,
2297            );
2298            WasmString {
2299                ptr: dst_mem.addr,
2300                len: dst_len,
2301                opts: dst_opts,
2302            }
2303        };
2304
2305        // Perform the initial latin1 transcode. This returns the number of
2306        // source code units consumed and the number of destination code
2307        // units (bytes) written.
2308        let (latin1, utf16) = match src_enc {
2309            FE::Utf8 => (Transcode::Utf8ToLatin1, Transcode::Utf8ToCompactUtf16),
2310            FE::Utf16 => (Transcode::Utf16ToLatin1, Transcode::Utf16ToCompactUtf16),
2311            FE::Latin1 => unreachable!(),
2312        };
2313        let transcode_latin1 = self.transcoder(src, &dst, latin1);
2314        let transcode_utf16 = self.transcoder(src, &dst, utf16);
2315        self.instruction(LocalGet(src.ptr.idx));
2316        self.instruction(LocalGet(src.len.idx));
2317        self.instruction(LocalGet(dst.ptr.idx));
2318        self.instruction(Call(transcode_latin1.as_u32()));
2319        self.instruction(LocalSet(dst.len.idx));
2320        let src_len_tmp = self.local_set_new_tmp(src_mem_opts.ptr());
2321
2322        // If the source was entirely consumed then the transcode completed
2323        // and all that's necessary is to optionally shrink the buffer.
2324        self.instruction(LocalGet(src_len_tmp.idx));
2325        self.instruction(LocalGet(src.len.idx));
2326        self.ptr_eq(src_mem_opts);
2327        self.instruction(If(BlockType::Empty)); // if latin1-or-utf16 block
2328
2329        // Test if the original byte length of the allocation is the same as
2330        // the number of written bytes, and if not then shrink the buffer
2331        // with a call to `realloc`.
2332        self.instruction(LocalGet(dst_byte_len.idx));
2333        self.instruction(LocalGet(dst.len.idx));
2334        self.ptr_ne(dst_mem_opts);
2335        self.instruction(If(BlockType::Empty));
2336        self.realloc(
2337            dst.opts,
2338            &dst.ptr,
2339            AllocSize::Local(dst_byte_len.idx),
2340            AllocSize::Local(dst.len.idx),
2341            2,
2342            Trap::StringOutOfBounds,
2343        );
2344        self.instruction(End);
2345
2346        // In this block the latin1 encoding failed. The host transcode
2347        // returned how many units were consumed from the source and how
2348        // many bytes were written to the destination. Here the buffer is
2349        // inflated and sized and the second utf16 intrinsic is invoked to
2350        // perform the final inflation.
2351        self.instruction(Else); // else latin1-or-utf16 block
2352
2353        // For utf8 validate that the inflated size is still within bounds.
2354        if src_enc.width() == 1 {
2355            self.validate_string_length_u8(src, 2);
2356        }
2357
2358        // Reallocate the buffer with twice the source code units in byte
2359        // size.
2360        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2361        self.ptr_uconst(dst_mem_opts, 1);
2362        self.ptr_shl(dst_mem_opts);
2363        let new_byte_len = self.local_set_new_tmp(dst_mem_opts.ptr());
2364        self.realloc(
2365            dst.opts,
2366            &dst.ptr,
2367            AllocSize::Local(dst_byte_len.idx),
2368            AllocSize::Local(new_byte_len.idx),
2369            2,
2370            Trap::StringOutOfBounds,
2371        );
2372        self.instruction(LocalGet(new_byte_len.idx));
2373        self.instruction(LocalSet(dst_byte_len.idx));
2374        self.free_temp_local(new_byte_len);
2375
2376        // Call the host utf16 transcoding function. This will inflate the
2377        // prior latin1 bytes and then encode the rest of the source string
2378        // as utf16 into the remaining space in the destination buffer.
2379        self.instruction(LocalGet(src.ptr.idx));
2380        self.instruction(LocalGet(src_len_tmp.idx));
2381        if let FE::Utf16 = src_enc {
2382            self.ptr_uconst(src_mem_opts, 1);
2383            self.ptr_shl(src_mem_opts);
2384        }
2385        self.ptr_add(src_mem_opts);
2386        self.instruction(LocalGet(src.len.idx));
2387        self.instruction(LocalGet(src_len_tmp.idx));
2388        self.ptr_sub(src_mem_opts);
2389        self.instruction(LocalGet(dst.ptr.idx));
2390        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2391        self.instruction(LocalGet(dst.len.idx));
2392        self.instruction(Call(transcode_utf16.as_u32()));
2393        self.instruction(LocalSet(dst.len.idx));
2394
2395        // If the returned number of code units written to the destination
2396        // is not equal to the size of the allocation then the allocation is
2397        // resized down to the appropriate size.
2398        //
2399        // Note that the byte size desired is `2*dst_len` and the current
2400        // byte buffer size is `2*src_len` so the `2` factor isn't checked
2401        // here, just the lengths.
2402        self.instruction(LocalGet(dst.len.idx));
2403        self.convert_src_len_to_dst(src.len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2404        self.ptr_ne(dst_mem_opts);
2405        self.instruction(If(BlockType::Empty));
2406        self.realloc(
2407            dst.opts,
2408            &dst.ptr,
2409            AllocSize::Local(dst_byte_len.idx),
2410            AllocSize::DoubleLocal(dst.len.idx),
2411            2,
2412            Trap::StringOutOfBounds,
2413        );
2414        self.instruction(End);
2415
2416        // Tag the returned pointer as utf16
2417        self.instruction(LocalGet(dst.len.idx));
2418        self.ptr_utf16_tag(dst_mem_opts);
2419        self.ptr_or(dst_mem_opts);
2420        self.instruction(LocalSet(dst.len.idx));
2421
2422        self.instruction(End); // end latin1-or-utf16 block
2423
2424        self.free_temp_local(src_len_tmp);
2425        self.free_temp_local(dst_byte_len);
2426
2427        dst
2428    }
2429
2430    fn validate_string_length(&mut self, src: &WasmString<'_>, dst: FE) {
2431        self.validate_string_length_u8(src, dst.width());
2432        self.consume_hostcall_fuel(src, dst);
2433    }
2434
2435    fn validate_string_length_u8(&mut self, s: &WasmString<'_>, dst: u8) {
2436        let mem_opts = match &s.opts.data_model {
2437            DataModel::Gc {} => todo!("CM+GC"),
2438            DataModel::LinearMemory(opts) => opts,
2439        };
2440
2441        // Check to see if the source byte length is out of bounds in
2442        // which case a trap is generated.
2443        self.instruction(LocalGet(s.len.idx));
2444        let max = MAX_STRING_BYTE_LENGTH / u32::from(dst);
2445        self.ptr_uconst(mem_opts, max);
2446        self.ptr_gt_u(mem_opts);
2447        self.instruction(If(BlockType::Empty));
2448        self.trap(Trap::StringOutOfBounds);
2449        self.instruction(End);
2450    }
2451
2452    fn transcoder(
2453        &mut self,
2454        src: &WasmString<'_>,
2455        dst: &WasmString<'_>,
2456        op: Transcode,
2457    ) -> FuncIndex {
2458        match (src.opts.data_model, dst.opts.data_model) {
2459            (DataModel::Gc {}, _) | (_, DataModel::Gc {}) => {
2460                todo!("CM+GC")
2461            }
2462            (
2463                DataModel::LinearMemory(LinearMemoryOptions {
2464                    memory: Some((src_mem, src_ty)),
2465                    realloc: _,
2466                }),
2467                DataModel::LinearMemory(LinearMemoryOptions {
2468                    memory: Some((dst_mem, dst_ty)),
2469                    realloc: _,
2470                }),
2471            ) => self.module.import_transcoder(Transcoder {
2472                from_memory: src_mem,
2473                from_memory64: src_ty.idx_type == IndexType::I64,
2474                to_memory: dst_mem,
2475                to_memory64: dst_ty.idx_type == IndexType::I64,
2476                op,
2477            }),
2478            (DataModel::LinearMemory(LinearMemoryOptions { memory: None, .. }), _)
2479            | (_, DataModel::LinearMemory(LinearMemoryOptions { memory: None, .. })) => {
2480                unreachable!()
2481            }
2482        }
2483    }
2484
2485    /// Shared preamble for translating list-like sequences (lists and maps).
2486    ///
2487    /// Emits: load ptr/len from source, compute byte lengths, malloc
2488    /// destination, validate bounds, and if element sizes are non-zero opens
2489    /// Block + Loop and initializes iteration locals.
2490    ///
2491    /// Returns a `SequenceTranslation` that the caller uses to emit the
2492    /// loop body before calling `end_translate_sequence`.
2493    fn begin_translate_sequence<'c>(
2494        &mut self,
2495        src: &Source<'c>,
2496        dst: &Destination<'c>,
2497        src_element_size: u32,
2498        src_element_align: u32,
2499        dst_element_size: u32,
2500        dst_element_align: u32,
2501    ) -> SequenceTranslation<'c> {
2502        let src_mem_opts = match &src.opts().data_model {
2503            DataModel::Gc {} => todo!("CM+GC"),
2504            DataModel::LinearMemory(opts) => opts,
2505        };
2506        let dst_mem_opts = match &dst.opts().data_model {
2507            DataModel::Gc {} => todo!("CM+GC"),
2508            DataModel::LinearMemory(opts) => opts,
2509        };
2510
2511        let src_opts = src.opts();
2512        let dst_opts = dst.opts();
2513
2514        // Load the pointer/length of this sequence into temporary locals.
2515        // These will be referenced a good deal so this just makes it easier
2516        // to deal with them consistently below rather than trying to reload
2517        // from memory for example.
2518        match src {
2519            Source::Stack(s) => {
2520                assert_eq!(s.locals.len(), 2);
2521                self.stack_get(&s.slice(0..1), src_mem_opts.ptr());
2522                self.stack_get(&s.slice(1..2), src_mem_opts.ptr());
2523            }
2524            Source::Memory(mem) => {
2525                self.ptr_load(mem);
2526                self.ptr_load(&mem.bump(src_mem_opts.ptr_size().into()));
2527            }
2528            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
2529        }
2530        let src_len = self.local_set_new_tmp(src_mem_opts.ptr());
2531        let src_ptr = self.local_set_new_tmp(src_mem_opts.ptr());
2532
2533        // Calculate the source/destination byte lengths into unique locals.
2534        let src_byte_len =
2535            self.calculate_list_byte_len(src_mem_opts, src_len.idx, src_element_size);
2536        let dst_byte_len = if src_element_size == dst_element_size {
2537            self.convert_src_len_to_dst(src_byte_len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2538            self.local_set_new_tmp(dst_mem_opts.ptr())
2539        } else if src_mem_opts.ptr() == dst_mem_opts.ptr() {
2540            self.calculate_list_byte_len(dst_mem_opts, src_len.idx, dst_element_size)
2541        } else {
2542            self.convert_src_len_to_dst(src_len.idx, src_mem_opts.ptr(), dst_mem_opts.ptr());
2543            let tmp = self.local_set_new_tmp(dst_mem_opts.ptr());
2544            let ret = self.calculate_list_byte_len(dst_mem_opts, tmp.idx, dst_element_size);
2545            self.free_temp_local(tmp);
2546            ret
2547        };
2548
2549        // Create a `Memory` operand which will internally assert that the
2550        // `src_ptr` value is properly aligned.
2551        let src_mem = self.memory_operand(
2552            src_opts,
2553            src_ptr,
2554            AllocSize::Local(src_byte_len.idx),
2555            src_element_align,
2556            Trap::ListOutOfBounds,
2557        );
2558
2559        // Here `realloc` is invoked (in a `malloc`-like fashion) to allocate
2560        // space for the sequence in the destination memory. This will also
2561        // internally insert checks that the returned pointer is aligned
2562        // correctly for the destination.
2563        let dst_mem = self.malloc(
2564            dst_opts,
2565            AllocSize::Local(dst_byte_len.idx),
2566            dst_element_align,
2567            Trap::ListOutOfBounds,
2568        );
2569
2570        self.free_temp_local(src_byte_len);
2571        self.free_temp_local(dst_byte_len);
2572
2573        // If both element sizes are 0 then there's nothing to copy so the
2574        // loop is skipped entirely. Otherwise open a Block (for early exit
2575        // on zero-length) and a Loop for the per-element iteration.
2576        let loop_state = if src_element_size > 0 || dst_element_size > 0 {
2577            self.instruction(Block(BlockType::Empty));
2578
2579            // Set the `remaining` local and only continue if it's > 0.
2580            self.instruction(LocalGet(src_len.idx));
2581            let remaining = self.local_tee_new_tmp(src_mem_opts.ptr());
2582            self.ptr_eqz(src_mem_opts);
2583            self.instruction(BrIf(0));
2584
2585            // Initialize the two iteration pointers to their starting values.
2586            self.instruction(LocalGet(src_mem.addr.idx));
2587            let cur_src_ptr = self.local_set_new_tmp(src_mem_opts.ptr());
2588            self.instruction(LocalGet(dst_mem.addr.idx));
2589            let cur_dst_ptr = self.local_set_new_tmp(dst_mem_opts.ptr());
2590
2591            self.instruction(Loop(BlockType::Empty));
2592
2593            Some(SequenceLoopState {
2594                remaining,
2595                cur_src_ptr,
2596                cur_dst_ptr,
2597            })
2598        } else {
2599            None
2600        };
2601
2602        SequenceTranslation {
2603            src_len,
2604            src_mem,
2605            dst_mem,
2606            src_opts,
2607            dst_opts,
2608            src_mem_opts,
2609            dst_mem_opts,
2610            loop_state,
2611        }
2612    }
2613
2614    /// Shared epilogue for translating list-like sequences.
2615    ///
2616    /// If a loop was opened, emits: decrement remaining, BrIf to loop
2617    /// head, End loop, End block, and frees iteration locals. Then stores
2618    /// the ptr/len pair into the destination and frees all temporaries.
2619    fn end_translate_sequence(&mut self, seq: SequenceTranslation<'_>, dst: &Destination) {
2620        if let Some(loop_state) = seq.loop_state {
2621            // Update the remaining count, falling through to break out if
2622            // it's zero now.
2623            self.instruction(LocalGet(loop_state.remaining.idx));
2624            self.ptr_iconst(seq.src_mem_opts, -1);
2625            self.ptr_add(seq.src_mem_opts);
2626            self.instruction(LocalTee(loop_state.remaining.idx));
2627            self.ptr_br_if(seq.src_mem_opts, 0);
2628            self.instruction(End); // end of loop
2629            self.instruction(End); // end of block
2630
2631            self.free_temp_local(loop_state.cur_dst_ptr);
2632            self.free_temp_local(loop_state.cur_src_ptr);
2633            self.free_temp_local(loop_state.remaining);
2634        }
2635
2636        // Store the ptr/length in the desired destination.
2637        match dst {
2638            Destination::Stack(s, _) => {
2639                self.instruction(LocalGet(seq.dst_mem.addr.idx));
2640                self.stack_set(&s[..1], seq.dst_mem_opts.ptr());
2641                self.convert_src_len_to_dst(
2642                    seq.src_len.idx,
2643                    seq.src_mem_opts.ptr(),
2644                    seq.dst_mem_opts.ptr(),
2645                );
2646                self.stack_set(&s[1..], seq.dst_mem_opts.ptr());
2647            }
2648            Destination::Memory(mem) => {
2649                self.instruction(LocalGet(mem.addr.idx));
2650                self.instruction(LocalGet(seq.dst_mem.addr.idx));
2651                self.ptr_store(mem);
2652                self.instruction(LocalGet(mem.addr.idx));
2653                self.convert_src_len_to_dst(
2654                    seq.src_len.idx,
2655                    seq.src_mem_opts.ptr(),
2656                    seq.dst_mem_opts.ptr(),
2657                );
2658                self.ptr_store(&mem.bump(seq.dst_mem_opts.ptr_size().into()));
2659            }
2660            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
2661        }
2662
2663        self.free_temp_local(seq.src_len);
2664        self.free_temp_local(seq.src_mem.addr);
2665        self.free_temp_local(seq.dst_mem.addr);
2666    }
2667
2668    fn translate_list(
2669        &mut self,
2670        src_ty: TypeListIndex,
2671        src: &Source<'_>,
2672        dst_ty: &InterfaceType,
2673        dst: &Destination,
2674    ) {
2675        let src_mem_opts = match &src.opts().data_model {
2676            DataModel::Gc {} => todo!("CM+GC"),
2677            DataModel::LinearMemory(opts) => opts,
2678        };
2679        let dst_mem_opts = match &dst.opts().data_model {
2680            DataModel::Gc {} => todo!("CM+GC"),
2681            DataModel::LinearMemory(opts) => opts,
2682        };
2683
2684        let src_element_ty = &self.types[src_ty].element;
2685        let dst_element_ty = match dst_ty {
2686            InterfaceType::List(r) => &self.types[*r].element,
2687            _ => panic!("expected a list"),
2688        };
2689        let (src_size, src_align) = self.types.size_align(src_mem_opts, src_element_ty);
2690        let (dst_size, dst_align) = self.types.size_align(dst_mem_opts, dst_element_ty);
2691
2692        let seq = self.begin_translate_sequence(src, dst, src_size, src_align, dst_size, dst_align);
2693
2694        if let Some(ref loop_state) = seq.loop_state {
2695            let element_src = Source::Memory(Memory {
2696                opts: seq.src_opts,
2697                offset: 0,
2698                addr: TempLocal::new(loop_state.cur_src_ptr.idx, loop_state.cur_src_ptr.ty),
2699            });
2700            let element_dst = Destination::Memory(Memory {
2701                opts: seq.dst_opts,
2702                offset: 0,
2703                addr: TempLocal::new(loop_state.cur_dst_ptr.idx, loop_state.cur_dst_ptr.ty),
2704            });
2705            self.translate(src_element_ty, &element_src, dst_element_ty, &element_dst);
2706
2707            if src_size > 0 {
2708                self.instruction(LocalGet(loop_state.cur_src_ptr.idx));
2709                self.ptr_uconst(src_mem_opts, src_size);
2710                self.ptr_add(src_mem_opts);
2711                self.instruction(LocalSet(loop_state.cur_src_ptr.idx));
2712            }
2713            if dst_size > 0 {
2714                self.instruction(LocalGet(loop_state.cur_dst_ptr.idx));
2715                self.ptr_uconst(dst_mem_opts, dst_size);
2716                self.ptr_add(dst_mem_opts);
2717                self.instruction(LocalSet(loop_state.cur_dst_ptr.idx));
2718            }
2719        }
2720
2721        self.end_translate_sequence(seq, dst);
2722    }
2723
2724    /// Translates a map from one component's memory to another.
2725    ///
2726    /// In the Component Model, a `map<K, V>` is stored in memory as
2727    /// `list<tuple<K, V>>`, so the translation reuses the same sequence
2728    /// scaffolding as lists but with a two-field (key, value) loop body.
2729    fn translate_map(
2730        &mut self,
2731        src_ty: TypeMapIndex,
2732        src: &Source<'_>,
2733        dst_ty: &InterfaceType,
2734        dst: &Destination,
2735    ) {
2736        let src_mem_opts = match &src.opts().data_model {
2737            DataModel::Gc {} => todo!("CM+GC"),
2738            DataModel::LinearMemory(opts) => opts,
2739        };
2740        let dst_mem_opts = match &dst.opts().data_model {
2741            DataModel::Gc {} => todo!("CM+GC"),
2742            DataModel::LinearMemory(opts) => opts,
2743        };
2744
2745        let src_map_ty = &self.types[src_ty];
2746        let dst_map_ty = match dst_ty {
2747            InterfaceType::Map(r) => &self.types[*r],
2748            _ => panic!("expected a map"),
2749        };
2750
2751        // Each map entry is a tuple<K, V> following record layout rules.
2752        let src_key_abi = self.types.canonical_abi(&src_map_ty.key);
2753        let src_value_abi = self.types.canonical_abi(&src_map_ty.value);
2754        let src_entry_abi = CanonicalAbiInfo::record([src_key_abi, src_value_abi].into_iter());
2755        let (src_tuple_size, src_entry_align) = src_mem_opts.sizealign(&src_entry_abi);
2756        let src_value_offset = {
2757            let mut offset = 0u32;
2758            if src_mem_opts.memory64() {
2759                src_key_abi.next_field64(&mut offset);
2760                src_value_abi.next_field64(&mut offset)
2761            } else {
2762                src_key_abi.next_field32(&mut offset);
2763                src_value_abi.next_field32(&mut offset)
2764            }
2765        };
2766
2767        let dst_key_abi = self.types.canonical_abi(&dst_map_ty.key);
2768        let dst_value_abi = self.types.canonical_abi(&dst_map_ty.value);
2769        let dst_entry_abi = CanonicalAbiInfo::record([dst_key_abi, dst_value_abi].into_iter());
2770        let (dst_tuple_size, dst_entry_align) = dst_mem_opts.sizealign(&dst_entry_abi);
2771        let dst_value_offset = {
2772            let mut offset = 0u32;
2773            if dst_mem_opts.memory64() {
2774                dst_key_abi.next_field64(&mut offset);
2775                dst_value_abi.next_field64(&mut offset)
2776            } else {
2777                dst_key_abi.next_field32(&mut offset);
2778                dst_value_abi.next_field32(&mut offset)
2779            }
2780        };
2781
2782        let seq = self.begin_translate_sequence(
2783            src,
2784            dst,
2785            src_tuple_size,
2786            src_entry_align,
2787            dst_tuple_size,
2788            dst_entry_align,
2789        );
2790
2791        if let Some(ref loop_state) = seq.loop_state {
2792            let key_src = Source::Memory(Memory {
2793                opts: seq.src_opts,
2794                offset: 0,
2795                addr: TempLocal::new(loop_state.cur_src_ptr.idx, src_mem_opts.ptr()),
2796            });
2797            let key_dst = Destination::Memory(Memory {
2798                opts: seq.dst_opts,
2799                offset: 0,
2800                addr: TempLocal::new(loop_state.cur_dst_ptr.idx, dst_mem_opts.ptr()),
2801            });
2802            self.translate(&src_map_ty.key, &key_src, &dst_map_ty.key, &key_dst);
2803
2804            let value_src = Source::Memory(Memory {
2805                opts: seq.src_opts,
2806                offset: src_value_offset,
2807                addr: TempLocal::new(loop_state.cur_src_ptr.idx, src_mem_opts.ptr()),
2808            });
2809            let value_dst = Destination::Memory(Memory {
2810                opts: seq.dst_opts,
2811                offset: dst_value_offset,
2812                addr: TempLocal::new(loop_state.cur_dst_ptr.idx, dst_mem_opts.ptr()),
2813            });
2814            self.translate(&src_map_ty.value, &value_src, &dst_map_ty.value, &value_dst);
2815
2816            // Advance past value + trailing padding to the next entry
2817            if src_tuple_size > 0 {
2818                self.instruction(LocalGet(loop_state.cur_src_ptr.idx));
2819                self.ptr_uconst(src_mem_opts, src_tuple_size);
2820                self.ptr_add(src_mem_opts);
2821                self.instruction(LocalSet(loop_state.cur_src_ptr.idx));
2822            }
2823            if dst_tuple_size > 0 {
2824                self.instruction(LocalGet(loop_state.cur_dst_ptr.idx));
2825                self.ptr_uconst(dst_mem_opts, dst_tuple_size);
2826                self.ptr_add(dst_mem_opts);
2827                self.instruction(LocalSet(loop_state.cur_dst_ptr.idx));
2828            }
2829        }
2830
2831        self.end_translate_sequence(seq, dst);
2832    }
2833
2834    fn calculate_list_byte_len(
2835        &mut self,
2836        opts: &LinearMemoryOptions,
2837        len_local: u32,
2838        elt_size: u32,
2839    ) -> TempLocal {
2840        // Zero-size types are easy to handle here because the byte size of the
2841        // destination is always zero.
2842        if elt_size == 0 {
2843            self.ptr_uconst(opts, 0);
2844            return self.local_set_new_tmp(opts.ptr());
2845        }
2846
2847        // For one-byte elements in the destination the check here can be a bit
2848        // more optimal than the general case below. In these situations if the
2849        // source pointer type is 32-bit then we're guaranteed to not overflow,
2850        // so the source length is simply casted to the destination's type.
2851        //
2852        // If the source is 64-bit then all that needs to be checked is to
2853        // ensure that it does not have the upper 32-bits set.
2854        if elt_size == 1 {
2855            if let ValType::I64 = opts.ptr() {
2856                self.instruction(LocalGet(len_local));
2857                self.instruction(I64Const(32));
2858                self.instruction(I64ShrU);
2859                self.instruction(I32WrapI64);
2860                self.instruction(If(BlockType::Empty));
2861                self.trap(Trap::ListOutOfBounds);
2862                self.instruction(End);
2863            }
2864            self.instruction(LocalGet(len_local));
2865            return self.local_set_new_tmp(opts.ptr());
2866        }
2867
2868        // The main check implemented by this function is to verify that
2869        // `src_len_local` does not exceed the 32-bit range. Byte sizes for
2870        // lists must always fit in 32-bits to get transferred to 32-bit
2871        // memories.
2872        self.instruction(Block(BlockType::Empty));
2873        self.instruction(Block(BlockType::Empty));
2874        self.instruction(LocalGet(len_local));
2875        match opts.ptr() {
2876            // The source's list length is guaranteed to be less than 32-bits
2877            // so simply extend it up to a 64-bit type for the multiplication
2878            // below.
2879            ValType::I32 => self.instruction(I64ExtendI32U),
2880
2881            // If the source is a 64-bit memory then if the item length doesn't
2882            // fit in 32-bits the byte length definitely won't, so generate a
2883            // branch to our overflow trap here if any of the upper 32-bits are set.
2884            ValType::I64 => {
2885                self.instruction(I64Const(32));
2886                self.instruction(I64ShrU);
2887                self.instruction(I32WrapI64);
2888                self.instruction(BrIf(0));
2889                self.instruction(LocalGet(len_local));
2890            }
2891
2892            _ => unreachable!(),
2893        }
2894
2895        // Next perform a 64-bit multiplication with the element byte size that
2896        // is itself guaranteed to fit in 32-bits. The result is then checked
2897        // to see if we overflowed the 32-bit space. The two input operands to
2898        // the multiplication are guaranteed to be 32-bits at most which means
2899        // that this multiplication shouldn't overflow.
2900        //
2901        // The result of the multiplication is saved into a local as well to
2902        // get the result afterwards.
2903        self.instruction(I64Const(elt_size.into()));
2904        self.instruction(I64Mul);
2905        let tmp = self.local_tee_new_tmp(ValType::I64);
2906        // Branch to success if the upper 32-bits are zero, otherwise
2907        // fall-through to the trap.
2908        self.instruction(I64Const(32));
2909        self.instruction(I64ShrU);
2910        self.instruction(I64Eqz);
2911        self.instruction(BrIf(1));
2912        self.instruction(End);
2913        self.trap(Trap::ListOutOfBounds);
2914        self.instruction(End);
2915
2916        // If a fresh local was used to store the result of the multiplication
2917        // then convert it down to 32-bits which should be guaranteed to not
2918        // lose information at this point.
2919        if opts.ptr() == ValType::I64 {
2920            tmp
2921        } else {
2922            self.instruction(LocalGet(tmp.idx));
2923            self.instruction(I32WrapI64);
2924            self.free_temp_local(tmp);
2925            self.local_set_new_tmp(ValType::I32)
2926        }
2927    }
2928
2929    fn convert_src_len_to_dst(
2930        &mut self,
2931        src_len_local: u32,
2932        src_ptr_ty: ValType,
2933        dst_ptr_ty: ValType,
2934    ) {
2935        self.instruction(LocalGet(src_len_local));
2936        match (src_ptr_ty, dst_ptr_ty) {
2937            (ValType::I32, ValType::I64) => self.instruction(I64ExtendI32U),
2938            (ValType::I64, ValType::I32) => self.instruction(I32WrapI64),
2939            (src, dst) => assert_eq!(src, dst),
2940        }
2941    }
2942
2943    fn translate_record(
2944        &mut self,
2945        src_ty: TypeRecordIndex,
2946        src: &Source<'_>,
2947        dst_ty: &InterfaceType,
2948        dst: &Destination,
2949    ) {
2950        let src_ty = &self.types[src_ty];
2951        let dst_ty = match dst_ty {
2952            InterfaceType::Record(r) => &self.types[*r],
2953            _ => panic!("expected a record"),
2954        };
2955
2956        // TODO: subtyping
2957        assert_eq!(src_ty.fields.len(), dst_ty.fields.len());
2958
2959        // First a map is made of the source fields to where they're coming
2960        // from (e.g. which offset or which locals). This map is keyed by the
2961        // fields' names
2962        let mut src_fields = HashMap::new();
2963        for (i, src) in src
2964            .record_field_srcs(self.types, src_ty.fields.iter().map(|f| f.ty))
2965            .enumerate()
2966        {
2967            let field = &src_ty.fields[i];
2968            src_fields.insert(&field.name, (src, &field.ty));
2969        }
2970
2971        // .. and next translation is performed in the order of the destination
2972        // fields in case the destination is the stack to ensure that the stack
2973        // has the fields all in the right order.
2974        //
2975        // Note that the lookup in `src_fields` is an infallible lookup which
2976        // will panic if the field isn't found.
2977        //
2978        // TODO: should that lookup be fallible with subtyping?
2979        for (i, dst) in dst
2980            .record_field_dsts(self.types, dst_ty.fields.iter().map(|f| f.ty))
2981            .enumerate()
2982        {
2983            let field = &dst_ty.fields[i];
2984            let (src, src_ty) = &src_fields[&field.name];
2985            self.translate(src_ty, src, &field.ty, &dst);
2986        }
2987    }
2988
2989    fn translate_flags(
2990        &mut self,
2991        src_ty: TypeFlagsIndex,
2992        src: &Source<'_>,
2993        dst_ty: &InterfaceType,
2994        dst: &Destination,
2995    ) {
2996        let src_ty = &self.types[src_ty];
2997        let dst_ty = match dst_ty {
2998            InterfaceType::Flags(r) => &self.types[*r],
2999            _ => panic!("expected a record"),
3000        };
3001
3002        // TODO: subtyping
3003        //
3004        // Notably this implementation does not support reordering flags from
3005        // the source to the destination nor having more flags in the
3006        // destination. Currently this is a copy from source to destination
3007        // in-bulk. Otherwise reordering indices would have to have some sort of
3008        // fancy bit twiddling tricks or something like that.
3009        assert_eq!(src_ty.names, dst_ty.names);
3010        let cnt = src_ty.names.len();
3011        match FlagsSize::from_count(cnt) {
3012            FlagsSize::Size0 => {}
3013            FlagsSize::Size1 => {
3014                let mask = if cnt == 8 { 0xff } else { (1 << cnt) - 1 };
3015                self.convert_u8_mask(src, dst, mask);
3016            }
3017            FlagsSize::Size2 => {
3018                let mask = if cnt == 16 { 0xffff } else { (1 << cnt) - 1 };
3019                self.convert_u16_mask(src, dst, mask);
3020            }
3021            FlagsSize::Size4Plus(n) => {
3022                let srcs = src.record_field_srcs(self.types, (0..n).map(|_| InterfaceType::U32));
3023                let dsts = dst.record_field_dsts(self.types, (0..n).map(|_| InterfaceType::U32));
3024                let n = usize::from(n);
3025                for (i, (src, dst)) in srcs.zip(dsts).enumerate() {
3026                    let mask = if i == n - 1 && (cnt % 32 != 0) {
3027                        (1 << (cnt % 32)) - 1
3028                    } else {
3029                        0xffffffff
3030                    };
3031                    self.convert_u32_mask(&src, &dst, mask);
3032                }
3033            }
3034        }
3035    }
3036
3037    fn translate_tuple(
3038        &mut self,
3039        src_ty: TypeTupleIndex,
3040        src: &Source<'_>,
3041        dst_ty: &InterfaceType,
3042        dst: &Destination,
3043    ) {
3044        let src_ty = &self.types[src_ty];
3045        let dst_ty = match dst_ty {
3046            InterfaceType::Tuple(t) => &self.types[*t],
3047            _ => panic!("expected a tuple"),
3048        };
3049
3050        // TODO: subtyping
3051        assert_eq!(src_ty.types.len(), dst_ty.types.len());
3052
3053        let srcs = src
3054            .record_field_srcs(self.types, src_ty.types.iter().copied())
3055            .zip(src_ty.types.iter());
3056        let dsts = dst
3057            .record_field_dsts(self.types, dst_ty.types.iter().copied())
3058            .zip(dst_ty.types.iter());
3059        for ((src, src_ty), (dst, dst_ty)) in srcs.zip(dsts) {
3060            self.translate(src_ty, &src, dst_ty, &dst);
3061        }
3062    }
3063
3064    fn translate_fixed_length_list(
3065        &mut self,
3066        src_ty: TypeFixedLengthListIndex,
3067        src: &Source<'_>,
3068        dst_ty: &InterfaceType,
3069        dst: &Destination,
3070    ) {
3071        let src_ty = &self.types[src_ty];
3072        let dst_ty = match dst_ty {
3073            InterfaceType::FixedLengthList(t) => &self.types[*t],
3074            _ => panic!("expected a fixed size list"),
3075        };
3076
3077        // TODO: subtyping
3078        assert_eq!(src_ty.size, dst_ty.size);
3079
3080        match (&src, &dst) {
3081            // Generate custom code for memory to memory copy
3082            (Source::Memory(src_mem), Destination::Memory(dst_mem)) => {
3083                let src_mem_opts = match &src_mem.opts.data_model {
3084                    DataModel::Gc {} => todo!("CM+GC"),
3085                    DataModel::LinearMemory(opts) => opts,
3086                };
3087                let dst_mem_opts = match &dst_mem.opts.data_model {
3088                    DataModel::Gc {} => todo!("CM+GC"),
3089                    DataModel::LinearMemory(opts) => opts,
3090                };
3091                let src_element_bytes = self.types.size_align(src_mem_opts, &src_ty.element).0;
3092                let dst_element_bytes = self.types.size_align(dst_mem_opts, &dst_ty.element).0;
3093                assert_ne!(src_element_bytes, 0);
3094                assert_ne!(dst_element_bytes, 0);
3095
3096                // because data is stored in-line, we assume that source and destination memory have been validated upstream
3097
3098                self.instruction(LocalGet(src_mem.addr.idx));
3099                if src_mem.offset != 0 {
3100                    self.ptr_uconst(src_mem_opts, src_mem.offset);
3101                    self.ptr_add(src_mem_opts);
3102                }
3103                let cur_src_ptr = self.local_set_new_tmp(src_mem_opts.ptr());
3104                self.instruction(LocalGet(dst_mem.addr.idx));
3105                if dst_mem.offset != 0 {
3106                    self.ptr_uconst(dst_mem_opts, dst_mem.offset);
3107                    self.ptr_add(dst_mem_opts);
3108                }
3109                let cur_dst_ptr = self.local_set_new_tmp(dst_mem_opts.ptr());
3110
3111                self.instruction(I32Const(src_ty.size as i32));
3112                let remaining = self.local_set_new_tmp(ValType::I32);
3113
3114                self.instruction(Loop(BlockType::Empty));
3115
3116                // Translate the next element in the list
3117                let element_src = Source::Memory(Memory {
3118                    opts: src_mem.opts,
3119                    offset: 0,
3120                    addr: TempLocal::new(cur_src_ptr.idx, cur_src_ptr.ty),
3121                });
3122                let element_dst = Destination::Memory(Memory {
3123                    opts: dst_mem.opts,
3124                    offset: 0,
3125                    addr: TempLocal::new(cur_dst_ptr.idx, cur_dst_ptr.ty),
3126                });
3127                self.translate(&src_ty.element, &element_src, &dst_ty.element, &element_dst);
3128
3129                // Update the two loop pointers
3130                self.instruction(LocalGet(cur_src_ptr.idx));
3131                self.ptr_uconst(src_mem_opts, src_element_bytes);
3132                self.ptr_add(src_mem_opts);
3133                self.instruction(LocalSet(cur_src_ptr.idx));
3134                self.instruction(LocalGet(cur_dst_ptr.idx));
3135                self.ptr_uconst(dst_mem_opts, dst_element_bytes);
3136                self.ptr_add(dst_mem_opts);
3137                self.instruction(LocalSet(cur_dst_ptr.idx));
3138
3139                // Update the remaining count, falling through to break out if it's zero
3140                // now.
3141                //
3142                // FIXME(#4311): needs memory64 treatment, `remaining` is an
3143                // i32 but this uses pointer-width instructions for a 64-bit
3144                // source memory
3145                self.instruction(LocalGet(remaining.idx));
3146                self.ptr_iconst(src_mem_opts, -1);
3147                self.ptr_add(src_mem_opts);
3148                self.instruction(LocalTee(remaining.idx));
3149                self.ptr_br_if(src_mem_opts, 0);
3150                self.instruction(End); // end of loop
3151
3152                self.free_temp_local(cur_dst_ptr);
3153                self.free_temp_local(cur_src_ptr);
3154                self.free_temp_local(remaining);
3155                return;
3156            }
3157            // for the non-memory-to-memory case fall back to using generic tuple translation
3158            (_, _) => {
3159                // Assumes that the number of elements are small enough for this unrolling
3160                assert!(
3161                    src_ty.size as usize <= MAX_FLAT_PARAMS
3162                        && dst_ty.size as usize <= MAX_FLAT_PARAMS
3163                );
3164                let srcs =
3165                    src.record_field_srcs(self.types, (0..src_ty.size).map(|_| src_ty.element));
3166                let dsts =
3167                    dst.record_field_dsts(self.types, (0..dst_ty.size).map(|_| dst_ty.element));
3168                for (src, dst) in srcs.zip(dsts) {
3169                    self.translate(&src_ty.element, &src, &dst_ty.element, &dst);
3170                }
3171            }
3172        }
3173    }
3174
3175    fn translate_variant(
3176        &mut self,
3177        src_ty: TypeVariantIndex,
3178        src: &Source<'_>,
3179        dst_ty: &InterfaceType,
3180        dst: &Destination,
3181    ) {
3182        let src_ty = &self.types[src_ty];
3183        let dst_ty = match dst_ty {
3184            InterfaceType::Variant(t) => &self.types[*t],
3185            _ => panic!("expected a variant"),
3186        };
3187
3188        let src_info = variant_info(self.types, src_ty.cases.iter().map(|(_, c)| c.as_ref()));
3189        let dst_info = variant_info(self.types, dst_ty.cases.iter().map(|(_, c)| c.as_ref()));
3190
3191        let iter = src_ty
3192            .cases
3193            .iter()
3194            .enumerate()
3195            .map(|(src_i, (src_case, src_case_ty))| {
3196                let dst_i = dst_ty
3197                    .cases
3198                    .iter()
3199                    .position(|(c, _)| c == src_case)
3200                    .unwrap();
3201                let dst_case_ty = &dst_ty.cases[dst_i];
3202                let src_i = u32::try_from(src_i).unwrap();
3203                let dst_i = u32::try_from(dst_i).unwrap();
3204                VariantCase {
3205                    src_i,
3206                    src_ty: src_case_ty.as_ref(),
3207                    dst_i,
3208                    dst_ty: dst_case_ty.as_ref(),
3209                }
3210            });
3211        self.convert_variant(src, &src_info, dst, &dst_info, iter);
3212    }
3213
3214    fn translate_enum(
3215        &mut self,
3216        src_ty: TypeEnumIndex,
3217        src: &Source<'_>,
3218        dst_ty: &InterfaceType,
3219        dst: &Destination,
3220    ) {
3221        let src_ty = &self.types[src_ty];
3222        let dst_ty = match dst_ty {
3223            InterfaceType::Enum(t) => &self.types[*t],
3224            _ => panic!("expected an option"),
3225        };
3226
3227        debug_assert_eq!(src_ty.info.size, dst_ty.info.size);
3228        debug_assert_eq!(src_ty.names.len(), dst_ty.names.len());
3229        debug_assert!(
3230            src_ty
3231                .names
3232                .iter()
3233                .zip(dst_ty.names.iter())
3234                .all(|(a, b)| a == b)
3235        );
3236
3237        // Get the discriminant.
3238        match src {
3239            Source::Stack(s) => self.stack_get(&s.slice(0..1), ValType::I32),
3240            Source::Memory(mem) => match src_ty.info.size {
3241                DiscriminantSize::Size1 => self.i32_load8u(mem),
3242                DiscriminantSize::Size2 => self.i32_load16u(mem),
3243                DiscriminantSize::Size4 => self.i32_load(mem),
3244            },
3245            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
3246        }
3247        let tmp = self.local_tee_new_tmp(ValType::I32);
3248
3249        // Assert that the discriminant is valid.
3250        self.instruction(I32Const(i32::try_from(src_ty.names.len()).unwrap()));
3251        self.instruction(I32GeU);
3252        self.instruction(If(BlockType::Empty));
3253        self.trap(Trap::InvalidDiscriminant);
3254        self.instruction(End);
3255
3256        // Save the discriminant to the destination.
3257        match dst {
3258            Destination::Stack(stack, _) => {
3259                self.local_get_tmp(&tmp);
3260                self.stack_set(&stack[..1], ValType::I32)
3261            }
3262            Destination::Memory(mem) => {
3263                self.push_dst_addr(dst);
3264                self.local_get_tmp(&tmp);
3265                match dst_ty.info.size {
3266                    DiscriminantSize::Size1 => self.i32_store8(mem),
3267                    DiscriminantSize::Size2 => self.i32_store16(mem),
3268                    DiscriminantSize::Size4 => self.i32_store(mem),
3269                }
3270            }
3271            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
3272        }
3273        self.free_temp_local(tmp);
3274    }
3275
3276    fn translate_option(
3277        &mut self,
3278        src_ty: TypeOptionIndex,
3279        src: &Source<'_>,
3280        dst_ty: &InterfaceType,
3281        dst: &Destination,
3282    ) {
3283        let src_ty = &self.types[src_ty].ty;
3284        let dst_ty = match dst_ty {
3285            InterfaceType::Option(t) => &self.types[*t].ty,
3286            _ => panic!("expected an option"),
3287        };
3288        let src_ty = Some(src_ty);
3289        let dst_ty = Some(dst_ty);
3290
3291        let src_info = variant_info(self.types, [None, src_ty]);
3292        let dst_info = variant_info(self.types, [None, dst_ty]);
3293
3294        self.convert_variant(
3295            src,
3296            &src_info,
3297            dst,
3298            &dst_info,
3299            [
3300                VariantCase {
3301                    src_i: 0,
3302                    dst_i: 0,
3303                    src_ty: None,
3304                    dst_ty: None,
3305                },
3306                VariantCase {
3307                    src_i: 1,
3308                    dst_i: 1,
3309                    src_ty,
3310                    dst_ty,
3311                },
3312            ]
3313            .into_iter(),
3314        );
3315    }
3316
3317    fn translate_result(
3318        &mut self,
3319        src_ty: TypeResultIndex,
3320        src: &Source<'_>,
3321        dst_ty: &InterfaceType,
3322        dst: &Destination,
3323    ) {
3324        let src_ty = &self.types[src_ty];
3325        let dst_ty = match dst_ty {
3326            InterfaceType::Result(t) => &self.types[*t],
3327            _ => panic!("expected a result"),
3328        };
3329
3330        let src_info = variant_info(self.types, [src_ty.ok.as_ref(), src_ty.err.as_ref()]);
3331        let dst_info = variant_info(self.types, [dst_ty.ok.as_ref(), dst_ty.err.as_ref()]);
3332
3333        self.convert_variant(
3334            src,
3335            &src_info,
3336            dst,
3337            &dst_info,
3338            [
3339                VariantCase {
3340                    src_i: 0,
3341                    dst_i: 0,
3342                    src_ty: src_ty.ok.as_ref(),
3343                    dst_ty: dst_ty.ok.as_ref(),
3344                },
3345                VariantCase {
3346                    src_i: 1,
3347                    dst_i: 1,
3348                    src_ty: src_ty.err.as_ref(),
3349                    dst_ty: dst_ty.err.as_ref(),
3350                },
3351            ]
3352            .into_iter(),
3353        );
3354    }
3355
3356    fn convert_variant<'c>(
3357        &mut self,
3358        src: &Source<'_>,
3359        src_info: &VariantInfo,
3360        dst: &Destination,
3361        dst_info: &VariantInfo,
3362        src_cases: impl ExactSizeIterator<Item = VariantCase<'c>>,
3363    ) {
3364        // The outermost block is special since it has the result type of the
3365        // translation here. That will depend on the `dst`.
3366        let outer_block_ty = match dst {
3367            Destination::Stack(dst_flat, _) => match dst_flat.len() {
3368                0 => BlockType::Empty,
3369                1 => BlockType::Result(dst_flat[0]),
3370                _ => {
3371                    let ty = self.module.core_types.function(&[], &dst_flat);
3372                    BlockType::FunctionType(ty)
3373                }
3374            },
3375            Destination::Memory(_) => BlockType::Empty,
3376            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
3377        };
3378        self.instruction(Block(outer_block_ty));
3379
3380        // After the outermost block generate a new block for each of the
3381        // remaining cases.
3382        let src_cases_len = src_cases.len();
3383        for _ in 0..src_cases_len - 1 {
3384            self.instruction(Block(BlockType::Empty));
3385        }
3386
3387        // Generate a block for an invalid variant discriminant
3388        self.instruction(Block(BlockType::Empty));
3389
3390        // And generate one final block that we'll be jumping out of with the
3391        // `br_table`
3392        self.instruction(Block(BlockType::Empty));
3393
3394        // Load the discriminant
3395        match src {
3396            Source::Stack(s) => self.stack_get(&s.slice(0..1), ValType::I32),
3397            Source::Memory(mem) => match src_info.size {
3398                DiscriminantSize::Size1 => self.i32_load8u(mem),
3399                DiscriminantSize::Size2 => self.i32_load16u(mem),
3400                DiscriminantSize::Size4 => self.i32_load(mem),
3401            },
3402            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
3403        }
3404
3405        // Generate the `br_table` for the discriminant. Each case has an
3406        // offset of 1 to skip the trapping block.
3407        let mut targets = Vec::new();
3408        for i in 0..src_cases_len {
3409            targets.push((i + 1) as u32);
3410        }
3411        self.instruction(BrTable(targets[..].into(), 0));
3412        self.instruction(End); // end the `br_table` block
3413
3414        self.trap(Trap::InvalidDiscriminant);
3415        self.instruction(End); // end the "invalid discriminant" block
3416
3417        // Translate each case individually within its own block. Note that the
3418        // iteration order here places the first case in the innermost block
3419        // and the last case in the outermost block. This matches the order
3420        // of the jump targets in the `br_table` instruction.
3421        let src_cases_len = u32::try_from(src_cases_len).unwrap();
3422        for case in src_cases {
3423            let VariantCase {
3424                src_i,
3425                src_ty,
3426                dst_i,
3427                dst_ty,
3428            } = case;
3429
3430            // Translate the discriminant here, noting that `dst_i` may be
3431            // different than `src_i`.
3432            self.push_dst_addr(dst);
3433            self.instruction(I32Const(dst_i as i32));
3434            match dst {
3435                Destination::Stack(stack, _) => self.stack_set(&stack[..1], ValType::I32),
3436                Destination::Memory(mem) => match dst_info.size {
3437                    DiscriminantSize::Size1 => self.i32_store8(mem),
3438                    DiscriminantSize::Size2 => self.i32_store16(mem),
3439                    DiscriminantSize::Size4 => self.i32_store(mem),
3440                },
3441                Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
3442            }
3443
3444            let src_payload = src.payload_src(self.types, src_info, src_ty);
3445            let dst_payload = dst.payload_dst(self.types, dst_info, dst_ty);
3446
3447            // Translate the payload of this case using the various types from
3448            // the dst/src.
3449            match (src_ty, dst_ty) {
3450                (Some(src_ty), Some(dst_ty)) => {
3451                    self.translate(src_ty, &src_payload, dst_ty, &dst_payload);
3452                }
3453                (None, None) => {}
3454                _ => unimplemented!(),
3455            }
3456
3457            // If the results of this translation were placed on the stack then
3458            // the stack values may need to be padded with more zeros due to
3459            // this particular case being possibly smaller than the entire
3460            // variant. That's handled here by pushing remaining zeros after
3461            // accounting for the discriminant pushed as well as the results of
3462            // this individual payload.
3463            if let Destination::Stack(payload_results, _) = dst_payload {
3464                if let Destination::Stack(dst_results, _) = dst {
3465                    let remaining = &dst_results[1..][payload_results.len()..];
3466                    for ty in remaining {
3467                        match ty {
3468                            ValType::I32 => self.instruction(I32Const(0)),
3469                            ValType::I64 => self.instruction(I64Const(0)),
3470                            ValType::F32 => self.instruction(F32Const(0.0.into())),
3471                            ValType::F64 => self.instruction(F64Const(0.0.into())),
3472                            _ => unreachable!(),
3473                        }
3474                    }
3475                }
3476            }
3477
3478            // Branch to the outermost block. Note that this isn't needed for
3479            // the outermost case since it simply falls through.
3480            if src_i != src_cases_len - 1 {
3481                self.instruction(Br(src_cases_len - src_i - 1));
3482            }
3483            self.instruction(End); // end this case's block
3484        }
3485    }
3486
3487    fn translate_future(
3488        &mut self,
3489        src_ty: TypeFutureTableIndex,
3490        src: &Source<'_>,
3491        dst_ty: &InterfaceType,
3492        dst: &Destination,
3493    ) {
3494        let dst_ty = match dst_ty {
3495            InterfaceType::Future(t) => *t,
3496            _ => panic!("expected a `Future`"),
3497        };
3498        let transfer = self.module.import_future_transfer();
3499        self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);
3500    }
3501
3502    fn translate_stream(
3503        &mut self,
3504        src_ty: TypeStreamTableIndex,
3505        src: &Source<'_>,
3506        dst_ty: &InterfaceType,
3507        dst: &Destination,
3508    ) {
3509        let dst_ty = match dst_ty {
3510            InterfaceType::Stream(t) => *t,
3511            _ => panic!("expected a `Stream`"),
3512        };
3513        let transfer = self.module.import_stream_transfer();
3514        self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);
3515    }
3516
3517    fn translate_error_context(
3518        &mut self,
3519        src_ty: TypeComponentLocalErrorContextTableIndex,
3520        src: &Source<'_>,
3521        dst_ty: &InterfaceType,
3522        dst: &Destination,
3523    ) {
3524        let dst_ty = match dst_ty {
3525            InterfaceType::ErrorContext(t) => *t,
3526            _ => panic!("expected an `ErrorContext`"),
3527        };
3528        let transfer = self.module.import_error_context_transfer();
3529        self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);
3530    }
3531
3532    fn translate_own(
3533        &mut self,
3534        src_ty: TypeResourceTableIndex,
3535        src: &Source<'_>,
3536        dst_ty: &InterfaceType,
3537        dst: &Destination,
3538    ) {
3539        let dst_ty = match dst_ty {
3540            InterfaceType::Own(t) => *t,
3541            _ => panic!("expected an `Own`"),
3542        };
3543        let transfer = self.module.import_resource_transfer_own();
3544        self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);
3545    }
3546
3547    fn translate_borrow(
3548        &mut self,
3549        src_ty: TypeResourceTableIndex,
3550        src: &Source<'_>,
3551        dst_ty: &InterfaceType,
3552        dst: &Destination,
3553    ) {
3554        let dst_ty = match dst_ty {
3555            InterfaceType::Borrow(t) => *t,
3556            _ => panic!("expected an `Borrow`"),
3557        };
3558
3559        if self.module.resource_owned_by_own_instance(dst_ty) {
3560            let transfer = self.module.import_resource_transfer_borrow_to_owner(src_ty);
3561            self.translate_handle_types(src, &[], dst, transfer);
3562        } else {
3563            let transfer = self.module.import_resource_transfer_borrow();
3564            self.translate_handle(src_ty.as_u32(), src, Some(dst_ty.as_u32()), dst, transfer);
3565        }
3566    }
3567
3568    /// Translates the index `src`, which resides in the table `src_ty`, into
3569    /// and index within `dst_ty` and is stored at `dst`.
3570    ///
3571    /// Actual translation of the index happens in a wasmtime libcall, which a
3572    /// cranelift-generated trampoline to satisfy this import will call. The
3573    /// `transfer` function is an imported function which takes the src, src_ty,
3574    /// and dst_ty, and returns the dst index.
3575    fn translate_handle(
3576        &mut self,
3577        src_ty: u32,
3578        src: &Source<'_>,
3579        dst_ty: Option<u32>,
3580        dst: &Destination,
3581        transfer: FuncIndex,
3582    ) {
3583        let types: &[u32] = match dst_ty {
3584            Some(dst_ty) => &[src_ty, dst_ty],
3585            None => &[src_ty],
3586        };
3587        self.translate_handle_types(src, types, dst, transfer);
3588    }
3589
3590    /// As [`Self::translate_handle`], except that `types` gives exactly the
3591    /// type constants to push after the index.
3592    fn translate_handle_types(
3593        &mut self,
3594        src: &Source<'_>,
3595        types: &[u32],
3596        dst: &Destination,
3597        transfer: FuncIndex,
3598    ) {
3599        self.push_dst_addr(dst);
3600        match src {
3601            Source::Memory(mem) => self.i32_load(mem),
3602            Source::Stack(stack) => self.stack_get(stack, ValType::I32),
3603            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
3604        }
3605        for ty in types {
3606            self.instruction(I32Const(*ty as i32));
3607        }
3608        self.instruction(Call(transfer.as_u32()));
3609        match dst {
3610            Destination::Memory(mem) => self.i32_store(mem),
3611            Destination::Stack(stack, _) => self.stack_set(stack, ValType::I32),
3612            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
3613        }
3614    }
3615
3616    /// Loads the `may_leave` flag for the given instance, traps with `trap` if
3617    /// it is not set, and returns a temporary local holding the loaded value
3618    /// so that it can later be restored with `restore_may_leave` without
3619    /// reloading the global.
3620    ///
3621    /// The `may_leave` flag is a boolean (0 or 1) so no masking is required.
3622    fn trap_if_not_may_leave(&mut self, flags_global: GlobalIndex, trap: Trap) -> TempLocal {
3623        self.instruction(Block(BlockType::Empty));
3624        self.instruction(GlobalGet(flags_global.as_u32()));
3625        // Save the flag's value (known to be `true` whenever the trap below is
3626        // not taken) into a temporary for later restoration.
3627        let saved = self.local_tee_new_tmp(ValType::I32);
3628        self.instruction(BrIf(0));
3629        self.trap(trap);
3630        self.instruction(End);
3631        saved
3632    }
3633
3634    /// Saves the current value of the `may_leave` flag into a fresh temporary
3635    /// local (returned) and then clears the flag to `false`.
3636    fn clear_may_leave(&mut self, flags_global: GlobalIndex) -> TempLocal {
3637        self.instruction(GlobalGet(flags_global.as_u32()));
3638        let saved = self.local_set_new_tmp(ValType::I32);
3639        self.set_may_leave_false(flags_global);
3640        saved
3641    }
3642
3643    /// Sets the `may_leave` flag to `false` by storing a constant `0`.
3644    ///
3645    /// Since there is only a single flag there is no need to reload the global
3646    /// and mask: storing `0` is sufficient.
3647    fn set_may_leave_false(&mut self, flags_global: GlobalIndex) {
3648        self.instruction(I32Const(0));
3649        self.instruction(GlobalSet(flags_global.as_u32()));
3650    }
3651
3652    /// Restores the `may_leave` flag to the value previously saved in `saved`
3653    /// (via `clear_may_leave` or `trap_if_not_may_leave`) and frees the
3654    /// temporary local.
3655    ///
3656    /// Storing the previously-loaded value (rather than reloading the global
3657    /// and or-ing in the flag bit) makes it clear in the generated CLIF that
3658    /// the same value that was there before is being written back. Combined
3659    /// with the constant `0` store in `set_may_leave_false`, this lets a future
3660    /// dead-store-elimination pass remove the clear-to-`false` store which will
3661    /// then allow our idempotent-store elimination to remove this restore for
3662    /// adapters whose body never touches the flag (e.g. simple inlined
3663    /// callees).
3664    fn restore_may_leave(&mut self, flags_global: GlobalIndex, saved: TempLocal) {
3665        self.instruction(LocalGet(saved.idx));
3666        self.instruction(GlobalSet(flags_global.as_u32()));
3667        self.free_temp_local(saved);
3668    }
3669
3670    fn assert_aligned(&mut self, ty: &InterfaceType, mem: &Memory) {
3671        let mem_opts = mem.mem_opts();
3672        if !self.module.tunables.debug_adapter_modules {
3673            return;
3674        }
3675        let align = self.types.align(mem_opts, ty);
3676        if align == 1 {
3677            return;
3678        }
3679        assert!(align.is_power_of_two());
3680        self.instruction(LocalGet(mem.addr.idx));
3681        self.ptr_uconst(mem_opts, mem.offset);
3682        self.ptr_add(mem_opts);
3683        self.ptr_uconst(mem_opts, align - 1);
3684        self.ptr_and(mem_opts);
3685        self.ptr_if(mem_opts, BlockType::Empty);
3686        self.trap(Trap::DebugAssertPointerAligned);
3687        self.instruction(End);
3688    }
3689
3690    /// Helper to invoke the guest's `realloc` function with a statically known
3691    /// `abi`.
3692    ///
3693    /// This will internally validate the return value is properly aligned and
3694    /// additionally within bounds of memory.
3695    fn malloc_abi<'c>(
3696        &mut self,
3697        opts: &'c Options,
3698        abi: &CanonicalAbiInfo,
3699        oob_trap: Trap,
3700    ) -> Memory<'c> {
3701        match &opts.data_model {
3702            DataModel::Gc {} => todo!("CM+GC"),
3703            DataModel::LinearMemory(mem_opts) => {
3704                let (size, align) = mem_opts.sizealign(abi);
3705                let size = AllocSize::Const(size);
3706                self.malloc(opts, size, align, oob_trap)
3707            }
3708        }
3709    }
3710
3711    /// Helper to invoke the guest's `realloc` function with the specified
3712    /// `size` and `align`.
3713    ///
3714    /// This will internally validate the return value is properly aligned and
3715    /// additionally within bounds of memory.
3716    fn malloc<'c>(
3717        &mut self,
3718        opts: &'c Options,
3719        size: AllocSize,
3720        align: u32,
3721        oob_trap: Trap,
3722    ) -> Memory<'c> {
3723        match &opts.data_model {
3724            DataModel::Gc {} => todo!("CM+GC"),
3725            DataModel::LinearMemory(mem_opts) => {
3726                let realloc = mem_opts.realloc.unwrap();
3727                self.ptr_uconst(mem_opts, 0);
3728                self.ptr_uconst(mem_opts, 0);
3729                self.ptr_uconst(mem_opts, align);
3730                self.alloc_size(mem_opts, &size);
3731                self.call_realloc(realloc);
3732                let addr = self.local_set_new_tmp(mem_opts.ptr());
3733                self.memory_operand(opts, addr, size, align, oob_trap)
3734            }
3735        }
3736    }
3737
3738    /// Helper to invoke the guest's `realloc` function with the specified
3739    /// arguments.
3740    ///
3741    /// This will internally validate the return value is properly aligned and
3742    /// additionally within bounds of memory.
3743    fn realloc(
3744        &mut self,
3745        opts: &Options,
3746        ptr: &TempLocal,
3747        prev_size: AllocSize,
3748        size: AllocSize,
3749        align: u32,
3750        oob_trap: Trap,
3751    ) {
3752        match &opts.data_model {
3753            DataModel::Gc {} => todo!("CM+GC"),
3754            DataModel::LinearMemory(mem_opts) => {
3755                let realloc = mem_opts.realloc.unwrap();
3756                self.instruction(LocalGet(ptr.idx));
3757                self.alloc_size(mem_opts, &prev_size);
3758                self.ptr_uconst(mem_opts, align);
3759                self.alloc_size(mem_opts, &size);
3760                self.call_realloc(realloc);
3761                self.instruction(LocalSet(ptr.idx));
3762                self.validate_guest_pointer(opts, &ptr, &size, align, oob_trap)
3763            }
3764        }
3765    }
3766
3767    /// Convenience helper aruond `memory_operand` which takes a
3768    /// statically known `abi` of the allocation.
3769    fn memory_operand_abi<'c>(
3770        &mut self,
3771        opts: &'c Options,
3772        addr: TempLocal,
3773        abi: &CanonicalAbiInfo,
3774        oob_trap: Trap,
3775    ) -> Memory<'c> {
3776        match &opts.data_model {
3777            DataModel::Gc {} => todo!("CM+GC"),
3778            DataModel::LinearMemory(mem_opts) => {
3779                let (size, align) = mem_opts.sizealign(abi);
3780                self.memory_operand(opts, addr, AllocSize::Const(size), align, oob_trap)
3781            }
3782        }
3783    }
3784
3785    /// Creates a `Memory` operand from the parts provided after validating
3786    /// that everything is in-bounds according to `validate_guest_pointer`.
3787    fn memory_operand<'c>(
3788        &mut self,
3789        opts: &'c Options,
3790        addr: TempLocal,
3791        size: AllocSize,
3792        align: u32,
3793        oob_trap: Trap,
3794    ) -> Memory<'c> {
3795        self.validate_guest_pointer(opts, &addr, &size, align, oob_trap);
3796        Memory {
3797            addr,
3798            opts,
3799            offset: 0,
3800        }
3801    }
3802
3803    /// Validates that the guest pointer `addr` is in-bounds for `size` amount
3804    /// of bytes.
3805    ///
3806    /// Additionally validates that `addr` is aligned to `align`.
3807    ///
3808    /// Traps with `oob_trap` if the `addr` value is not in-bounds for the
3809    /// linear memory specified by `opts`.
3810    fn validate_guest_pointer(
3811        &mut self,
3812        opts: &Options,
3813        addr: &TempLocal,
3814        size: &AllocSize,
3815        align: u32,
3816        oob_trap: Trap,
3817    ) {
3818        let mem_opts = match &opts.data_model {
3819            DataModel::Gc {} => todo!("CM+GC"),
3820            DataModel::LinearMemory(mem_opts) => mem_opts,
3821        };
3822
3823        // If the alignment is 1 then everything is trivially aligned and the
3824        // check can be omitted.
3825        if align != 1 {
3826            self.instruction(LocalGet(addr.idx));
3827            assert!(align.is_power_of_two());
3828            self.ptr_uconst(mem_opts, align - 1);
3829            self.ptr_and(mem_opts);
3830            self.ptr_if(mem_opts, BlockType::Empty);
3831            self.trap(Trap::UnalignedPointer);
3832            self.instruction(End);
3833        }
3834
3835        let extend_to_64 = |me: &mut Self| {
3836            if !mem_opts.memory64() {
3837                me.instruction(I64ExtendI32U);
3838            }
3839        };
3840
3841        self.instruction(Block(BlockType::Empty));
3842        self.instruction(Block(BlockType::Empty));
3843        let (memory, ty) = mem_opts.memory.unwrap();
3844
3845        // Calculate the full byte size of memory with `memory.size`. Note that
3846        // arithmetic here is done always in 64-bits to accommodate 4G memories.
3847        // Additionally it's assumed that 64-bit memories never fill up
3848        // entirely.
3849        self.instruction(MemorySize(memory.as_u32()));
3850        extend_to_64(self);
3851        self.instruction(I64Const(ty.page_size_log2.into()));
3852        self.instruction(I64Shl);
3853
3854        // Calculate the end address of the string. This is done by adding the
3855        // base pointer to the byte length. For 32-bit memories there's no need
3856        // to check for overflow since everything is extended to 64-bit, but for
3857        // 64-bit memories overflow is checked.
3858        self.instruction(LocalGet(addr.idx));
3859        extend_to_64(self);
3860        self.alloc_size(mem_opts, size);
3861        extend_to_64(self);
3862        self.instruction(I64Add);
3863        if mem_opts.memory64() {
3864            let tmp = self.local_tee_new_tmp(ValType::I64);
3865            self.instruction(LocalGet(addr.idx));
3866            self.ptr_lt_u(mem_opts);
3867            self.instruction(BrIf(0));
3868            self.instruction(LocalGet(tmp.idx));
3869            self.free_temp_local(tmp);
3870        }
3871
3872        // If the byte size of memory is greater than the final address of the
3873        // string then the string is invalid. Note that if it's precisely equal
3874        // then that's ok.
3875        self.instruction(I64GeU);
3876        self.instruction(BrIf(1));
3877
3878        self.instruction(End);
3879        self.trap(oob_trap);
3880        self.instruction(End);
3881    }
3882
3883    /// Generates a new local in this function of the `ty` specified,
3884    /// initializing it with the top value on the current wasm stack.
3885    ///
3886    /// The returned `TempLocal` must be freed after it is finished with
3887    /// `free_temp_local`.
3888    fn local_tee_new_tmp(&mut self, ty: ValType) -> TempLocal {
3889        self.gen_temp_local(ty, LocalTee)
3890    }
3891
3892    /// Same as `local_tee_new_tmp` but initializes the local with `LocalSet`
3893    /// instead of `LocalTee`.
3894    fn local_set_new_tmp(&mut self, ty: ValType) -> TempLocal {
3895        self.gen_temp_local(ty, LocalSet)
3896    }
3897
3898    fn local_get_tmp(&mut self, local: &TempLocal) {
3899        self.instruction(LocalGet(local.idx));
3900    }
3901
3902    fn gen_temp_local(&mut self, ty: ValType, insn: fn(u32) -> Instruction<'static>) -> TempLocal {
3903        // First check to see if any locals are available in this function which
3904        // were previously generated but are no longer in use.
3905        if let Some(idx) = self.free_locals.get_mut(&ty).and_then(|v| v.pop()) {
3906            self.instruction(insn(idx));
3907            return TempLocal {
3908                ty,
3909                idx,
3910                needs_free: true,
3911            };
3912        }
3913
3914        // Failing that generate a fresh new local.
3915        let locals = &mut self.module.funcs[self.result].locals;
3916        match locals.last_mut() {
3917            Some((cnt, prev_ty)) if ty == *prev_ty => *cnt += 1,
3918            _ => locals.push((1, ty)),
3919        }
3920        self.nlocals += 1;
3921        let idx = self.nlocals - 1;
3922        self.instruction(insn(idx));
3923        TempLocal {
3924            ty,
3925            idx,
3926            needs_free: true,
3927        }
3928    }
3929
3930    /// Used to release a `TempLocal` from a particular lexical scope to allow
3931    /// its possible reuse in later scopes.
3932    fn free_temp_local(&mut self, mut local: TempLocal) {
3933        assert!(local.needs_free);
3934        self.free_locals
3935            .entry(local.ty)
3936            .or_insert(Vec::new())
3937            .push(local.idx);
3938        local.needs_free = false;
3939    }
3940
3941    /// Reads all of the current task's `context.{get,set}` slots into fresh
3942    /// temporary locals which can later be handed to `restore_context`.
3943    fn save_context(&mut self) -> Vec<TempLocal> {
3944        if !self.module.tunables.concurrency_support {
3945            return Vec::new();
3946        }
3947        let mut saved = Vec::new();
3948        for slot in 0..NUM_COMPONENT_CONTEXT_SLOTS {
3949            let get = self.module.import_context_get(slot);
3950            self.instruction(Call(get.as_u32()));
3951            saved.push(self.local_set_new_tmp(ValType::I32));
3952        }
3953        saved
3954    }
3955
3956    /// Stores zero into all of the current task's `context.{get,set}` slots.
3957    fn clear_context(&mut self) {
3958        if !self.module.tunables.concurrency_support {
3959            return;
3960        }
3961        for slot in 0..NUM_COMPONENT_CONTEXT_SLOTS {
3962            let set = self.module.import_context_set(slot);
3963            self.instruction(I32Const(0));
3964            self.instruction(Call(set.as_u32()));
3965        }
3966    }
3967
3968    /// Stores the slot values previously read by `save_context` back into the
3969    /// current task's `context.{get,set}` slots.
3970    fn restore_context(&mut self, saved: Vec<TempLocal>) {
3971        for (slot, local) in saved.into_iter().enumerate() {
3972            let set = self.module.import_context_set(slot);
3973            self.instruction(LocalGet(local.idx));
3974            self.instruction(Call(set.as_u32()));
3975            self.free_temp_local(local);
3976        }
3977    }
3978
3979    /// Emits a call to a guest `realloc` function.
3980    ///
3981    /// Note that this has special handling of the current task's
3982    /// `context.{get,set}` slots, namely they're saved/restored around this
3983    /// call and zero'd out during the call.
3984    fn call_realloc(&mut self, realloc: FuncIndex) {
3985        let saved = self.save_context();
3986        self.clear_context();
3987        self.instruction(Call(realloc.as_u32()));
3988        self.restore_context(saved);
3989    }
3990
3991    fn instruction(&mut self, instr: Instruction) {
3992        instr.encode(&mut self.code);
3993    }
3994
3995    fn trap(&mut self, trap: Trap) {
3996        let trap_func = self.module.import_trap(trap);
3997        self.instruction(Call(trap_func.as_u32()));
3998        self.instruction(Unreachable);
3999    }
4000
4001    /// Emits the prologue of an exception barrier wrapping the body of a
4002    /// function.
4003    ///
4004    /// An adapter is the boundary between two components, and the
4005    /// component model's canonical ABI specifies that an exception
4006    /// which propagates out of a component without being caught
4007    /// becomes a trap rather than unwinding into the other
4008    /// component. To implement that, the entire body of an adapter
4009    /// function is wrapped in a `try_table` whose `catch_all` clause
4010    /// traps. This catches exceptions thrown not only by the callee
4011    /// itself but also by any other guest functions the adapter
4012    /// invokes (e.g. `realloc`). Calls to host intrinsics inside the
4013    /// barrier are compiled as plain calls, since the host turns any
4014    /// exception into a trap rather than unwinding it into the adapter.
4015    ///
4016    /// The generated structure, completed by `exit_exception_barrier`,
4017    /// is:
4018    ///
4019    /// ```wasm
4020    /// block (result ...)        ;; carries results past the handler
4021    ///   block                   ;; catch_all landing pad
4022    ///     try_table (result ...) (catch_all 0)
4023    ///       ;; ... body ...
4024    ///     end
4025    ///     br 1                  ;; done; carry results past the handler
4026    ///   end
4027    ///   ;; an exception was caught: raise a trap
4028    ///   unreachable
4029    /// end
4030    /// ```
4031    ///
4032    /// This is only done when the exceptions proposal is enabled.
4033    fn enter_exception_barrier(&mut self, results: &[ValType]) {
4034        if !self.module.features.exceptions() {
4035            return;
4036        }
4037        let block_ty = match results.len() {
4038            0 => BlockType::Empty,
4039            1 => BlockType::Result(results[0]),
4040            _ => BlockType::FunctionType(self.module.core_types.function(&[], results)),
4041        };
4042        // Outer block: carries the body's results past the handler.
4043        self.instruction(Block(block_ty));
4044        // Inner block: the landing pad targeted by the `catch_all` clause.
4045        self.instruction(Block(BlockType::Empty));
4046        self.instruction(TryTable(block_ty, vec![Catch::All { label: 0 }].into()));
4047    }
4048
4049    /// Emits the epilogue of an exception barrier started with
4050    /// `enter_exception_barrier`: the body's results jump past the
4051    /// `catch_all` landing pad, which turns a caught exception into a
4052    /// trap.
4053    fn exit_exception_barrier(&mut self) {
4054        if !self.module.features.exceptions() {
4055            return;
4056        }
4057        // End of the `try_table`.
4058        self.instruction(End);
4059        // Normal completion: jump over the handler, carrying the results.
4060        self.instruction(Br(1));
4061        // End of the inner block: the `catch_all` landing pad.
4062        self.instruction(End);
4063        self.trap(Trap::UncaughtException);
4064        // End of the outer block; the body's results flow out.
4065        self.instruction(End);
4066    }
4067
4068    /// Pushes a `Body` fragment directly to the function being created.
4069    fn push_body(&mut self, body: Body) {
4070        self.flush_code();
4071        self.module.funcs[self.result].body.push(body);
4072    }
4073
4074    /// Flushes out the current `code` instructions into the destination
4075    /// function.
4076    ///
4077    /// This is a noop if no instructions have been encoded yet.
4078    fn flush_code(&mut self) {
4079        if self.code.is_empty() {
4080            return;
4081        }
4082        self.module.funcs[self.result]
4083            .body
4084            .push(Body::Raw(mem::take(&mut self.code)));
4085    }
4086
4087    fn finish(mut self) {
4088        // Append the final `end` instruction which all functions require, and
4089        // then empty out the temporary buffer in `Compiler`.
4090        self.instruction(End);
4091        self.flush_code();
4092
4093        // Flag the function as "done" which helps with an assert later on in
4094        // emission that everything was eventually finished.
4095        self.module.funcs[self.result].filled_in = true;
4096    }
4097
4098    /// Fetches the value contained with the local specified by `stack` and
4099    /// converts it to `dst_ty`.
4100    ///
4101    /// This is only intended for use in primitive operations where `stack` is
4102    /// guaranteed to have only one local. The type of the local on the stack is
4103    /// then converted to `dst_ty` appropriately. Note that the types may be
4104    /// different due to the "flattening" of variant types.
4105    fn stack_get(&mut self, stack: &Stack<'_>, dst_ty: ValType) {
4106        assert_eq!(stack.locals.len(), 1);
4107        let (idx, src_ty) = stack.locals[0];
4108        self.instruction(LocalGet(idx));
4109        match (src_ty, dst_ty) {
4110            (ValType::I32, ValType::I32)
4111            | (ValType::I64, ValType::I64)
4112            | (ValType::F32, ValType::F32)
4113            | (ValType::F64, ValType::F64) => {}
4114
4115            (ValType::I32, ValType::F32) => self.instruction(F32ReinterpretI32),
4116            (ValType::I64, ValType::I32) => {
4117                self.assert_i64_upper_bits_not_set(idx);
4118                self.instruction(I32WrapI64);
4119            }
4120            (ValType::I64, ValType::F64) => self.instruction(F64ReinterpretI64),
4121            (ValType::I64, ValType::F32) => {
4122                self.assert_i64_upper_bits_not_set(idx);
4123                self.instruction(I32WrapI64);
4124                self.instruction(F32ReinterpretI32);
4125            }
4126
4127            // should not be possible given the `join` function for variants
4128            (ValType::I32, ValType::I64)
4129            | (ValType::I32, ValType::F64)
4130            | (ValType::F32, ValType::I32)
4131            | (ValType::F32, ValType::I64)
4132            | (ValType::F32, ValType::F64)
4133            | (ValType::F64, ValType::I32)
4134            | (ValType::F64, ValType::I64)
4135            | (ValType::F64, ValType::F32)
4136
4137            // not used in the component model
4138            | (ValType::Ref(_), _)
4139            | (_, ValType::Ref(_))
4140            | (ValType::V128, _)
4141            | (_, ValType::V128) => {
4142                panic!("cannot get {dst_ty:?} from {src_ty:?} local");
4143            }
4144        }
4145    }
4146
4147    fn assert_i64_upper_bits_not_set(&mut self, local: u32) {
4148        if !self.module.tunables.debug_adapter_modules {
4149            return;
4150        }
4151        self.instruction(LocalGet(local));
4152        self.instruction(I64Const(32));
4153        self.instruction(I64ShrU);
4154        self.instruction(I32WrapI64);
4155        self.instruction(If(BlockType::Empty));
4156        self.trap(Trap::DebugAssertUpperBitsUnset);
4157        self.instruction(End);
4158    }
4159
4160    /// Converts the top value on the WebAssembly stack which has type
4161    /// `src_ty` to `dst_tys[0]`.
4162    ///
4163    /// This is only intended for conversion of primitives where the `dst_tys`
4164    /// list is known to be of length 1.
4165    fn stack_set(&mut self, dst_tys: &[ValType], src_ty: ValType) {
4166        assert_eq!(dst_tys.len(), 1);
4167        let dst_ty = dst_tys[0];
4168        match (src_ty, dst_ty) {
4169            (ValType::I32, ValType::I32)
4170            | (ValType::I64, ValType::I64)
4171            | (ValType::F32, ValType::F32)
4172            | (ValType::F64, ValType::F64) => {}
4173
4174            (ValType::F32, ValType::I32) => self.instruction(I32ReinterpretF32),
4175            (ValType::I32, ValType::I64) => self.instruction(I64ExtendI32U),
4176            (ValType::F64, ValType::I64) => self.instruction(I64ReinterpretF64),
4177            (ValType::F32, ValType::I64) => {
4178                self.instruction(I32ReinterpretF32);
4179                self.instruction(I64ExtendI32U);
4180            }
4181
4182            // should not be possible given the `join` function for variants
4183            (ValType::I64, ValType::I32)
4184            | (ValType::F64, ValType::I32)
4185            | (ValType::I32, ValType::F32)
4186            | (ValType::I64, ValType::F32)
4187            | (ValType::F64, ValType::F32)
4188            | (ValType::I32, ValType::F64)
4189            | (ValType::I64, ValType::F64)
4190            | (ValType::F32, ValType::F64)
4191
4192            // not used in the component model
4193            | (ValType::Ref(_), _)
4194            | (_, ValType::Ref(_))
4195            | (ValType::V128, _)
4196            | (_, ValType::V128) => {
4197                panic!("cannot get {dst_ty:?} from {src_ty:?} local");
4198            }
4199        }
4200    }
4201
4202    fn i32_load8u(&mut self, mem: &Memory) {
4203        self.instruction(LocalGet(mem.addr.idx));
4204        self.instruction(I32Load8U(mem.memarg(0)));
4205    }
4206
4207    fn i32_load8s(&mut self, mem: &Memory) {
4208        self.instruction(LocalGet(mem.addr.idx));
4209        self.instruction(I32Load8S(mem.memarg(0)));
4210    }
4211
4212    fn i32_load16u(&mut self, mem: &Memory) {
4213        self.instruction(LocalGet(mem.addr.idx));
4214        self.instruction(I32Load16U(mem.memarg(1)));
4215    }
4216
4217    fn i32_load16s(&mut self, mem: &Memory) {
4218        self.instruction(LocalGet(mem.addr.idx));
4219        self.instruction(I32Load16S(mem.memarg(1)));
4220    }
4221
4222    fn i32_load(&mut self, mem: &Memory) {
4223        self.instruction(LocalGet(mem.addr.idx));
4224        self.instruction(I32Load(mem.memarg(2)));
4225    }
4226
4227    fn i64_load(&mut self, mem: &Memory) {
4228        self.instruction(LocalGet(mem.addr.idx));
4229        self.instruction(I64Load(mem.memarg(3)));
4230    }
4231
4232    fn ptr_load(&mut self, mem: &Memory) {
4233        if mem.mem_opts().memory64() {
4234            self.i64_load(mem);
4235        } else {
4236            self.i32_load(mem);
4237        }
4238    }
4239
4240    fn ptr_add(&mut self, opts: &LinearMemoryOptions) {
4241        if opts.memory64() {
4242            self.instruction(I64Add);
4243        } else {
4244            self.instruction(I32Add);
4245        }
4246    }
4247
4248    fn ptr_sub(&mut self, opts: &LinearMemoryOptions) {
4249        if opts.memory64() {
4250            self.instruction(I64Sub);
4251        } else {
4252            self.instruction(I32Sub);
4253        }
4254    }
4255
4256    fn ptr_mul(&mut self, opts: &LinearMemoryOptions) {
4257        if opts.memory64() {
4258            self.instruction(I64Mul);
4259        } else {
4260            self.instruction(I32Mul);
4261        }
4262    }
4263
4264    fn ptr_gt_u(&mut self, opts: &LinearMemoryOptions) {
4265        if opts.memory64() {
4266            self.instruction(I64GtU);
4267        } else {
4268            self.instruction(I32GtU);
4269        }
4270    }
4271
4272    fn ptr_lt_u(&mut self, opts: &LinearMemoryOptions) {
4273        if opts.memory64() {
4274            self.instruction(I64LtU);
4275        } else {
4276            self.instruction(I32LtU);
4277        }
4278    }
4279
4280    fn ptr_shl(&mut self, opts: &LinearMemoryOptions) {
4281        if opts.memory64() {
4282            self.instruction(I64Shl);
4283        } else {
4284            self.instruction(I32Shl);
4285        }
4286    }
4287
4288    fn ptr_eqz(&mut self, opts: &LinearMemoryOptions) {
4289        if opts.memory64() {
4290            self.instruction(I64Eqz);
4291        } else {
4292            self.instruction(I32Eqz);
4293        }
4294    }
4295
4296    fn ptr_uconst(&mut self, opts: &LinearMemoryOptions, val: u32) {
4297        if opts.memory64() {
4298            self.instruction(I64Const(val.into()));
4299        } else {
4300            self.instruction(I32Const(val.cast_signed()));
4301        }
4302    }
4303
4304    /// Pushes the `latin1+utf16` utf16 tag for `opts`'s memory.
4305    fn ptr_utf16_tag(&mut self, opts: &LinearMemoryOptions) {
4306        if opts.memory64() {
4307            self.instruction(I64Const(i64::MIN));
4308        } else {
4309            self.instruction(I32Const(i32::MIN));
4310        }
4311    }
4312
4313    /// Pushes the mask that clears `ptr_utf16_tag` for `opts`'s memory.
4314    fn ptr_utf16_untag_mask(&mut self, opts: &LinearMemoryOptions) {
4315        if opts.memory64() {
4316            self.instruction(I64Const(i64::MAX));
4317        } else {
4318            self.instruction(I32Const(i32::MAX));
4319        }
4320    }
4321
4322    fn ptr_iconst(&mut self, opts: &LinearMemoryOptions, val: i32) {
4323        if opts.memory64() {
4324            self.instruction(I64Const(val.into()));
4325        } else {
4326            self.instruction(I32Const(val));
4327        }
4328    }
4329
4330    fn ptr_eq(&mut self, opts: &LinearMemoryOptions) {
4331        if opts.memory64() {
4332            self.instruction(I64Eq);
4333        } else {
4334            self.instruction(I32Eq);
4335        }
4336    }
4337
4338    fn ptr_ne(&mut self, opts: &LinearMemoryOptions) {
4339        if opts.memory64() {
4340            self.instruction(I64Ne);
4341        } else {
4342            self.instruction(I32Ne);
4343        }
4344    }
4345
4346    fn ptr_and(&mut self, opts: &LinearMemoryOptions) {
4347        if opts.memory64() {
4348            self.instruction(I64And);
4349        } else {
4350            self.instruction(I32And);
4351        }
4352    }
4353
4354    fn ptr_or(&mut self, opts: &LinearMemoryOptions) {
4355        if opts.memory64() {
4356            self.instruction(I64Or);
4357        } else {
4358            self.instruction(I32Or);
4359        }
4360    }
4361
4362    fn ptr_xor(&mut self, opts: &LinearMemoryOptions) {
4363        if opts.memory64() {
4364            self.instruction(I64Xor);
4365        } else {
4366            self.instruction(I32Xor);
4367        }
4368    }
4369
4370    fn ptr_if(&mut self, opts: &LinearMemoryOptions, ty: BlockType) {
4371        if opts.memory64() {
4372            self.instruction(I64Const(0));
4373            self.instruction(I64Ne);
4374        }
4375        self.instruction(If(ty));
4376    }
4377
4378    fn ptr_br_if(&mut self, opts: &LinearMemoryOptions, depth: u32) {
4379        if opts.memory64() {
4380            self.instruction(I64Const(0));
4381            self.instruction(I64Ne);
4382        }
4383        self.instruction(BrIf(depth));
4384    }
4385
4386    fn f32_load(&mut self, mem: &Memory) {
4387        self.instruction(LocalGet(mem.addr.idx));
4388        self.instruction(F32Load(mem.memarg(2)));
4389    }
4390
4391    fn f64_load(&mut self, mem: &Memory) {
4392        self.instruction(LocalGet(mem.addr.idx));
4393        self.instruction(F64Load(mem.memarg(3)));
4394    }
4395
4396    fn push_dst_addr(&mut self, dst: &Destination) {
4397        if let Destination::Memory(mem) = dst {
4398            self.instruction(LocalGet(mem.addr.idx));
4399        }
4400    }
4401
4402    fn i32_store8(&mut self, mem: &Memory) {
4403        self.instruction(I32Store8(mem.memarg(0)));
4404    }
4405
4406    fn i32_store16(&mut self, mem: &Memory) {
4407        self.instruction(I32Store16(mem.memarg(1)));
4408    }
4409
4410    fn i32_store(&mut self, mem: &Memory) {
4411        self.instruction(I32Store(mem.memarg(2)));
4412    }
4413
4414    fn i64_store(&mut self, mem: &Memory) {
4415        self.instruction(I64Store(mem.memarg(3)));
4416    }
4417
4418    fn ptr_store(&mut self, mem: &Memory) {
4419        if mem.mem_opts().memory64() {
4420            self.i64_store(mem);
4421        } else {
4422            self.i32_store(mem);
4423        }
4424    }
4425
4426    fn f32_store(&mut self, mem: &Memory) {
4427        self.instruction(F32Store(mem.memarg(2)));
4428    }
4429
4430    fn f64_store(&mut self, mem: &Memory) {
4431        self.instruction(F64Store(mem.memarg(3)));
4432    }
4433
4434    /// Push a pointer-typed value for `opts` on the wasm stack representing
4435    /// the `size` passed in.
4436    fn alloc_size(&mut self, opts: &LinearMemoryOptions, size: &AllocSize) {
4437        match size {
4438            AllocSize::Const(size) => self.ptr_uconst(opts, *size),
4439            AllocSize::Local(idx) => self.instruction(LocalGet(*idx)),
4440            AllocSize::DoubleLocal(idx) => {
4441                self.instruction(LocalGet(*idx));
4442                self.ptr_uconst(opts, 1);
4443                self.ptr_shl(opts);
4444            }
4445        }
4446    }
4447}
4448
4449impl<'a> Source<'a> {
4450    /// Given this `Source` returns an iterator over the `Source` for each of
4451    /// the component `fields` specified.
4452    ///
4453    /// This will automatically slice stack-based locals to the appropriate
4454    /// width for each component type and additionally calculate the appropriate
4455    /// offset for each memory-based type.
4456    fn record_field_srcs<'b>(
4457        &'b self,
4458        types: &'b ComponentTypesBuilder,
4459        fields: impl IntoIterator<Item = InterfaceType> + 'b,
4460    ) -> impl Iterator<Item = Source<'a>> + 'b
4461    where
4462        'a: 'b,
4463    {
4464        let mut offset = 0;
4465        fields.into_iter().map(move |ty| match self {
4466            Source::Memory(mem) => {
4467                let mem = next_field_offset(&mut offset, types, &ty, mem);
4468                Source::Memory(mem)
4469            }
4470            Source::Stack(stack) => {
4471                let cnt = types.flat_types(&ty).unwrap().len() as u32;
4472                offset += cnt;
4473                Source::Stack(stack.slice((offset - cnt) as usize..offset as usize))
4474            }
4475            Source::Struct(_) => todo!(),
4476            Source::Array(_) => todo!(),
4477        })
4478    }
4479
4480    /// Returns the corresponding discriminant source and payload source f
4481    fn payload_src(
4482        &self,
4483        types: &ComponentTypesBuilder,
4484        info: &VariantInfo,
4485        case: Option<&InterfaceType>,
4486    ) -> Source<'a> {
4487        match self {
4488            Source::Stack(s) => {
4489                let flat_len = match case {
4490                    Some(case) => types.flat_types(case).unwrap().len(),
4491                    None => 0,
4492                };
4493                Source::Stack(s.slice(1..s.locals.len()).slice(0..flat_len))
4494            }
4495            Source::Memory(mem) => {
4496                let mem = if mem.mem_opts().memory64() {
4497                    mem.bump(info.payload_offset64)
4498                } else {
4499                    mem.bump(info.payload_offset32)
4500                };
4501                Source::Memory(mem)
4502            }
4503            Source::Struct(_) | Source::Array(_) => todo!("CM+GC"),
4504        }
4505    }
4506
4507    fn opts(&self) -> &'a Options {
4508        match self {
4509            Source::Stack(s) => s.opts,
4510            Source::Memory(mem) => mem.opts,
4511            Source::Struct(s) => s.opts,
4512            Source::Array(a) => a.opts,
4513        }
4514    }
4515}
4516
4517impl<'a> Destination<'a> {
4518    /// Same as `Source::record_field_srcs` but for destinations.
4519    fn record_field_dsts<'b, I>(
4520        &'b self,
4521        types: &'b ComponentTypesBuilder,
4522        fields: I,
4523    ) -> impl Iterator<Item = Destination<'b>> + use<'b, I>
4524    where
4525        'a: 'b,
4526        I: IntoIterator<Item = InterfaceType> + 'b,
4527    {
4528        let mut offset = 0;
4529        fields.into_iter().map(move |ty| match self {
4530            Destination::Memory(mem) => {
4531                let mem = next_field_offset(&mut offset, types, &ty, mem);
4532                Destination::Memory(mem)
4533            }
4534            Destination::Stack(s, opts) => {
4535                let cnt = types.flat_types(&ty).unwrap().len() as u32;
4536                offset += cnt;
4537                Destination::Stack(&s[(offset - cnt) as usize..offset as usize], opts)
4538            }
4539            Destination::Struct(_) => todo!(),
4540            Destination::Array(_) => todo!(),
4541        })
4542    }
4543
4544    /// Returns the corresponding discriminant source and payload source f
4545    fn payload_dst(
4546        &self,
4547        types: &ComponentTypesBuilder,
4548        info: &VariantInfo,
4549        case: Option<&InterfaceType>,
4550    ) -> Destination<'_> {
4551        match self {
4552            Destination::Stack(s, opts) => {
4553                let flat_len = match case {
4554                    Some(case) => types.flat_types(case).unwrap().len(),
4555                    None => 0,
4556                };
4557                Destination::Stack(&s[1..][..flat_len], opts)
4558            }
4559            Destination::Memory(mem) => {
4560                let mem = if mem.mem_opts().memory64() {
4561                    mem.bump(info.payload_offset64)
4562                } else {
4563                    mem.bump(info.payload_offset32)
4564                };
4565                Destination::Memory(mem)
4566            }
4567            Destination::Struct(_) | Destination::Array(_) => todo!("CM+GC"),
4568        }
4569    }
4570
4571    fn opts(&self) -> &'a Options {
4572        match self {
4573            Destination::Stack(_, opts) => opts,
4574            Destination::Memory(mem) => mem.opts,
4575            Destination::Struct(s) => s.opts,
4576            Destination::Array(a) => a.opts,
4577        }
4578    }
4579}
4580
4581fn next_field_offset<'a>(
4582    offset: &mut u32,
4583    types: &ComponentTypesBuilder,
4584    field: &InterfaceType,
4585    mem: &Memory<'a>,
4586) -> Memory<'a> {
4587    let abi = types.canonical_abi(field);
4588    let offset = if mem.mem_opts().memory64() {
4589        abi.next_field64(offset)
4590    } else {
4591        abi.next_field32(offset)
4592    };
4593    mem.bump(offset)
4594}
4595
4596impl<'a> Memory<'a> {
4597    fn memarg(&self, align: u32) -> MemArg {
4598        MemArg {
4599            offset: u64::from(self.offset),
4600            align,
4601            target: MemArgTarget::Memory(self.mem_opts().memory.unwrap().0.as_u32()),
4602            ordering: None,
4603        }
4604    }
4605
4606    fn bump(&self, offset: u32) -> Memory<'a> {
4607        Memory {
4608            opts: self.opts,
4609            addr: TempLocal::new(self.addr.idx, self.addr.ty),
4610            offset: self.offset + offset,
4611        }
4612    }
4613}
4614
4615impl<'a> Stack<'a> {
4616    fn slice(&self, range: Range<usize>) -> Stack<'a> {
4617        Stack {
4618            locals: &self.locals[range],
4619            opts: self.opts,
4620        }
4621    }
4622}
4623
4624struct VariantCase<'a> {
4625    src_i: u32,
4626    src_ty: Option<&'a InterfaceType>,
4627    dst_i: u32,
4628    dst_ty: Option<&'a InterfaceType>,
4629}
4630
4631fn variant_info<'a, I>(types: &ComponentTypesBuilder, cases: I) -> VariantInfo
4632where
4633    I: IntoIterator<Item = Option<&'a InterfaceType>>,
4634    I::IntoIter: ExactSizeIterator,
4635{
4636    VariantInfo::new(
4637        cases
4638            .into_iter()
4639            .map(|ty| ty.map(|ty| types.canonical_abi(ty))),
4640    )
4641    .0
4642}
4643
4644/// State for the iteration loop inside a sequence translation.
4645struct SequenceLoopState {
4646    remaining: TempLocal,
4647    cur_src_ptr: TempLocal,
4648    cur_dst_ptr: TempLocal,
4649}
4650
4651/// Holds all temporaries created by `begin_translate_sequence` so the
4652/// caller can emit a custom loop body before calling
4653/// `end_translate_sequence`.
4654struct SequenceTranslation<'a> {
4655    src_len: TempLocal,
4656    src_mem: Memory<'a>,
4657    dst_mem: Memory<'a>,
4658    src_opts: &'a Options,
4659    dst_opts: &'a Options,
4660    src_mem_opts: &'a LinearMemoryOptions,
4661    dst_mem_opts: &'a LinearMemoryOptions,
4662    loop_state: Option<SequenceLoopState>,
4663}
4664
4665enum AllocSize {
4666    Const(u32),
4667    Local(u32),
4668    DoubleLocal(u32),
4669}
4670
4671struct WasmString<'a> {
4672    ptr: TempLocal,
4673    len: TempLocal,
4674    opts: &'a Options,
4675}
4676
4677struct TempLocal {
4678    idx: u32,
4679    ty: ValType,
4680    needs_free: bool,
4681}
4682
4683impl TempLocal {
4684    fn new(idx: u32, ty: ValType) -> TempLocal {
4685        TempLocal {
4686            idx,
4687            ty,
4688            needs_free: false,
4689        }
4690    }
4691}
4692
4693impl std::ops::Drop for TempLocal {
4694    fn drop(&mut self) {
4695        if self.needs_free {
4696            panic!("temporary local not free'd");
4697        }
4698    }
4699}
4700
4701impl From<FlatType> for ValType {
4702    fn from(ty: FlatType) -> ValType {
4703        match ty {
4704            FlatType::I32 => ValType::I32,
4705            FlatType::I64 => ValType::I64,
4706            FlatType::F32 => ValType::F32,
4707            FlatType::F64 => ValType::F64,
4708        }
4709    }
4710}