1use 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
47const 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 code: Vec<u8>,
58
59 nlocals: u32,
61
62 free_locals: HashMap<ValType, Vec<u32>>,
64
65 fuel: usize,
74
75 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 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 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 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 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 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 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
215pub(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 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 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 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 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 emit_resource_call: false,
293 };
294 compiler.translate(&helper.src.ty, &src, &helper.dst.ty, &dst);
295 compiler.finish();
296}
297
298enum Source<'a> {
301 Stack(Stack<'a>),
307
308 Memory(Memory<'a>),
311
312 #[allow(dead_code, reason = "CM+GC is still WIP")]
315 Struct(GcStruct<'a>),
316
317 #[allow(dead_code, reason = "CM+GC is still WIP")]
320 Array(GcArray<'a>),
321}
322
323enum Destination<'a> {
325 Stack(&'a [ValType], &'a Options),
331
332 Memory(Memory<'a>),
334
335 #[allow(dead_code, reason = "CM+GC is still WIP")]
338 Struct(GcStruct<'a>),
339
340 #[allow(dead_code, reason = "CM+GC is still WIP")]
343 Array(GcArray<'a>),
344}
345
346struct Stack<'a> {
347 locals: &'a [(u32, ValType)],
353 opts: &'a Options,
355}
356
357struct Memory<'a> {
359 opts: &'a Options,
361 addr: TempLocal,
364 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
375struct GcStruct<'a> {
377 opts: &'a Options,
378 }
380
381struct GcArray<'a> {
383 opts: &'a Options,
384 }
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 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 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 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 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 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 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 fn compile_async_start_adapter(mut self, adapter: &AdapterData, sig: &Signature) {
563 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, ¶m_locals);
579 if let Some(saved) = saved {
580 self.restore_may_leave(adapter.lift.flags, saved);
581 }
582
583 self.finish();
584 }
585
586 fn compile_async_return_adapter(mut self, adapter: &AdapterData, sig: &Signature) {
595 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 self.translate_results(adapter, ¶m_locals, ¶m_locals);
619 if let Some(saved) = saved {
620 self.restore_may_leave(adapter.lower.flags, saved);
621 }
622
623 self.finish()
624 }
625
626 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 let saved_lower_may_leave =
650 self.trap_if_not_may_leave(adapter.lower.flags, Trap::CannotLeaveComponent);
651
652 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 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 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, ¶m_locals);
743 if let Some(saved) = saved_lift_may_leave {
744 self.restore_may_leave(adapter.lift.flags, saved);
745 }
746
747 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 let callee_context = if adapter.lift.post_return.is_some() {
766 self.save_context()
767 } else {
768 Vec::new()
769 };
770
771 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 if self.translate_results_may_call_lower_realloc(adapter) {
799 self.set_may_leave_false(adapter.lower.flags);
800 self.translate_results(adapter, ¶m_locals, &result_locals);
801 self.restore_may_leave(adapter.lower.flags, saved_lower_may_leave);
802 } else {
803 self.translate_results(adapter, ¶m_locals, &result_locals);
804 self.free_temp_local(saved_lower_may_leave);
805 }
806
807 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 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 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 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 assert_eq!(src_tys.len(), dst_tys.len());
888
889 let max_flat_params = match lower_opts.data_model {
893 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: ¶m_locals[..flat.len()],
911 opts: lower_opts,
912 })
913 } else {
914 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 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 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 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 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 let cost = match src_ty {
1087 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 InterfaceType::Char => 1,
1105
1106 InterfaceType::String => 40,
1109
1110 InterfaceType::List(_) => 40,
1113 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 InterfaceType::Option(_) | InterfaceType::Result(_) => 2,
1132
1133 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 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 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 None => {
1204 let src_loc = match src {
1205 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 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 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 self.push_body(Body::Call(helper));
1259
1260 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 assert!(matches!(dst_ty, InterfaceType::Bool));
1300 self.push_dst_addr(dst);
1301
1302 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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)); 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 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 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 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 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)); self.instruction(Call(transcode.as_u32()));
2024
2025 self.instruction(LocalGet(dst.len.idx));
2029 self.ptr_add(dst_mem_opts);
2030 self.instruction(LocalSet(dst.len.idx));
2031
2032 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 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 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); self.free_temp_local(src_len_tmp);
2077 self.free_temp_local(dst_byte_len);
2078
2079 dst
2080 }
2081
2082 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 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); self.free_temp_local(dst_byte_len);
2163
2164 dst
2165 }
2166
2167 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 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 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 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 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 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 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)); 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 self.instruction(Else); if src_enc.width() == 1 {
2355 self.validate_string_length_u8(src, 2);
2356 }
2357
2358 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 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 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 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); 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 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 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 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 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 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 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 let loop_state = if src_element_size > 0 || dst_element_size > 0 {
2577 self.instruction(Block(BlockType::Empty));
2578
2579 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 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 fn end_translate_sequence(&mut self, seq: SequenceTranslation<'_>, dst: &Destination) {
2620 if let Some(loop_state) = seq.loop_state {
2621 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); self.instruction(End); 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 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 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 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 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 if elt_size == 0 {
2843 self.ptr_uconst(opts, 0);
2844 return self.local_set_new_tmp(opts.ptr());
2845 }
2846
2847 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 self.instruction(Block(BlockType::Empty));
2873 self.instruction(Block(BlockType::Empty));
2874 self.instruction(LocalGet(len_local));
2875 match opts.ptr() {
2876 ValType::I32 => self.instruction(I64ExtendI32U),
2880
2881 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 self.instruction(I64Const(elt_size.into()));
2904 self.instruction(I64Mul);
2905 let tmp = self.local_tee_new_tmp(ValType::I64);
2906 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 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 assert_eq!(src_ty.fields.len(), dst_ty.fields.len());
2958
2959 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 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 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 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 assert_eq!(src_ty.size, dst_ty.size);
3079
3080 match (&src, &dst) {
3081 (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 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 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 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 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); 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 (_, _) => {
3159 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 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 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 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 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 let src_cases_len = src_cases.len();
3383 for _ in 0..src_cases_len - 1 {
3384 self.instruction(Block(BlockType::Empty));
3385 }
3386
3387 self.instruction(Block(BlockType::Empty));
3389
3390 self.instruction(Block(BlockType::Empty));
3393
3394 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 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); self.trap(Trap::InvalidDiscriminant);
3415 self.instruction(End); 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 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 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 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 if src_i != src_cases_len - 1 {
3481 self.instruction(Br(src_cases_len - src_i - 1));
3482 }
3483 self.instruction(End); }
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 fn local_tee_new_tmp(&mut self, ty: ValType) -> TempLocal {
3889 self.gen_temp_local(ty, LocalTee)
3890 }
3891
3892 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 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 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 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 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 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 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 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 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 self.instruction(Block(block_ty));
4044 self.instruction(Block(BlockType::Empty));
4046 self.instruction(TryTable(block_ty, vec![Catch::All { label: 0 }].into()));
4047 }
4048
4049 fn exit_exception_barrier(&mut self) {
4054 if !self.module.features.exceptions() {
4055 return;
4056 }
4057 self.instruction(End);
4059 self.instruction(Br(1));
4061 self.instruction(End);
4063 self.trap(Trap::UncaughtException);
4064 self.instruction(End);
4066 }
4067
4068 fn push_body(&mut self, body: Body) {
4070 self.flush_code();
4071 self.module.funcs[self.result].body.push(body);
4072 }
4073
4074 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 self.instruction(End);
4091 self.flush_code();
4092
4093 self.module.funcs[self.result].filled_in = true;
4096 }
4097
4098 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 (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 | (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 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 (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 | (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 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 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 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 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 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 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 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
4644struct SequenceLoopState {
4646 remaining: TempLocal,
4647 cur_src_ptr: TempLocal,
4648 cur_dst_ptr: TempLocal,
4649}
4650
4651struct 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}